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 hausd = 0.01 146 self.plex.metricSetIsotropic(False) 147 self.plex.metricSetRestrictAnisotropyFirst(False) 148 self.plex.metricSetNoInsertion(False) 149 self.plex.metricSetNoSwapping(False) 150 self.plex.metricSetNoMovement(False) 151 self.plex.metricSetVerbosity(-1) 152 self.plex.metricSetNumIterations(3) 153 self.plex.metricSetMinimumMagnitude(h_min) 154 self.plex.metricSetMaximumMagnitude(h_max) 155 self.plex.metricSetMaximumAnisotropy(a_max) 156 self.plex.metricSetTargetComplexity(target) 157 self.plex.metricSetNormalizationOrder(p) 158 self.plex.metricSetGradationFactor(beta) 159 self.plex.metricSetHausdorffNumber(hausd) 160 161 self.assertFalse(self.plex.metricIsIsotropic()) 162 self.assertFalse(self.plex.metricRestrictAnisotropyFirst()) 163 self.assertFalse(self.plex.metricNoInsertion()) 164 self.assertFalse(self.plex.metricNoSwapping()) 165 self.assertFalse(self.plex.metricNoMovement()) 166 assert self.plex.metricGetVerbosity() == -1 167 assert self.plex.metricGetNumIterations() == 3 168 assert np.isclose(self.plex.metricGetMinimumMagnitude(), h_min) 169 assert np.isclose(self.plex.metricGetMaximumMagnitude(), h_max) 170 assert np.isclose(self.plex.metricGetMaximumAnisotropy(), a_max) 171 assert np.isclose(self.plex.metricGetTargetComplexity(), target) 172 assert np.isclose(self.plex.metricGetNormalizationOrder(), p) 173 assert np.isclose(self.plex.metricGetGradationFactor(), beta) 174 assert np.isclose(self.plex.metricGetHausdorffNumber(), hausd) 175 176 metric1 = self.plex.metricCreateUniform(1.0) 177 metric2 = self.plex.metricCreateUniform(2.0) 178 metric = self.plex.metricAverage2(metric1, metric2) 179 metric2.array[:] *= 0.75 180 assert np.allclose(metric.array, metric2.array) 181 metric = self.plex.metricIntersection2(metric1, metric2) 182 assert np.allclose(metric.array, metric1.array) 183 metric = self.plex.metricEnforceSPD(metric) 184 assert np.allclose(metric.array, metric1.array) 185 nMetric = self.plex.metricNormalize(metric, restrictSizes=False, restrictAnisotropy=False) 186 metric.scale(pow(target, 2.0/self.DIM)) 187 assert np.allclose(metric.array, nMetric.array) 188 189 def testAdapt(self): 190 if self.DIM == 1: return 191 self.plex.orient() 192 plex = self.plex.refine() 193 plex.distribute() 194 if self.CELLS is None and not plex.isSimplex(): return 195 if sum(self.DOFS) > 1: return 196 metric = plex.metricCreateUniform(9.0) 197 try: 198 newplex = plex.adaptMetric(metric,"") 199 except PETSc.Error as exc: 200 if exc.ierr != ERR_ARG_OUTOFRANGE: raise 201 202 203# -------------------------------------------------------------------- 204 205class BaseTestPlex_2D(BaseTestPlex): 206 DIM = 2 207 CELLS = [[0, 1, 3], [1, 3, 4], [1, 2, 4], [2, 4, 5], 208 [3, 4, 6], [4, 6, 7], [4, 5, 7], [5, 7, 8]] 209 COORDS = [[0.0, 0.0], [0.5, 0.0], [1.0, 0.0], 210 [0.0, 0.5], [0.5, 0.5], [1.0, 0.5], 211 [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]] 212 DOFS = [1, 0, 0] 213 214class BaseTestPlex_3D(BaseTestPlex): 215 DIM = 3 216 CELLS = [[0, 2, 3, 7], [0, 2, 6, 7], [0, 4, 6, 7], 217 [0, 1, 3, 7], [0, 1, 5, 7], [0, 4, 5, 7]] 218 COORDS = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.], 219 [0., 0., 1.], [1., 0., 1.], [0., 1., 1.], [1., 1., 1.]] 220 DOFS = [1, 0, 0, 0] 221 222# -------------------------------------------------------------------- 223 224class TestPlex_1D(BaseTestPlex, unittest.TestCase): 225 pass 226 227class TestPlex_2D(BaseTestPlex_2D, unittest.TestCase): 228 pass 229 230class TestPlex_3D(BaseTestPlex_3D, unittest.TestCase): 231 pass 232 233class TestPlex_2D_P3(BaseTestPlex_2D, unittest.TestCase): 234 DOFS = [1, 2, 1] 235 236class TestPlex_3D_P3(BaseTestPlex_3D, unittest.TestCase): 237 DOFS = [1, 2, 1, 0] 238 239class TestPlex_3D_P4(BaseTestPlex_3D, unittest.TestCase): 240 DOFS = [1, 3, 3, 1] 241 242class TestPlex_2D_BoxTensor(BaseTestPlex_2D, unittest.TestCase): 243 CELLS = None 244 COORDS = None 245 def setUp(self): 246 self.plex = PETSc.DMPlex().createBoxMesh([3,3], simplex=False) 247 248class TestPlex_3D_BoxTensor(BaseTestPlex_3D, unittest.TestCase): 249 CELLS = None 250 COORDS = None 251 def setUp(self): 252 self.plex = PETSc.DMPlex().createBoxMesh([3,3,3], simplex=False) 253 254try: 255 raise PETSc.Error 256 PETSc.DMPlex().createBoxMesh([2,2], simplex=True, comm=PETSc.COMM_SELF).destroy() 257except PETSc.Error: 258 pass 259else: 260 class TestPlex_2D_Box(BaseTestPlex_2D, unittest.TestCase): 261 CELLS = None 262 COORDS = None 263 def setUp(self): 264 self.plex = PETSc.DMPlex().createBoxMesh([1,1], simplex=True) 265 266 class TestPlex_2D_Boundary(BaseTestPlex_2D, unittest.TestCase): 267 CELLS = None 268 COORDS = None 269 def setUp(self): 270 boundary = PETSc.DMPlex().create(self.COMM) 271 boundary.createSquareBoundary([0., 0.], [1., 1.], [2, 2]) 272 boundary.setDimension(self.DIM-1) 273 self.plex = PETSc.DMPlex().generate(boundary) 274 275 class TestPlex_3D_Box(BaseTestPlex_3D, unittest.TestCase): 276 CELLS = None 277 COORDS = None 278 def setUp(self): 279 self.plex = PETSc.DMPlex().createBoxMesh([1,1,1], simplex=True) 280 281 class TestPlex_3D_Boundary(BaseTestPlex_3D, unittest.TestCase): 282 CELLS = None 283 COORDS = None 284 def setUp(self): 285 boundary = PETSc.DMPlex().create(self.COMM) 286 boundary.createCubeBoundary([0., 0., 0.], [1., 1., 1.], [1, 1, 1]) 287 boundary.setDimension(self.DIM-1) 288 self.plex = PETSc.DMPlex().generate(boundary) 289 290# -------------------------------------------------------------------- 291 292PETSC_DIR = petsc4py.get_config()['PETSC_DIR'] 293 294def check_dtype(method): 295 def wrapper(self, *args, **kwargs): 296 if PETSc.ScalarType is PETSc.ComplexType: 297 return 298 else: 299 return method(self, *args, **kwargs) 300 return wrapper 301 302def check_package(method): 303 def wrapper(self, *args, **kwargs): 304 if not PETSc.Sys.hasExternalPackage("hdf5"): 305 return 306 elif self.PARTITIONERTYPE != "simple" and \ 307 not PETSc.Sys.hasExternalPackage(self.PARTITIONERTYPE): 308 return 309 else: 310 return method(self, *args, **kwargs) 311 return wrapper 312 313def check_nsize(method): 314 def wrapper(self, *args, **kwargs): 315 if PETSc.COMM_WORLD.size != self.NSIZE: 316 return 317 else: 318 return method(self, *args, **kwargs) 319 return wrapper 320 321class BaseTestPlexHDF5(object): 322 NSIZE = 4 323 NTIMES = 3 324 325 def setUp(self): 326 self.txtvwr = PETSc.Viewer() 327 328 def tearDown(self): 329 if not PETSc.COMM_WORLD.rank: 330 if os.path.exists(self.outfile()): 331 os.remove(self.outfile()) 332 if os.path.exists(self.tmp_output_file()): 333 os.remove(self.tmp_output_file()) 334 self.txtvwr = None 335 336 def _name(self): 337 return "%s_outformat-%s_%s" % (self.SUFFIX, 338 self.OUTFORMAT, 339 self.PARTITIONERTYPE) 340 341 def infile(self): 342 return os.path.join(PETSC_DIR, "share/petsc/datafiles/", 343 "meshes/blockcylinder-50.h5") 344 345 def outfile(self): 346 return os.path.join("./temp_test_dmplex_%s.h5" % self._name()) 347 348 def informat(self): 349 return PETSc.Viewer.Format.HDF5_XDMF 350 351 def outformat(self): 352 d = {"hdf5_petsc": PETSc.Viewer.Format.HDF5_PETSC, 353 "hdf5_xdmf": PETSc.Viewer.Format.HDF5_XDMF} 354 return d[self.OUTFORMAT] 355 356 def partitionerType(self): 357 d = {"simple": PETSc.Partitioner.Type.SIMPLE, 358 "ptscotch": PETSc.Partitioner.Type.PTSCOTCH, 359 "parmetis": PETSc.Partitioner.Type.PARMETIS} 360 return d[self.PARTITIONERTYPE] 361 362 def ref_output_file(self): 363 return os.path.join(PETSC_DIR, "src/dm/impls/plex/tutorials/", 364 "output/ex5_%s.out" % self._name()) 365 366 def tmp_output_file(self): 367 return os.path.join("./temp_test_dmplex_%s.out" % self._name()) 368 369 def outputText(self, msg, comm): 370 if not comm.rank: 371 with open(self.tmp_output_file(), 'a') as f: 372 f.write(msg) 373 374 def outputPlex(self, plex): 375 self.txtvwr.createASCII(self.tmp_output_file(), 376 mode='a', comm=plex.comm) 377 plex.view(viewer=self.txtvwr) 378 self.txtvwr.destroy() 379 380 @check_dtype 381 @check_package 382 @check_nsize 383 def testViewLoadCycle(self): 384 grank = PETSc.COMM_WORLD.rank 385 for i in range(self.NTIMES): 386 if i == 0: 387 infname = self.infile() 388 informt = self.informat() 389 else: 390 infname = self.outfile() 391 informt = self.outformat() 392 if self.HETEROGENEOUS: 393 mycolor = (grank > self.NTIMES - i) 394 else: 395 mycolor = 0 396 try: 397 import mpi4py 398 except ImportError: 399 self.skipTest('mpi4py') # throws special exception to signal test skip 400 mpicomm = PETSc.COMM_WORLD.tompi4py() 401 comm = PETSc.Comm(comm=mpicomm.Split(color=mycolor, key=grank)) 402 if mycolor == 0: 403 self.outputText("Begin cycle %d\n" % i, comm) 404 plex = PETSc.DMPlex() 405 vwr = PETSc.ViewerHDF5() 406 # Create plex 407 plex.create(comm=comm) 408 plex.setName("DMPlex Object") 409 # Load data from XDMF into dm in parallel 410 vwr.create(infname, mode='r', comm=comm) 411 vwr.pushFormat(format=informt) 412 plex.load(viewer=vwr) 413 plex.setOptionsPrefix("loaded_") 414 plex.distributeSetDefault(False) 415 plex.setFromOptions() 416 vwr.popFormat() 417 vwr.destroy() 418 self.outputPlex(plex) 419 # Test DM is indeed distributed 420 flg = plex.isDistributed() 421 self.outputText("Loaded mesh distributed? %s\n" % 422 str(flg).upper(), comm) 423 # Interpolate 424 plex.interpolate() 425 plex.setOptionsPrefix("interpolated_") 426 plex.setFromOptions() 427 self.outputPlex(plex) 428 # Redistribute 429 part = plex.getPartitioner() 430 part.setType(self.partitionerType()) 431 _ = plex.distribute(overlap=0) 432 plex.setOptionsPrefix("redistributed_") 433 plex.setFromOptions() 434 self.outputPlex(plex) 435 # Save redistributed dm to XDMF in parallel 436 vwr.create(self.outfile(), mode='w', comm=comm) 437 vwr.pushFormat(format=self.outformat()) 438 plex.setName("DMPlex Object") 439 plex.view(viewer=vwr) 440 vwr.popFormat() 441 vwr.destroy() 442 # Destroy plex 443 plex.destroy() 444 self.outputText("End cycle %d\n--------\n" % i, comm) 445 PETSc.COMM_WORLD.Barrier() 446 # Check that the output is identical to that of plex/tutorial/ex5.c. 447 self.assertTrue(filecmp.cmp(self.tmp_output_file(), 448 self.ref_output_file(), shallow=False), 449 'Contents of the files not the same.') 450 PETSc.COMM_WORLD.Barrier() 451 452class BaseTestPlexHDF5Homogeneous(BaseTestPlexHDF5): 453 """Test save on N / load on N.""" 454 SUFFIX = 0 455 HETEROGENEOUS = False 456 457class BaseTestPlexHDF5Heterogeneous(BaseTestPlexHDF5): 458 """Test save on N / load on M.""" 459 SUFFIX = 1 460 HETEROGENEOUS = True 461 462class TestPlexHDF5PETSCSimpleHomogeneous(BaseTestPlexHDF5Homogeneous, 463 unittest.TestCase): 464 OUTFORMAT = "hdf5_petsc" 465 PARTITIONERTYPE = "simple" 466 467""" 468Skipping. PTScotch produces different distributions when run 469in a sequence in a single session. 470 471class TestPlexHDF5PETSCPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous, 472 unittest.TestCase): 473 OUTFORMAT = "hdf5_petsc" 474 PARTITIONERTYPE = "ptscotch" 475""" 476 477class TestPlexHDF5PETSCParmetisHomogeneous(BaseTestPlexHDF5Homogeneous, 478 unittest.TestCase): 479 OUTFORMAT = "hdf5_petsc" 480 PARTITIONERTYPE = "parmetis" 481 482class TestPlexHDF5XDMFSimpleHomogeneous(BaseTestPlexHDF5Homogeneous, 483 unittest.TestCase): 484 OUTFORMAT = "hdf5_xdmf" 485 PARTITIONERTYPE = "simple" 486 487""" 488Skipping. PTScotch produces different distributions when run 489in a sequence in a single session. 490 491class TestPlexHDF5XDMFPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous, 492 unittest.TestCase): 493 OUTFORMAT = "hdf5_xdmf" 494 PARTITIONERTYPE = "ptscotch" 495""" 496 497class TestPlexHDF5XDMFParmetisHomogeneous(BaseTestPlexHDF5Homogeneous, 498 unittest.TestCase): 499 OUTFORMAT = "hdf5_xdmf" 500 PARTITIONERTYPE = "parmetis" 501 502class TestPlexHDF5PETSCSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous, 503 unittest.TestCase): 504 OUTFORMAT = "hdf5_petsc" 505 PARTITIONERTYPE = "simple" 506 507""" 508Skipping. PTScotch produces different distributions when run 509in a sequence in a single session. 510 511class TestPlexHDF5PETSCPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous, 512 unittest.TestCase): 513 OUTFORMAT = "hdf5_petsc" 514 PARTITIONERTYPE = "ptscotch" 515""" 516 517class TestPlexHDF5PETSCParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous, 518 unittest.TestCase): 519 OUTFORMAT = "hdf5_petsc" 520 PARTITIONERTYPE = "parmetis" 521 522class TestPlexHDF5XDMFSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous, 523 unittest.TestCase): 524 OUTFORMAT = "hdf5_xdmf" 525 PARTITIONERTYPE = "simple" 526 527class TestPlexHDF5XDMFPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous, 528 unittest.TestCase): 529 OUTFORMAT = "hdf5_xdmf" 530 PARTITIONERTYPE = "ptscotch" 531 532class TestPlexHDF5XDMFParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous, 533 unittest.TestCase): 534 OUTFORMAT = "hdf5_xdmf" 535 PARTITIONERTYPE = "parmetis" 536 537# -------------------------------------------------------------------- 538 539if __name__ == '__main__': 540 unittest.main() 541