##
## ------------------------------------------------------------------------
-__doc__ = 'PyDealII is just an empty shell. You need to either\n\
+__doc__ = "PyDealII is just an empty shell. You need to either\n\
import PyDealII.Debug or PyDealII.Release. Do not\n\
- import both of them.'
+ import both of them."
except ImportError:
from PyDealII.Release import *
-class TestCellAccessorWrapper(unittest.TestCase):
+class TestCellAccessorWrapper(unittest.TestCase):
def setUp(self):
- self.triangulation = Triangulation('2D')
+ self.triangulation = Triangulation("2D")
self.triangulation.generate_hyper_cube()
self.triangulation.refine_global(1)
def test_at_boundary(self):
for cell in self.triangulation.active_cells():
- self.assertEqual(cell.at_boundary(), cell.has_boundary_lines())
+ self.assertEqual(cell.at_boundary(), cell.has_boundary_lines())
def test_faces(self):
n_neighbors = 0
def test_refine_flag(self):
index = 0
- refine_flags = ['no_refinement', 'cut_x', 'cut_y', 'cut_xy']
+ refine_flags = ["no_refinement", "cut_x", "cut_y", "cut_xy"]
for cell in self.triangulation.active_cells():
cell.refine_flag = refine_flags[index]
index += 1
index += 1
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
except ImportError:
from PyDealII.Release import *
-class TestManifoldWrapperShell(unittest.TestCase):
+class TestManifoldWrapperShell(unittest.TestCase):
def setUp(self):
- self.triangulation = Triangulation('2D')
+ self.triangulation = Triangulation("2D")
p_center = Point([0, 0])
- self.triangulation.generate_hyper_shell(center = p_center, inner_radius = 0.5, outer_radius = 1., n_cells = 0, colorize = True)
-
- self.manifold = Manifold(dim = 2, spacedim = 2)
+ self.triangulation.generate_hyper_shell(
+ center=p_center,
+ inner_radius=0.5,
+ outer_radius=1.0,
+ n_cells=0,
+ colorize=True,
+ )
+
+ self.manifold = Manifold(dim=2, spacedim=2)
self.manifold.create_polar(p_center)
def test_manifold(self):
for cell in self.triangulation.active_cells():
for face in cell.faces():
if face.at_boundary() and face.boundary_id == 1:
- circumference += face.measure()
+ circumference += face.measure()
- self.assertTrue(abs(circumference - 2*math.pi)/(2*math.pi) < 1e-2)
+ self.assertTrue(abs(circumference - 2 * math.pi) / (2 * math.pi) < 1e-2)
-class TestManifoldWrapperBall(unittest.TestCase):
+class TestManifoldWrapperBall(unittest.TestCase):
def setUp(self):
- self.triangulation = Triangulation('3D')
- p_center = Point([0., 0., 0.])
- self.triangulation.generate_hyper_ball(center = p_center, radius = 1.)
+ self.triangulation = Triangulation("3D")
+ p_center = Point([0.0, 0.0, 0.0])
+ self.triangulation.generate_hyper_ball(center=p_center, radius=1.0)
- self.manifold = Manifold(dim = 3, spacedim = 3)
+ self.manifold = Manifold(dim=3, spacedim=3)
self.manifold.create_spherical(p_center)
def test_manifold(self):
- self.triangulation.reset_manifold(number = 0)
- self.triangulation.set_manifold(number = 0, manifold = self.manifold)
+ self.triangulation.reset_manifold(number=0)
+ self.triangulation.set_manifold(number=0, manifold=self.manifold)
for cell in self.triangulation.active_cells():
if cell.at_boundary():
cell.manifold_id = 0
for cell in self.triangulation.active_cells():
volume += cell.measure()
- self.assertTrue(abs(volume - 4./3. * math.pi) / (4./3.*math.pi) < 2e-2)
+ self.assertTrue(
+ abs(volume - 4.0 / 3.0 * math.pi) / (4.0 / 3.0 * math.pi) < 2e-2
+ )
-class TestManifoldWrapperFunction(unittest.TestCase):
+class TestManifoldWrapperFunction(unittest.TestCase):
def setUp(self):
- self.manifold_1 = Manifold(dim = 2, spacedim = 2)
+ self.manifold_1 = Manifold(dim=2, spacedim=2)
self.manifold_1.create_function_string("x^2;y^2", "sqrt(x);sqrt(y)")
- self.manifold_2 = Manifold(dim = 2, spacedim = 2)
- self.manifold_2.create_function(lambda p: [p[0]**2., p[1]**2.],\
- lambda p: [math.sqrt(p[0]), math.sqrt(p[1])] )
+ self.manifold_2 = Manifold(dim=2, spacedim=2)
+ self.manifold_2.create_function(
+ lambda p: [p[0] ** 2.0, p[1] ** 2.0],
+ lambda p: [math.sqrt(p[0]), math.sqrt(p[1])],
+ )
- self.tria_reference = Triangulation('2D')
- test_directory = os.environ.get('DEAL_II_PYTHON_TESTPATH')
- self.tria_reference.read(test_directory+'/manifold_wrapper.vtk', 'vtk')
+ self.tria_reference = Triangulation("2D")
+ test_directory = os.environ.get("DEAL_II_PYTHON_TESTPATH")
+ self.tria_reference.read(test_directory + "/manifold_wrapper.vtk", "vtk")
def test_manifold_str(self):
- self.triangulation = Triangulation('2D')
- p_center = Point([0., 0., 0.])
+ self.triangulation = Triangulation("2D")
+ p_center = Point([0.0, 0.0, 0.0])
self.triangulation.generate_hyper_cube()
- self.triangulation.reset_manifold(number = 0)
- self.triangulation.set_manifold(number = 0, manifold = self.manifold_1)
+ self.triangulation.reset_manifold(number=0)
+ self.triangulation.set_manifold(number=0, manifold=self.manifold_1)
for cell in self.triangulation.active_cells():
cell.set_all_manifold_ids(0)
self.triangulation.refine_global(2)
- for cell_ref, cell in zip(self.tria_reference.active_cells(), self.triangulation.active_cells()):
+ for cell_ref, cell in zip(
+ self.tria_reference.active_cells(), self.triangulation.active_cells()
+ ):
self.assertTrue(abs(cell_ref.measure() - cell.measure()) < 1e-8)
def test_manifold_lambda(self):
- self.triangulation = Triangulation('2D')
- p_center = Point([0., 0., 0.])
+ self.triangulation = Triangulation("2D")
+ p_center = Point([0.0, 0.0, 0.0])
self.triangulation.generate_hyper_cube()
- self.triangulation.reset_manifold(number = 0)
- self.triangulation.set_manifold(number = 0, manifold = self.manifold_2)
+ self.triangulation.reset_manifold(number=0)
+ self.triangulation.set_manifold(number=0, manifold=self.manifold_2)
for cell in self.triangulation.active_cells():
cell.set_all_manifold_ids(0)
self.triangulation.refine_global(2)
- for cell_ref, cell in zip(self.tria_reference.active_cells(), self.triangulation.active_cells()):
+ for cell_ref, cell in zip(
+ self.tria_reference.active_cells(), self.triangulation.active_cells()
+ ):
self.assertTrue(abs(cell_ref.measure() - cell.measure()) < 1e-8)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
except ImportError:
from PyDealII.Release import *
-class TestMappingWrapperCube(unittest.TestCase):
+class TestMappingWrapperCube(unittest.TestCase):
def setUp(self):
- self.triangulation = Triangulation('2D')
+ self.triangulation = Triangulation("2D")
self.triangulation.generate_hyper_cube()
self.triangulation.refine_global(1)
def test_mapping(self):
- mapping = MappingQ(dim = 2, spacedim = 2, degree = 1)
+ mapping = MappingQ(dim=2, spacedim=2, degree=1)
p_unit = Point([0.5, 0.5])
-
+
for cell in self.triangulation.active_cells():
p_real = mapping.transform_unit_to_real_cell(cell, p_unit)
p_unit_back = mapping.transform_real_to_unit_cell(cell, p_real)
-
+
self.assertTrue(p_unit.distance(p_unit_back) < 1e-10)
-class TestMappingWrapperSphere(unittest.TestCase):
+class TestMappingWrapperSphere(unittest.TestCase):
def setUp(self):
- self.triangulation = Triangulation('2D', '3D')
- p_center = Point([0., 0., 0.])
+ self.triangulation = Triangulation("2D", "3D")
+ p_center = Point([0.0, 0.0, 0.0])
self.triangulation.generate_hyper_sphere(p_center)
def test_mapping(self):
- mapping = MappingQ(dim = 2, spacedim = 3, degree = 4)
+ mapping = MappingQ(dim=2, spacedim=3, degree=4)
p_unit = Point([0.5, 0.5])
-
+
for cell in self.triangulation.active_cells():
p_real = mapping.transform_unit_to_real_cell(cell, p_unit)
p_unit_back = mapping.transform_real_to_unit_cell(cell, p_real)
-
+
self.assertTrue(p_unit.distance(p_unit_back) < 1e-10)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
class TestPointWrapper(unittest.TestCase):
-
def test_2d_point(self):
- p1 = Point([0., 1.])
- self.assertEqual(p1.x, 0.)
- self.assertEqual(p1.y, 1.)
- p1.x = 1.
- p1.y = 2.
- self.assertEqual(p1.x, 1.)
- self.assertEqual(p1.y, 2.)
- p2 = Point([0., 2.])
- self.assertEqual(p1.distance(p2), 1.)
- self.assertEqual(p2.norm(), 2.)
- self.assertEqual(p2.norm_square(), 4.)
+ p1 = Point([0.0, 1.0])
+ self.assertEqual(p1.x, 0.0)
+ self.assertEqual(p1.y, 1.0)
+ p1.x = 1.0
+ p1.y = 2.0
+ self.assertEqual(p1.x, 1.0)
+ self.assertEqual(p1.y, 2.0)
+ p2 = Point([0.0, 2.0])
+ self.assertEqual(p1.distance(p2), 1.0)
+ self.assertEqual(p2.norm(), 2.0)
+ self.assertEqual(p2.norm_square(), 4.0)
self.assertEqual(p1 != p2, True)
self.assertEqual(p1 == p2, False)
- self.assertEqual(p1*p2, 4.)
+ self.assertEqual(p1 * p2, 4.0)
p3 = p1 + p2
self.assertEqual(p3.x, p1.x + p2.x)
self.assertEqual(p3.y, p1.y + p2.y)
p3 = -p2
self.assertEqual(p3.x, -p2.x)
self.assertEqual(p3.y, -p2.y)
- p3 = p2 / 2.
- self.assertEqual(p3.x, p2.x / 2.)
- self.assertEqual(p3.y, p2.y / 2.)
- p3 = p2 * 2.
- self.assertEqual(p3.x, p2.x * 2.)
- self.assertEqual(p3.y, p2.y * 2.)
+ p3 = p2 / 2.0
+ self.assertEqual(p3.x, p2.x / 2.0)
+ self.assertEqual(p3.y, p2.y / 2.0)
+ p3 = p2 * 2.0
+ self.assertEqual(p3.x, p2.x * 2.0)
+ self.assertEqual(p3.y, p2.y * 2.0)
p2 += p1
- self.assertEqual(p2.x, 1.)
- self.assertEqual(p2.y, 4.)
+ self.assertEqual(p2.x, 1.0)
+ self.assertEqual(p2.y, 4.0)
p2 -= p1
- self.assertEqual(p2.x, 0.)
- self.assertEqual(p2.y, 2.)
- p2 /= 2.
- self.assertEqual(p2.x, 0.)
- self.assertEqual(p2.y, 1.)
- p2 *= 2.
- self.assertEqual(p2.x, 0.)
- self.assertEqual(p2.y, 2.)
+ self.assertEqual(p2.x, 0.0)
+ self.assertEqual(p2.y, 2.0)
+ p2 /= 2.0
+ self.assertEqual(p2.x, 0.0)
+ self.assertEqual(p2.y, 1.0)
+ p2 *= 2.0
+ self.assertEqual(p2.x, 0.0)
+ self.assertEqual(p2.y, 2.0)
def test_3d_point(self):
- p1 = Point([0., 1., 2.])
- self.assertEqual(p1.x, 0.)
- self.assertEqual(p1.y, 1.)
- self.assertEqual(p1.z, 2.)
- p1.x = 1.
- p1.y = 2.
- p1.z = 3.
- self.assertEqual(p1.x, 1.)
- self.assertEqual(p1.y, 2.)
- self.assertEqual(p1.z, 3.)
- p2 = Point([0., 1., 2.])
+ p1 = Point([0.0, 1.0, 2.0])
+ self.assertEqual(p1.x, 0.0)
+ self.assertEqual(p1.y, 1.0)
+ self.assertEqual(p1.z, 2.0)
+ p1.x = 1.0
+ p1.y = 2.0
+ p1.z = 3.0
+ self.assertEqual(p1.x, 1.0)
+ self.assertEqual(p1.y, 2.0)
+ self.assertEqual(p1.z, 3.0)
+ p2 = Point([0.0, 1.0, 2.0])
self.assertAlmostEqual(p1.distance(p2), math.sqrt(3))
self.assertAlmostEqual(p2.norm(), math.sqrt(5))
- self.assertEqual(p2.norm_square(), 5.)
+ self.assertEqual(p2.norm_square(), 5.0)
self.assertEqual(p1 != p2, True)
self.assertEqual(p1 == p2, False)
- self.assertEqual(p1*p2, 8)
+ self.assertEqual(p1 * p2, 8)
dim = 3
p3 = p1 + p2
self.assertEqual(p3.x, p1.x + p2.x)
self.assertEqual(p3.x, -p2.x)
self.assertEqual(p3.y, -p2.y)
self.assertEqual(p3.z, -p2.z)
- p3 = p2 / 2.
- self.assertEqual(p3.x, p2.x / 2.)
- self.assertEqual(p3.y, p2.y / 2.)
- self.assertEqual(p3.z, p2.z / 2.)
- p3 = p2 * 2.
- self.assertEqual(p3.x, p2.x * 2.)
- self.assertEqual(p3.y, p2.y * 2.)
- self.assertEqual(p3.z, p2.z * 2.)
+ p3 = p2 / 2.0
+ self.assertEqual(p3.x, p2.x / 2.0)
+ self.assertEqual(p3.y, p2.y / 2.0)
+ self.assertEqual(p3.z, p2.z / 2.0)
+ p3 = p2 * 2.0
+ self.assertEqual(p3.x, p2.x * 2.0)
+ self.assertEqual(p3.y, p2.y * 2.0)
+ self.assertEqual(p3.z, p2.z * 2.0)
p2 += p1
- self.assertEqual(p2.x, 1.)
- self.assertEqual(p2.y, 3.)
- self.assertEqual(p2.z, 5.)
+ self.assertEqual(p2.x, 1.0)
+ self.assertEqual(p2.y, 3.0)
+ self.assertEqual(p2.z, 5.0)
p2 -= p1
- self.assertEqual(p2.x, 0.)
- self.assertEqual(p2.y, 1.)
- self.assertEqual(p2.z, 2.)
- p2 /= 2.
- self.assertEqual(p2.x, 0.)
+ self.assertEqual(p2.x, 0.0)
+ self.assertEqual(p2.y, 1.0)
+ self.assertEqual(p2.z, 2.0)
+ p2 /= 2.0
+ self.assertEqual(p2.x, 0.0)
self.assertEqual(p2.y, 0.5)
- self.assertEqual(p2.z, 1.)
- p2 *= 2.
- self.assertEqual(p2.x, 0.)
- self.assertEqual(p2.y, 1.)
- self.assertEqual(p2.z, 2.)
+ self.assertEqual(p2.z, 1.0)
+ p2 *= 2.0
+ self.assertEqual(p2.x, 0.0)
+ self.assertEqual(p2.y, 1.0)
+ self.assertEqual(p2.z, 2.0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
except ImportError:
from PyDealII.Release import *
-class TestQuadratureWrapper(unittest.TestCase):
+class TestQuadratureWrapper(unittest.TestCase):
def test_gauss(self):
- quadrature = Quadrature(dim = 3)
- quadrature.create_gauss(n = 1);
+ quadrature = Quadrature(dim=3)
+ quadrature.create_gauss(n=1)
- w_sum = 0.
+ w_sum = 0.0
for weight in quadrature.weights():
w_sum += weight
- self.assertTrue(abs(1. - w_sum) < 1e-10)
+ self.assertTrue(abs(1.0 - w_sum) < 1e-10)
def test_gauss_lobatto(self):
- quadrature = Quadrature(dim = 3)
- quadrature.create_gauss_lobatto(n = 2);
+ quadrature = Quadrature(dim=3)
+ quadrature.create_gauss_lobatto(n=2)
- w_sum = 0.
+ w_sum = 0.0
for weight in quadrature.weights():
w_sum += weight
- self.assertTrue(abs(1. - w_sum) < 1e-10)
+ self.assertTrue(abs(1.0 - w_sum) < 1e-10)
+
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
except ImportError:
from PyDealII.Release import *
-class TestTriangulationWrapper(unittest.TestCase):
+class TestTriangulationWrapper(unittest.TestCase):
def setUp(self):
- self.dim = [['2D', '2D'], ['2D', '3D'], ['3D', '3D']]
- self.restricted_dim = [['2D', '2D'], ['3D', '3D']]
+ self.dim = [["2D", "2D"], ["2D", "3D"], ["3D", "3D"]]
+ self.restricted_dim = [["2D", "2D"], ["3D", "3D"]]
def build_hyper_cube_triangulation(self, dim):
triangulation_1 = Triangulation(dim[0], dim[1])
def build_hyper_rectangle_triangulation(self, dim):
triangulation_2 = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
- point_1 = Point([0., 0.])
- point_2 = Point([1., 1.])
+ if dim[0] == "2D":
+ point_1 = Point([0.0, 0.0])
+ point_2 = Point([1.0, 1.0])
else:
- point_1 = Point([0., 0., 0.])
- point_2 = Point([1., 1., 1.])
+ point_1 = Point([0.0, 0.0, 0.0])
+ point_2 = Point([1.0, 1.0, 1.0])
triangulation_2.generate_hyper_rectangle(point_1, point_2)
return triangulation_2
def test_simplex(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- point_1 = Point([0., 0.])
- point_2 = Point([1., 0.])
- point_3 = Point([1., 1.])
+ if dim[0] == "2D":
+ point_1 = Point([0.0, 0.0])
+ point_2 = Point([1.0, 0.0])
+ point_3 = Point([1.0, 1.0])
vertices = [point_1, point_2, point_3]
else:
- point_1 = Point([0., 0., 0.])
- point_2 = Point([1., 0., 0.])
- point_3 = Point([1., 1., 0.])
- point_4 = Point([1., 1., 1.])
+ point_1 = Point([0.0, 0.0, 0.0])
+ point_2 = Point([1.0, 0.0, 0.0])
+ point_3 = Point([1.0, 1.0, 0.0])
+ point_4 = Point([1.0, 1.0, 1.0])
vertices = [point_1, point_2, point_3, point_4]
triangulation.generate_simplex(vertices)
n_cells = triangulation.n_active_cells()
def test_create_triangulation(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- vertices = [[0., 0.], [1., 0.], [0., 1.], [1., 1.]]
+ if dim[0] == "2D":
+ vertices = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
cell_vertices = [[0, 1, 2, 3]]
else:
- vertices = [[0., 0., 0.], [1., 0., 0.],\
- [0., 1., 0.], [1., 1., 0.],\
- [0., 0., 1.], [1., 0., 1.],\
- [0., 1., 1.], [1., 1., 1.]]
+ vertices = [
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [1.0, 0.0, 1.0],
+ [0.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0],
+ ]
cell_vertices = [[0, 1, 2, 3, 4, 5, 6, 7]]
triangulation.create_triangulation(vertices, cell_vertices)
n_cells = triangulation.n_active_cells()
repetitions = 2
triangulation.generate_subdivided_hyper_cube(repetitions)
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 4)
else:
self.assertEqual(n_cells, 8)
def test_subdivided_hyper_rectangle(self):
for dim in self.dim:
triangulation = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
repetitions = [6, 4]
- point_1 = Point([0., 0.])
- point_2 = Point([1., 1.])
+ point_1 = Point([0.0, 0.0])
+ point_2 = Point([1.0, 1.0])
else:
repetitions = [2, 3, 4]
- point_1 = Point([0., 0., 0.])
- point_2 = Point([1., 1., 1.])
- triangulation.generate_subdivided_hyper_rectangle(repetitions,
- point_1,
- point_2)
+ point_1 = Point([0.0, 0.0, 0.0])
+ point_2 = Point([1.0, 1.0, 1.0])
+ triangulation.generate_subdivided_hyper_rectangle(
+ repetitions, point_1, point_2
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 24)
def test_subdivided_steps_hyper_rectangle(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
step_sizes = [[0.6, 0.4], [0.4, 0.6]]
- point_1 = Point([0., 0.])
- point_2 = Point([1., 1.])
- triangulation.generate_subdivided_steps_hyper_rectangle(step_sizes,
- point_1,
- point_2)
+ point_1 = Point([0.0, 0.0])
+ point_2 = Point([1.0, 1.0])
+ triangulation.generate_subdivided_steps_hyper_rectangle(
+ step_sizes, point_1, point_2
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 4)
else:
step_sizes = [[0.6, 0.4], [0.4, 0.6], [0.5, 0.5]]
- point_1 = Point([0., 0., 0.])
- point_2 = Point([1., 1., 1.])
- triangulation.generate_subdivided_steps_hyper_rectangle(step_sizes,
- point_1,
- point_2)
+ point_1 = Point([0.0, 0.0, 0.0])
+ point_2 = Point([1.0, 1.0, 1.0])
+ triangulation.generate_subdivided_steps_hyper_rectangle(
+ step_sizes, point_1, point_2
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 8)
def test_subdivided_material_hyper_rectangle(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
spacing = [[0.3, 0.3, 0.4], [0.4, 0.3, 0.3]]
- point = Point([1., 1.])
+ point = Point([1.0, 1.0])
material_ids = [[1, 2, 3], [0, -1, 1], [2, -1, 3]]
triangulation.generate_subdivided_material_hyper_rectangle(
- spacing, point, material_ids)
+ spacing, point, material_ids
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 7)
else:
spacing = [[0.3, 0.3, 0.4], [0.4, 0.3, 0.3], [0.2, 0.3, 0.5]]
- point = Point([1., 1., 1.])
- material_ids = [[[1, 2, 3], [0, -1, 1], [2, -1, 3]],
- [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
- [[2, -1, -1], [-1, -1, -1], [-1, -1, -1]]]
+ point = Point([1.0, 1.0, 1.0])
+ material_ids = [
+ [[1, 2, 3], [0, -1, 1], [2, -1, 3]],
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
+ [[2, -1, -1], [-1, -1, -1], [-1, -1, -1]],
+ ]
triangulation.generate_subdivided_material_hyper_rectangle(
- spacing, point, material_ids)
+ spacing, point, material_ids
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 17)
def test_hyper_cube_with_cylindrical_hole(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0])
- triangulation.generate_hyper_cube_with_cylindrical_hole(inner_radius = .25,
- outer_radius = .5, L = .5, repetitions = 1, colorize = False)
+ triangulation.generate_hyper_cube_with_cylindrical_hole(
+ inner_radius=0.25,
+ outer_radius=0.5,
+ L=0.5,
+ repetitions=1,
+ colorize=False,
+ )
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 8)
def test_generate_cheese(self):
for dim in self.dim:
triangulation = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
holes = [2, 3]
triangulation.generate_cheese(holes)
n_cells = triangulation.n_active_cells()
triangulation = Triangulation(dim[0])
triangulation.generate_channel_with_cylinder()
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 108)
else:
self.assertEqual(n_cells, 432)
def test_generate_general_cell(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0], dim[1])
- if (dim[0] == '2D'):
- point_0 = Point([0., 0.])
- point_1 = Point([1., 0.])
- point_2 = Point([0., 1.])
- point_3 = Point([1., 1.])
+ if dim[0] == "2D":
+ point_0 = Point([0.0, 0.0])
+ point_1 = Point([1.0, 0.0])
+ point_2 = Point([0.0, 1.0])
+ point_3 = Point([1.0, 1.0])
points = [point_0, point_1, point_2, point_3]
triangulation.generate_general_cell(points)
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 4)
else:
- point_0 = Point([0., 0., 0.])
- point_1 = Point([1., 0., 0.])
- point_2 = Point([0., 1., 0.])
- point_3 = Point([1., 1., 0.])
- point_4 = Point([0., 0., 1.])
- point_5 = Point([1., 0., 1.])
- point_6 = Point([0., 1., 1.])
- point_7 = Point([1., 1., 1.])
- points = [point_0, point_1, point_2, point_3, point_4, point_5,
- point_6, point_7]
+ point_0 = Point([0.0, 0.0, 0.0])
+ point_1 = Point([1.0, 0.0, 0.0])
+ point_2 = Point([0.0, 1.0, 0.0])
+ point_3 = Point([1.0, 1.0, 0.0])
+ point_4 = Point([0.0, 0.0, 1.0])
+ point_5 = Point([1.0, 0.0, 1.0])
+ point_6 = Point([0.0, 1.0, 1.0])
+ point_7 = Point([1.0, 1.0, 1.0])
+ points = [
+ point_0,
+ point_1,
+ point_2,
+ point_3,
+ point_4,
+ point_5,
+ point_6,
+ point_7,
+ ]
triangulation.generate_general_cell(points)
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 8)
def test_generate_parallelogram(self):
- triangulation = Triangulation('2D')
- corner_0 = Point([1., 0.])
- corner_1 = Point([1., 1.])
+ triangulation = Triangulation("2D")
+ corner_0 = Point([1.0, 0.0])
+ corner_1 = Point([1.0, 1.0])
corners = [corner_0, corner_1]
triangulation.generate_parallelogram(corners)
triangulation.refine_global(1)
def test_generate_parallelepid(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- corner_0 = Point([1., 0.])
- corner_1 = Point([1., 1.])
+ if dim[0] == "2D":
+ corner_0 = Point([1.0, 0.0])
+ corner_1 = Point([1.0, 1.0])
corners = [corner_0, corner_1]
triangulation.generate_parallelepiped(corners)
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 4)
else:
- corner_0 = Point([1., 0., 0.])
- corner_1 = Point([0., 1., 0.])
- corner_2 = Point([0., 0., 1.])
+ corner_0 = Point([1.0, 0.0, 0.0])
+ corner_1 = Point([0.0, 1.0, 0.0])
+ corner_2 = Point([0.0, 0.0, 1.0])
corners = [corner_0, corner_1, corner_2]
triangulation.generate_parallelepiped(corners)
triangulation.refine_global(1)
def test_generate_fixed_subdivided_parallelepiped(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- corner_0 = Point([1., 0.])
- corner_1 = Point([1., 1.])
+ if dim[0] == "2D":
+ corner_0 = Point([1.0, 0.0])
+ corner_1 = Point([1.0, 1.0])
corners = [corner_0, corner_1]
- triangulation.generate_fixed_subdivided_parallelepiped(2,
- corners)
+ triangulation.generate_fixed_subdivided_parallelepiped(2, corners)
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 16)
else:
- corner_0 = Point([1., 0., 0.])
- corner_1 = Point([0., 1., 0.])
- corner_2 = Point([0., 0., 1.])
+ corner_0 = Point([1.0, 0.0, 0.0])
+ corner_1 = Point([0.0, 1.0, 0.0])
+ corner_2 = Point([0.0, 0.0, 1.0])
corners = [corner_0, corner_1, corner_2]
- triangulation.generate_fixed_subdivided_parallelepiped(2,
- corners)
+ triangulation.generate_fixed_subdivided_parallelepiped(2, corners)
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 64)
def test_generate_varying_subdivided_parallelepiped(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- corner_0 = Point([1., 0.])
- corner_1 = Point([1., 1.])
+ if dim[0] == "2D":
+ corner_0 = Point([1.0, 0.0])
+ corner_1 = Point([1.0, 1.0])
corners = [corner_0, corner_1]
- subdivisions = [2 , 3]
- triangulation.generate_varying_subdivided_parallelepiped(subdivisions,
- corners)
+ subdivisions = [2, 3]
+ triangulation.generate_varying_subdivided_parallelepiped(
+ subdivisions, corners
+ )
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 24)
else:
- corner_0 = Point([1., 0., 0.])
- corner_1 = Point([0., 1., 0.])
- corner_2 = Point([0., 0., 1.])
+ corner_0 = Point([1.0, 0.0, 0.0])
+ corner_1 = Point([0.0, 1.0, 0.0])
+ corner_2 = Point([0.0, 0.0, 1.0])
corners = [corner_0, corner_1, corner_2]
- subdivisions = [2 , 3, 1]
- triangulation.generate_varying_subdivided_parallelepiped(subdivisions,
- corners)
+ subdivisions = [2, 3, 1]
+ triangulation.generate_varying_subdivided_parallelepiped(
+ subdivisions, corners
+ )
triangulation.refine_global(1)
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 48)
def test_generate_enclosed_hyper_cube(self):
for dim in self.restricted_dim:
triangulation = Triangulation(dim[0])
- left = 1.
- right = 3.
- thickness = 4.
- triangulation.generate_enclosed_hyper_cube(left, right,
- thickness)
+ left = 1.0
+ right = 3.0
+ thickness = 4.0
+ triangulation.generate_enclosed_hyper_cube(left, right, thickness)
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 9)
else:
self.assertEqual(n_cells, 27)
def test_hyper_ball(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- center = Point([0., 0.])
+ if dim[0] == "2D":
+ center = Point([0.0, 0.0])
n_cells_ref = 5
else:
- center = Point([0., 0., 0.])
+ center = Point([0.0, 0.0, 0.0])
n_cells_ref = 7
triangulation.generate_hyper_ball(center)
n_cells = triangulation.n_active_cells()
triangulation = Triangulation(dim[0])
triangulation.generate_hyper_ball_balanced()
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 12)
else:
self.assertEqual(n_cells, 32)
def test_hyper_sphere(self):
- triangulation = Triangulation('2D', '3D')
- center = Point([0, 0])
- radius = 1.
- triangulation.generate_hyper_sphere(center, radius)
- n_cells = triangulation.n_active_cells()
- self.assertEqual(n_cells, 6)
+ triangulation = Triangulation("2D", "3D")
+ center = Point([0, 0])
+ radius = 1.0
+ triangulation.generate_hyper_sphere(center, radius)
+ n_cells = triangulation.n_active_cells()
+ self.assertEqual(n_cells, 6)
def test_quarter_hyper_ball(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- center = Point([0., 0.])
+ if dim[0] == "2D":
+ center = Point([0.0, 0.0])
n_cells_ref = 3
else:
- center = Point([0., 0., 0.])
+ center = Point([0.0, 0.0, 0.0])
n_cells_ref = 4
triangulation.generate_quarter_hyper_ball(center)
n_cells = triangulation.n_active_cells()
def test_half_hyper_ball(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
- center = Point([0., 0.])
+ if dim[0] == "2D":
+ center = Point([0.0, 0.0])
n_cells_ref = 4
else:
- center = Point([0., 0., 0.])
+ center = Point([0.0, 0.0, 0.0])
n_cells_ref = 6
triangulation.generate_half_hyper_ball(center)
n_cells = triangulation.n_active_cells()
def test_cylinder(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
n_cells_ref = 1
else:
n_cells_ref = 10
self.assertEqual(n_cells, n_cells_ref)
def test_subdivided_cylinder(self):
- triangulation = Triangulation('3D')
+ triangulation = Triangulation("3D")
n_cells_ref = 5
triangulation.generate_subdivided_cylinder(2)
n_cells = triangulation.n_active_cells()
def test_truncated_cone(self):
for dim in self.dim:
triangulation = Triangulation(dim[0])
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
n_cells_ref = 1
else:
n_cells_ref = 5
for dim in self.dim:
triangulation_1 = self.build_hyper_cube_triangulation(dim)
triangulation_2 = self.build_hyper_rectangle_triangulation(dim)
- if (dim[1] == '2D'):
- triangulation_2.shift([1., 0.])
+ if dim[1] == "2D":
+ triangulation_2.shift([1.0, 0.0])
else:
- triangulation_2.shift([1., 0., 0.])
+ triangulation_2.shift([1.0, 0.0, 0.0])
triangulation = Triangulation(dim[0], dim[1])
- triangulation.merge_triangulations([triangulation_1,
- triangulation_2])
+ triangulation.merge_triangulations([triangulation_1, triangulation_2])
n_cells = triangulation.n_active_cells()
self.assertEqual(n_cells, 2)
for dim in self.restricted_dim:
triangulation_in = self.build_hyper_cube_triangulation(dim)
triangulation_out = Triangulation(dim[0])
- if (dim[0] == '2D'):
- triangulation_out.replicate_triangulation(triangulation_in, [3, 2]);
+ if dim[0] == "2D":
+ triangulation_out.replicate_triangulation(triangulation_in, [3, 2])
else:
- triangulation_out.replicate_triangulation(triangulation_in, [3, 2, 1]);
+ triangulation_out.replicate_triangulation(triangulation_in, [3, 2, 1])
n_cells = triangulation_out.n_active_cells()
self.assertEqual(n_cells, 6)
triangulation_2 = Triangulation(dim[0])
triangulation_1.flatten_triangulation(triangulation_2)
n_cells = triangulation_2.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 16)
else:
self.assertEqual(n_cells, 64)
-
def test_adaptive_refinement(self):
for dim in self.dim:
triangulation = self.build_hyper_cube_triangulation(dim)
triangulation.refine_global(1)
for cell in triangulation.active_cells():
- cell.refine_flag = 'isotropic'
+ cell.refine_flag = "isotropic"
break
triangulation.execute_coarsening_and_refinement()
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 7)
else:
self.assertEqual(n_cells, 15)
triangulation = self.build_hyper_cube_triangulation(dim)
triangulation.refine_global(2)
n_cells = triangulation.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 16)
else:
self.assertEqual(n_cells, 64)
-
def test_transform(self):
for dim in self.dim:
triangulation_1 = self.build_hyper_cube_triangulation(dim)
triangulation_2 = self.build_hyper_cube_triangulation(dim)
triangulation_2.refine_global(1)
- triangulation_1.transform(lambda p: [v + 1. for v in p])
+ triangulation_1.transform(lambda p: [v + 1.0 for v in p])
- if dim[1] == '3D':
- offset = Point([1., 1., 1.])
+ if dim[1] == "3D":
+ offset = Point([1.0, 1.0, 1.0])
else:
- offset = Point([1., 1.])
-
- for (cell_1, cell_2) in zip(triangulation_1.active_cells(), triangulation_2.active_cells()):
- self.assertTrue(cell_1.center().distance(cell_2.center() + offset) < 1e-8)
+ offset = Point([1.0, 1.0])
+ for (cell_1, cell_2) in zip(
+ triangulation_1.active_cells(), triangulation_2.active_cells()
+ ):
+ self.assertTrue(
+ cell_1.center().distance(cell_2.center() + offset) < 1e-8
+ )
def test_find_active_cell_around_point(self):
for dim in self.dim:
cell_ret = triangulation.find_active_cell_around_point(cell.center())
self.assertTrue(cell.center().distance(cell_ret.center()) < 1e-8)
-
def test_simplex(self):
for dim in self.dim:
triangulation_hex = self.build_hyper_cube_triangulation(dim)
triangulation_simplex = Triangulation(dim[0], dim[1])
triangulation_hex.convert_hypercube_to_simplex_mesh(triangulation_simplex)
- if dim[0] == '3D':
+ if dim[0] == "3D":
self.assertTrue(triangulation_simplex.n_active_cells() == 24)
else:
self.assertTrue(triangulation_simplex.n_active_cells() == 8)
-
def test_save_load(self):
for dim in self.dim:
triangulation_1 = self.build_hyper_cube_triangulation(dim)
triangulation_1.refine_global(1)
- triangulation_1.save('mesh.output')
+ triangulation_1.save("mesh.output")
triangulation_2 = Triangulation(dim[0], dim[1])
- triangulation_2.load('mesh.output')
+ triangulation_2.load("mesh.output")
n_cells = triangulation_2.n_active_cells()
- if (dim[0] == '2D'):
+ if dim[0] == "2D":
self.assertEqual(n_cells, 4)
else:
self.assertEqual(n_cells, 8)
-
def test_mesh_smoothing(self):
- tria = Triangulation('2D')
+ tria = Triangulation("2D")
self.assertEqual(tria.get_mesh_smoothing(), MeshSmoothing.none)
tria.set_mesh_smoothing(MeshSmoothing.maximum_smoothing)
self.assertEqual(tria.get_mesh_smoothing(), MeshSmoothing.maximum_smoothing)
- tria = Triangulation('2D', MeshSmoothing.limit_level_difference_at_vertices)
- self.assertEqual(tria.get_mesh_smoothing(), MeshSmoothing.limit_level_difference_at_vertices)
+ tria = Triangulation("2D", MeshSmoothing.limit_level_difference_at_vertices)
+ self.assertEqual(
+ tria.get_mesh_smoothing(), MeshSmoothing.limit_level_difference_at_vertices
+ )
- tria = Triangulation('2D', '3D', MeshSmoothing.none, False)
+ tria = Triangulation("2D", "3D", MeshSmoothing.none, False)
tria.set_mesh_smoothing(MeshSmoothing.limit_level_difference_at_vertices)
- self.assertEqual(tria.get_mesh_smoothing(), MeshSmoothing.limit_level_difference_at_vertices)
-
- tria = Triangulation('3D', MeshSmoothing.limit_level_difference_at_vertices | MeshSmoothing.do_not_produce_unrefined_islands)
- self.assertEqual(tria.get_mesh_smoothing(), MeshSmoothing.limit_level_difference_at_vertices | MeshSmoothing.do_not_produce_unrefined_islands)
-
-
-if __name__ == '__main__':
+ self.assertEqual(
+ tria.get_mesh_smoothing(), MeshSmoothing.limit_level_difference_at_vertices
+ )
+
+ tria = Triangulation(
+ "3D",
+ MeshSmoothing.limit_level_difference_at_vertices
+ | MeshSmoothing.do_not_produce_unrefined_islands,
+ )
+ self.assertEqual(
+ tria.get_mesh_smoothing(),
+ MeshSmoothing.limit_level_difference_at_vertices
+ | MeshSmoothing.do_not_produce_unrefined_islands,
+ )
+
+
+if __name__ == "__main__":
unittest.main()
yield root + "/" + file_name
-filenames = itertools.chain(filename_generator(".h"),
- filename_generator(".cc"),
- filename_generator(".html"))
+filenames = itertools.chain(
+ filename_generator(".h"), filename_generator(".cc"), filename_generator(".html")
+)
return_code = 0
for filename in filenames:
- file_handle = io.open(filename, encoding='utf-8')
+ file_handle = io.open(filename, encoding="utf-8")
try:
file_handle.read()
except UnicodeDecodeError:
- print(filename + ' is not encoded with UTF-8')
+ print(filename + " is not encoded with UTF-8")
return_code = 1
finally:
file_handle.close()
if "@{" in l:
count = count + 1
elif "@}" in l:
- count = count -1
+ count = count - 1
if count < 0:
- sys.exit("Error in file '%s' in line %d"%(filename, lineno))
+ sys.exit("Error in file '%s' in line %d" % (filename, lineno))
lineno = lineno + 1
if count != 0:
- sys.exit("Error: missing closing braces in file '%s'"%(filename))
+ sys.exit("Error: missing closing braces in file '%s'" % (filename))
return
+
# have empty lines in html tables?
def check_empty_lines_in_tables(lines):
count = 0
if "<table" in l:
count = count + 1
elif "</table>" in l:
- count = count -1
+ count = count - 1
if count < 0:
- sys.exit("Error in file '%s' in line %d"%(filename, lineno))
+ sys.exit("Error in file '%s' in line %d" % (filename, lineno))
if count == 1:
if l.strip() == "":
- sys.exit("Error: empty line inside html table in file '%s' in line %d"%(filename, lineno))
+ sys.exit(
+ "Error: empty line inside html table in file '%s' in line %d"
+ % (filename, lineno)
+ )
lineno = lineno + 1
if count != 0:
- sys.exit("Error: mismatched html table tags in file '%s'"%(filename))
+ sys.exit("Error: mismatched html table tags in file '%s'" % (filename))
return
+
# have more than one header with the same name in a tutorial?
def check_multiple_defined_headers(lines):
headers = []
# this may break if a header splits across a line
if "<h" in l:
# convert thisheader to the doxygen header name equivalent
- thisheader = l # take this line
- thisheader = thisheader.replace(' ', '') # remove all whitespace
- thisheader = thisheader.split('<h')[1] # remove header tag '<h'
+ thisheader = l # take this line
+ thisheader = thisheader.replace(" ", "") # remove all whitespace
+ thisheader = thisheader.split("<h")[1] # remove header tag '<h'
- if thisheader[0] == '2':
+ if thisheader[0] == "2":
# We do not use <h2> headers in tutorials because our script
# does not put them in the table of contents (for historical
# reasons). Instead, please use <h3>, <h4>, etc..
- sys.exit("Error: Header <h2> detected in file '%s'. This is"
- " not allowed in tutorial programs. Please use <h3>"
- " instead." % (filename))
-
- if thisheader[0] in ['1', '2', '3', '4', '5']: # make sure the next character is 1-5
- thisheader = thisheader[2:] # remove '*>'
- if len(thisheader.split('</h'))==2: # check for close header on the same line
- thisheader = thisheader.split('</h')[0] # remove close header tag
- thisheader = ''.join(ch for ch in thisheader if ch.isalnum()) # remove nonalphanumeric
+ sys.exit(
+ "Error: Header <h2> detected in file '%s'. This is"
+ " not allowed in tutorial programs. Please use <h3>"
+ " instead." % (filename)
+ )
+
+ if thisheader[0] in [
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ ]: # make sure the next character is 1-5
+ thisheader = thisheader[2:] # remove '*>'
+ if (
+ len(thisheader.split("</h")) == 2
+ ): # check for close header on the same line
+ thisheader = thisheader.split("</h")[0] # remove close header tag
+ thisheader = "".join(
+ ch for ch in thisheader if ch.isalnum()
+ ) # remove nonalphanumeric
if thisheader in headers:
- sys.exit("Error: repeated header title '%s' in file group '%s'"%(thisheader,filename))
+ sys.exit(
+ "Error: repeated header title '%s' in file group '%s'"
+ % (thisheader, filename)
+ )
else:
headers.append(thisheader)
else:
- sys.exit("Error: mismatched html header flags in file group '%s'"%(filename))
+ sys.exit(
+ "Error: mismatched html header flags in file group '%s'"
+ % (filename)
+ )
# do not check else here because it may match with template arguments like '<hsize_t>'
-
+
# detect @sect[1-5]{ ... }
if "@sect" in l:
- thisheader = l # take this line
- thisheader = thisheader.replace(' ', '') # remove all whitespace
- thisheader = thisheader.split('@sect')[1] # remove '@sect'
- if thisheader[0] in ['1', '2', '3', '4', '5']: # make sure the next character is 1-5
- thisheader = thisheader[2:] # remove the number
- thisheader = ''.join(ch for ch in thisheader if ch.isalnum()) # remove nonalphanumeric
+ thisheader = l # take this line
+ thisheader = thisheader.replace(" ", "") # remove all whitespace
+ thisheader = thisheader.split("@sect")[1] # remove '@sect'
+ if thisheader[0] in [
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ ]: # make sure the next character is 1-5
+ thisheader = thisheader[2:] # remove the number
+ thisheader = "".join(
+ ch for ch in thisheader if ch.isalnum()
+ ) # remove nonalphanumeric
if thisheader in headers:
- sys.exit("Error: repeated header title '%s' in file group '%s'"%(thisheader,filename))
+ sys.exit(
+ "Error: repeated header title '%s' in file group '%s'"
+ % (thisheader, filename)
+ )
else:
headers.append(thisheader)
args = sys.argv
-if len(args)!=2:
- print("Usage: %s <filename>"%(sys.argv[0]))
+if len(args) != 2:
+ print("Usage: %s <filename>" % (sys.argv[0]))
sys.exit("Error: please pass exactly one filename to this script")
filename = args[1]
check_empty_lines_in_tables(lines)
# if it's intro.dox, combine it with step-**.cc and results.dox and check headers
-if 'intro.dox' in filename:
+if "intro.dox" in filename:
# get stepname.cc
- stepname = filename.split('/doc',1)[0]
- stepname = stepname + '/' + stepname.split('/',1)[1] + '.cc'
+ stepname = filename.split("/doc", 1)[0]
+ stepname = stepname + "/" + stepname.split("/", 1)[1] + ".cc"
# get results.dox
- resultsname = filename.split('intro.dox',1)[0] + 'results.dox'
-
+ resultsname = filename.split("intro.dox", 1)[0] + "results.dox"
+
# open the '.cc' file:
fstep = open(stepname)
fres = open(resultsname)
lines += fres.readlines()
fres.close()
-
+
# check the file group
check_multiple_defined_headers(lines)
# ones that correspond to #include statements for deal.II header
# files. For those, add a link from header file to the one it includes
# to the graph.
-def add_includes_for_file(header_file_name, G) :
+def add_includes_for_file(header_file_name, G):
f = open(header_file_name)
lines = f.readlines()
f.close()
- for line in lines :
+ for line in lines:
m = match_includes.match(line)
- if m :
+ if m:
included_file = m.group(1)
- G.add_edge(header_file_name.replace("include/", ""),
- included_file)
-
+ G.add_edge(header_file_name.replace("include/", ""), included_file)
# Create a list of all header files in the include folder.
# For each header file, add the includes as the edges of a directed graph.
G = nx.DiGraph()
-for header_file_name in filelist :
+for header_file_name in filelist:
add_includes_for_file(header_file_name, G)
# Then figure out whether there are cycles and if so, print them:
cycles = nx.simple_cycles(G)
cycles_as_list = list(cycles)
-if (len(cycles_as_list) > 0) :
- print (f"Cycles in the include graph detected!")
- for cycle in cycles_as_list :
+if len(cycles_as_list) > 0:
+ print(f"Cycles in the include graph detected!")
+ for cycle in cycles_as_list:
print(cycle)
exit(1)
# Skip the following tokens since they show up frequently but are not related to
# double word typos
-SKIP = ["//", "*", "}", "|", "};", ">", "\"", "|", "/",
- "numbers::invalid_unsigned_int,", "std::string,", "int,"]
+SKIP = [
+ "//",
+ "*",
+ "}",
+ "|",
+ "};",
+ ">",
+ '"',
+ "|",
+ "/",
+ "numbers::invalid_unsigned_int,",
+ "std::string,",
+ "int,",
+]
-with open(sys.argv[1], 'r', encoding='utf-8') as handle:
+with open(sys.argv[1], "r", encoding="utf-8") as handle:
previous_line = ""
for line_n, line in enumerate(handle):
line = line.strip()
"""
Argument parser.
"""
- parser = argparse.ArgumentParser("Run clang-format on all files "
- "in a list of directories "
- "that satisfy a given regex."
- "This program requires "
- "clang-format version 16.0.")
-
- parser.add_argument("-b", "--clang-format-binary", metavar="PATH",
- default=distutils.spawn.find_executable("clang-format"))
-
- parser.add_argument("--regex", default="*.cc,*.h",
- help="Regular expression (regex) to filter files on "
- "which clang-format is applied.")
-
- parser.add_argument("--dry-run", default=False, action='store_true',
- help="If --dry-run is passed as an argument, "
- "file names of files that are not formatted correctly "
- "are written out, without actually formatting them.")
-
- parser.add_argument("-dirs", "--directories",
- default="include,source,tests,examples",
- help="Comma-delimited list of directories to work on."
- "By default only \"examples\", \"include\", "
- "\"source\" and \"tests\" "
- "directories are chosen to work on."
- "Path to directories can be both absolute or relative.")
-
- parser.add_argument("-j", metavar="THREAD_COUNT", type=int, default=0,
- help="Number of clang-format instances to be run "
- "in parallel."
- "By default this is equal to the maximum number of "
- "available threads less one.")
+ parser = argparse.ArgumentParser(
+ "Run clang-format on all files "
+ "in a list of directories "
+ "that satisfy a given regex."
+ "This program requires "
+ "clang-format version 16.0."
+ )
+
+ parser.add_argument(
+ "-b",
+ "--clang-format-binary",
+ metavar="PATH",
+ default=distutils.spawn.find_executable("clang-format"),
+ )
+
+ parser.add_argument(
+ "--regex",
+ default="*.cc,*.h",
+ help="Regular expression (regex) to filter files on "
+ "which clang-format is applied.",
+ )
+
+ parser.add_argument(
+ "--dry-run",
+ default=False,
+ action="store_true",
+ help="If --dry-run is passed as an argument, "
+ "file names of files that are not formatted correctly "
+ "are written out, without actually formatting them.",
+ )
+
+ parser.add_argument(
+ "-dirs",
+ "--directories",
+ default="include,source,tests,examples",
+ help="Comma-delimited list of directories to work on."
+ 'By default only "examples", "include", '
+ '"source" and "tests" '
+ "directories are chosen to work on."
+ "Path to directories can be both absolute or relative.",
+ )
+
+ parser.add_argument(
+ "-j",
+ metavar="THREAD_COUNT",
+ type=int,
+ default=0,
+ help="Number of clang-format instances to be run "
+ "in parallel."
+ "By default this is equal to the maximum number of "
+ "available threads less one.",
+ )
return parser.parse_args()
"""
if clang_format_binary:
try:
- clang_format_version = subprocess.check_output([clang_format_binary,
- '--version']).decode()
- version_number = re.search(r'Version\s*([\d.]+)',
- clang_format_version,
- re.IGNORECASE).group(1)
+ clang_format_version = subprocess.check_output(
+ [clang_format_binary, "--version"]
+ ).decode()
+ version_number = re.search(
+ r"Version\s*([\d.]+)", clang_format_version, re.IGNORECASE
+ ).group(1)
if version_number not in compatible_version_list:
sys.exit(
"""
*** No compatible clang-format program found.
***
*** Install any of the following versions
- ***""" + ", ".join(compatible_version_list)
+ ***"""
+ + ", ".join(compatible_version_list)
)
except subprocess.CalledProcessError as subprocess_error:
raise SystemExit(subprocess_error)
#
# Generate a temporary file and copy the contents of the given file.
#
- _, temp_file_name = mkstemp(dir=temp_dir,
- prefix=file_name+'.',
- suffix='.tmp')
+ _, temp_file_name = mkstemp(dir=temp_dir, prefix=file_name + ".", suffix=".tmp")
shutil.copyfile(full_file_name, temp_file_name)
#
# Prepare command line statement to be executed by a subprocess call
# to apply formatting to file_name.
#
- apply_clang_format_str = parsed_arguments.clang_format_binary + ' ' + \
- full_file_name + " > " + temp_file_name
+ apply_clang_format_str = (
+ parsed_arguments.clang_format_binary
+ + " "
+ + full_file_name
+ + " > "
+ + temp_file_name
+ )
try:
subprocess.call(apply_clang_format_str, shell=True)
except OSError as os_error:
# available threads less one.
#
if n_threads == 0:
- n_threads = (n_available_threads-1) if n_available_threads > 1 else 1
+ n_threads = (n_available_threads - 1) if n_available_threads > 1 else 1
logging.info("Number of threads picked up: %d", n_threads)
# a target with given arguments.
#
for _ in range(n_threads):
- thread_worker = threading.Thread(target=format_file,
- args=(arguments, task_queue, tmpdir))
+ thread_worker = threading.Thread(
+ target=format_file, args=(arguments, task_queue, tmpdir)
+ )
thread_worker.daemon = True
thread_worker.start()
# Look through all directories, recursively, and find all files
# that match the given regex.
#
- for directory in arguments.directories.split(','):
+ for directory in arguments.directories.split(","):
for dirpath, _, filenames in os.walk(directory):
- for pattern in arguments.regex.split(','):
+ for pattern in arguments.regex.split(","):
for file_name in fnmatch.filter(filenames, pattern):
task_queue.put(os.path.join(dirpath, file_name))
#
# contrib/utlitlies/programs/clang-16/bin
#
if not PARSED_ARGUMENTS.clang_format_binary:
- os.environ["PATH"] += ':' + \
- os.getcwd() + "/contrib/utilities/programs/clang-16/bin"
+ os.environ["PATH"] += (
+ ":" + os.getcwd() + "/contrib/utilities/programs/clang-16/bin"
+ )
PARSED_ARGUMENTS.clang_format_binary = distutils.spawn.find_executable(
- "clang-format")
+ "clang-format"
+ )
#
# Do not log verbose information on dry-run.
else:
logging.basicConfig(level=logging.INFO)
- check_clang_format_version(PARSED_ARGUMENTS.clang_format_binary,
- ['6.0.0', '6.0.1'])
+ check_clang_format_version(PARSED_ARGUMENTS.clang_format_binary, ["6.0.0", "6.0.1"])
process(PARSED_ARGUMENTS)
FINISH = time.time()
- logging.info("Finished code formatting in: %f seconds.", (FINISH-START))
+ logging.info("Finished code formatting in: %f seconds.", (FINISH - START))
python 3.
"""
if sys.version_info.major > 2:
- return str(string, 'utf8').splitlines()
+ return str(string, "utf8").splitlines()
else:
- return unicode(string, errors='replace').splitlines()
+ return unicode(string, errors="replace").splitlines()
class DeprecatedDeclaration(object):
for information regarding when the deprecation notice appeared. The line
itself is printed out later.
"""
+
def __init__(self, line):
assert "DEAL_II_DEPRECATED" in line
# in case the line contains extra ':'s, split input based on where grep
# puts the line number:
line_number_re = re.search(":[0-9]+:", line)
if line_number_re:
- line_number_range = (line_number_re.regs[0][0] + 1,
- line_number_re.regs[0][1] - 1)
- self.file_name = line[0:line_number_range[0] - 1]
+ line_number_range = (
+ line_number_re.regs[0][0] + 1,
+ line_number_re.regs[0][1] - 1,
+ )
+ self.file_name = line[0 : line_number_range[0] - 1]
self.line_n = int(line[slice(*line_number_range)])
- self.deprecation_line = line[line_number_range[1] + 1:].strip()
+ self.deprecation_line = line[line_number_range[1] + 1 :].strip()
else:
- raise ValueError("The given line does not contain a line number of "
- "the form, e.g., :42:.")
+ raise ValueError(
+ "The given line does not contain a line number of "
+ "the form, e.g., :42:."
+ )
- git_log_output = subprocess.check_output(["git", "blame", "-p",
- "-L", "{0},{0}".format(self.line_n),
- self.file_name])
+ git_log_output = subprocess.check_output(
+ ["git", "blame", "-p", "-L", "{0},{0}".format(self.line_n), self.file_name]
+ )
self.git_log_output = decode_and_split(git_log_output)
- self.commit_hash = self.git_log_output[0].split(' ')[0]
- self.commit_summary = self.git_log_output[9][len("summary "):]
- self.epoch_time = int(self.git_log_output[7][len("commiter-time "):])
- self.output_time = datetime.datetime.fromtimestamp(self.epoch_time, datetime.UTC)
-
- git_tag_output = subprocess.check_output(["git", "tag", "--contains",
- self.commit_hash,
- "-l", "v[0-9].[0-9].[0-9]"])
+ self.commit_hash = self.git_log_output[0].split(" ")[0]
+ self.commit_summary = self.git_log_output[9][len("summary ") :]
+ self.epoch_time = int(self.git_log_output[7][len("commiter-time ") :])
+ self.output_time = datetime.datetime.fromtimestamp(
+ self.epoch_time, datetime.UTC
+ )
+
+ git_tag_output = subprocess.check_output(
+ ["git", "tag", "--contains", self.commit_hash, "-l", "v[0-9].[0-9].[0-9]"]
+ )
git_tag_output = decode_and_split(git_tag_output)
if git_tag_output:
# matched tags must start with 'v[0-9]': skip the v
else:
self.release = ""
-
def print_record(self):
"""Print a description of the record to stdout. The 'Release' field
corresponds to the release number in which the declaration was first
def main():
# check that we are in the top directory
- if not all((os.path.isdir(directory)
- for directory in ["./include", "./tests", "./examples"])):
- raise Exception("This script must be called from the top-level directory of deal.II.")
- result = subprocess.check_output(["grep", "-R", "--line-number", "DEAL_II_DEPRECATED",
- "./include/"])
+ if not all(
+ (
+ os.path.isdir(directory)
+ for directory in ["./include", "./tests", "./examples"]
+ )
+ ):
+ raise Exception(
+ "This script must be called from the top-level directory of deal.II."
+ )
+ result = subprocess.check_output(
+ ["grep", "-R", "--line-number", "DEAL_II_DEPRECATED", "./include/"]
+ )
result = decode_and_split(result)
deprecated_declarations = list()
for line in result:
try:
deprecated_declarations.append(DeprecatedDeclaration(line))
- except subprocess.CalledProcessError: # ignore errors coming from git
+ except subprocess.CalledProcessError: # ignore errors coming from git
pass
deprecated_declarations.sort(key=lambda u: u.epoch_time)
pass
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
import argparse
from argparse import RawTextHelpFormatter
-__author__ = 'The authors of deal.II'
-__copyright__ = 'Copyright 2024, deal.II'
-__license__ = 'GNU GPL 2 or later'
+__author__ = "The authors of deal.II"
+__copyright__ = "Copyright 2024, deal.II"
+__license__ = "GNU GPL 2 or later"
def get_parameter_value(parameters, name):
- """ Given a dictionary of parameters with a structure as
+ """Given a dictionary of parameters with a structure as
the one created by read_parameter_file(), return the value
of the parameter with the given name. Returns None if the
parameter is not found.
return None
-
def set_parameter_value(parameters, name, value):
- """ Given a dictionary of parameters with a structure as
+ """Given a dictionary of parameters with a structure as
the one created by read_parameter_file(), recursively search
through the subsections and set the value
of the first parameter with the given name to the given value.
def split_parameter_line(line):
- """ Read a 'set parameter' line and extract the name, value, and format. """
+ """Read a 'set parameter' line and extract the name, value, and format."""
- equal_index = line.find('=')
+ equal_index = line.find("=")
# Determine number of additional spaces left of equal sign.
# We need to store these separately, because there might be two
# lines setting the same parameter, but different number of spaces. They
alignment_spaces = len(line[:equal_index]) - len(line[:equal_index].rstrip())
# skip initial word "set" in parameter name
- words_left_of_equal_sign = line[:equal_index].replace("\\\n","").split()
+ words_left_of_equal_sign = line[:equal_index].replace("\\\n", "").split()
param_name = words_left_of_equal_sign[1:]
- param_name = ' '.join(param_name)
+ param_name = " ".join(param_name)
# strip spaces at end of value string, keep all inline comments
- param_value = line[equal_index+1:].rstrip()
+ param_value = line[equal_index + 1 :].rstrip()
# if there is one or more spaces at the start of the string, remove one space.
# keep additional spaces, because they are part of the formatting.
# this way we can add one space when writing the file back and keep the formatting
- if param_value.startswith(' ') and len(param_value) > 1:
+ if param_value.startswith(" ") and len(param_value) > 1:
param_value = param_value[1:]
return param_name, param_value, alignment_spaces
-
def read_value_or_subsection(input_file, parameters):
- """ Read a value or a subsection from a parameter file into a parameter dictionary.
- """
+ """Read a value or a subsection from a parameter file into a parameter dictionary."""
# Keep track of the comment lines to
# add them to the next parameter or subsection
while line[-1] == "\\":
line += "\n" + next(input_file).rstrip()
- words = line.replace("\\\n","").split()
+ words = line.replace("\\\n", "").split()
# Attach empty lines if we are inside a comment
if line == "" or len(words) == 0:
elif line[0] == "#":
if accumulated_comment != "":
accumulated_comment += "\n"
- accumulated_comment += line.replace("\\\n","")
+ accumulated_comment += line.replace("\\\n", "")
# If we encounter a 'subsection' line, store the subsection name
# and recursively call this function to read the subsection
elif words[0] == "subsection":
- subsection_name = ' '.join(words[1:]).replace("\\","")
+ subsection_name = " ".join(words[1:]).replace("\\", "")
if subsection_name not in parameters:
- parameters[subsection_name] = {"comment": "", "value" : dict({}), "type": "subsection"}
+ parameters[subsection_name] = {
+ "comment": "",
+ "value": dict({}),
+ "type": "subsection",
+ }
if parameters[subsection_name]["comment"] != "":
parameters[subsection_name]["comment"] += "\n"
parameters[subsection_name]["comment"] += accumulated_comment
accumulated_comment = ""
- parameters[subsection_name]["value"].update(read_value_or_subsection(input_file, parameters[subsection_name]["value"]))
+ parameters[subsection_name]["value"].update(
+ read_value_or_subsection(
+ input_file, parameters[subsection_name]["value"]
+ )
+ )
# If we encounter a 'set' line, store the parameter name and value
- elif words[0] == 'set':
+ elif words[0] == "set":
name, value, alignment_spaces = split_parameter_line(line)
- parameters[name] = {"comment": accumulated_comment, "value": value, "alignment spaces": alignment_spaces, "type": "parameter"}
+ parameters[name] = {
+ "comment": accumulated_comment,
+ "value": value,
+ "alignment spaces": alignment_spaces,
+ "type": "parameter",
+ }
accumulated_comment = ""
elif words[0] == "include":
- name = ' '.join(words[1:])
- value = ''
+ name = " ".join(words[1:])
+ value = ""
alignment_spaces = 0
- parameters[name] = {"comment": accumulated_comment, "value": value, "alignment spaces": alignment_spaces, "type": "include"}
+ parameters[name] = {
+ "comment": accumulated_comment,
+ "value": value,
+ "alignment spaces": alignment_spaces,
+ "type": "include",
+ }
accumulated_comment = ""
elif words[0] == "end":
# sometimes there are comments at the end of files or subsection. store them in their own parameter
if accumulated_comment != "":
- parameters["postcomment"] = {"comment": accumulated_comment, "value": "", "alignment spaces": 0, "type": "comment"}
+ parameters["postcomment"] = {
+ "comment": accumulated_comment,
+ "value": "",
+ "alignment spaces": 0,
+ "type": "comment",
+ }
accumulated_comment = ""
return parameters
# sometimes there are comments at the end of files or subsection. store them in their own parameter
if accumulated_comment != "":
- parameters["postcomment"] = {"comment": accumulated_comment, "value": "", "alignment spaces": 0, "type": "comment"}
+ parameters["postcomment"] = {
+ "comment": accumulated_comment,
+ "value": "",
+ "alignment spaces": 0,
+ "type": "comment",
+ }
accumulated_comment = ""
return parameters
-
def read_parameter_file(file):
- """ Read parameter file, and return a dictionary with all values.
+ """Read parameter file, and return a dictionary with all values.
The returned dictionary contains as keys the name of the subsection,
include statement or parameter, and as value a dictionary with
parameters = dict({})
- with open(file, 'r') as f:
+ with open(file, "r") as f:
read_value_or_subsection(f, parameters)
return parameters
-
def write_comment_if_existent(comment, prepend_spaces, file):
- """ Print the comment lines, take care to use the correct indentation.
- """
+ """Print the comment lines, take care to use the correct indentation."""
if comment != "":
for line in comment.split("\n"):
if line != "":
file.write(line + "\n")
-
def write_value_or_subsection(parameters, prepend_spaces, file):
- """ Write a parameters dictionary recursively into a given file.
+ """Write a parameters dictionary recursively into a given file.
prepend_spaces tracks the current indentation level.
"""
# Add empty line before comments
if first_entry == False and parameters[entry]["comment"] != "":
file.write("\n")
- write_comment_if_existent(parameters[entry]["comment"], prepend_spaces, file)
+ write_comment_if_existent(
+ parameters[entry]["comment"], prepend_spaces, file
+ )
# Only add a space after equal sign if the value is not empty
space_if_value = " " if parameters[entry]["value"] != "" else ""
- file.write(" " * prepend_spaces + "set " + entry + " " * parameters[entry]["alignment spaces"] + "=" \
- + space_if_value + parameters[entry]["value"] + "\n")
+ file.write(
+ " " * prepend_spaces
+ + "set "
+ + entry
+ + " " * parameters[entry]["alignment spaces"]
+ + "="
+ + space_if_value
+ + parameters[entry]["value"]
+ + "\n"
+ )
elif parameters[entry]["type"] == "include":
# Add empty line before include
if first_entry == False:
file.write("\n")
- write_comment_if_existent(parameters[entry]["comment"], prepend_spaces, file)
+ write_comment_if_existent(
+ parameters[entry]["comment"], prepend_spaces, file
+ )
# Write the include
file.write(" " * prepend_spaces + "include " + entry + "\n")
elif parameters[entry]["type"] == "subsection":
if first_entry == False:
file.write("\n")
- write_comment_if_existent(parameters[entry]["comment"], prepend_spaces, file)
+ write_comment_if_existent(
+ parameters[entry]["comment"], prepend_spaces, file
+ )
file.write(" " * prepend_spaces + "subsection " + entry + "\n")
prepend_spaces += 2
elif parameters[entry]["type"] == "comment":
if first_entry == False and parameters[entry]["comment"] != "":
file.write("\n")
- write_comment_if_existent(parameters[entry]["comment"], prepend_spaces, file)
+ write_comment_if_existent(
+ parameters[entry]["comment"], prepend_spaces, file
+ )
first_entry = False
return 0
-
def write_parameter_file(parameters, file):
- """ Given a dictionary of parameters with a structure as
+ """Given a dictionary of parameters with a structure as
the one created by read_parameter_file(), write the dictionary
to a file.
"""
prepend_spaces = 0
- with open(file,'w') as f:
+ with open(file, "w") as f:
write_value_or_subsection(parameters, prepend_spaces, f)
return 0
-
def main(input_file, output_file):
- """ This function reformats the given input .prm files to follow our
+ """This function reformats the given input .prm files to follow our
general formatting guidelines.
"""
parameters = read_parameter_file(input_file)
write_parameter_file(parameters, output_file)
-
-if __name__ == '__main__':
+if __name__ == "__main__":
parser = argparse.ArgumentParser(
- prog='deal.II .prm file reformatter',
- description=
-"""Reformats deal.II .prm files to follow our general formatting guidelines.
+ prog="deal.II .prm file reformatter",
+ description="""Reformats deal.II .prm files to follow our general formatting guidelines.
The script expects two arguments, a path to the file to be formatted, and a
path to which the formatted output should be written. If the two paths are
identical the given file is overwritten with the formatted output.
This is not always perfectly possible.
- retain broken lines (`\\`) in values of parameters and comments, remove
them from subsection or parameter names. """,
- formatter_class=RawTextHelpFormatter)
+ formatter_class=RawTextHelpFormatter,
+ )
- parser.add_argument('input_file', type=str, help='The .prm file to reformat.')
- parser.add_argument('output_file', type=str, help='The .prm file to write the reformatted file to.')
+ parser.add_argument("input_file", type=str, help="The .prm file to reformat.")
+ parser.add_argument(
+ "output_file", type=str, help="The .prm file to write the reformatted file to."
+ )
args = parser.parse_args()
sys.exit(main(args.input_file, args.output_file))
## This script runs install_name_tool on each library under basedir (first argument
## on command line) and makes sure that all libraries are installed with absolute
## id name. This makes Mac OS X happy about not using DYLD_LIBRARY_PATH, which is generally
-## a bad thing.
+## a bad thing.
import os
import sys
from subprocess import check_output as run
-basedir = '/Applications/deal.II.app/Contents/Resources/opt/'
+basedir = "/Applications/deal.II.app/Contents/Resources/opt/"
if len(sys.argv) > 1:
basedir = sys.argv[1]
## Lib object
-#
+#
# Stores the name of a library, its install name, its location and all its dependencies, as given by `otool -L`
+
class Lib(object):
location = None
install_name = None
name = None
deps = None
+
def __str__(self):
mystr = ""
- mystr += "Name :"+str(self.name)
- mystr +="\nInstall name:"+str(self.install_name)
- mystr +="\nLocation :"+str(self.location)
- mystr +="\nDeps : ... "
+ mystr += "Name :" + str(self.name)
+ mystr += "\nInstall name:" + str(self.install_name)
+ mystr += "\nLocation :" + str(self.location)
+ mystr += "\nDeps : ... "
return mystr
+
# Walk the current tree, and extract all libraries
def get_libs():
libraries = []
if os.path.isfile(filename) and f.endswith("dylib"):
a = Lib()
a.name = f
- a.install_name = run(["otool", "-D", filename]).split('\n')[1]
- a.location= os.path.join(root, f)
- long_deps = run(["otool", "-L", a.location]).split('\n')
- a.deps = [dep.partition(' ')[0][1::] for dep in long_deps[2:-1]]
+ a.install_name = run(["otool", "-D", filename]).split("\n")[1]
+ a.location = os.path.join(root, f)
+ long_deps = run(["otool", "-L", a.location]).split("\n")
+ a.deps = [dep.partition(" ")[0][1::] for dep in long_deps[2:-1]]
libraries += [a]
return libraries
# # Fix all install names first
-#
+#
# Some will fail, because they are either stub files, or system files...
# In[ ]:
continue
if i.install_name != i.location:
try:
- run(["install_name_tool",'-id',i.location, i.location])
+ run(["install_name_tool", "-id", i.location, i.location])
except:
- print("Failed: ",i.name)
- print( "(",libraries[c].name,")")
+ print("Failed: ", i.name)
+ print("(", libraries[c].name, ")")
failed += [c]
-print (failed)
-print ('Removing failed libs...')
+print(failed)
+print("Removing failed libs...")
for fail in reversed(failed):
- print ("Removing from list",libraries[fail].name)
+ print("Removing from list", libraries[fail].name)
del libraries[fail]
# # Fix all dependencies with absolute paths
-for c in xrange(len(libraries)):
+for c in xrange(len(libraries)):
this_lib = libraries[c]
if this_lib.install_name != this_lib.location:
- print('Not valid:', i.name)
+ print("Not valid:", i.name)
else:
lib = this_lib.name
- command = ['install_name_tool']
+ command = ["install_name_tool"]
for dep in this_lib.deps:
for loc in libraries:
if dep.find(loc.name) != -1 and dep != loc.install_name:
- command += ['-change', dep, loc.install_name]
+ command += ["-change", dep, loc.install_name]
break
try:
if len(command) != 1:
command += [this_lib.location]
- print('Processing', lib)
- print('======================\n\n')
+ print("Processing", lib)
+ print("======================\n\n")
print(" ".join(command))
- print('======================\n\n')
+ print("======================\n\n")
run(command)
except:
- print('\n\n*********************************************')
- print('Last command failed!')
+ print("\n\n*********************************************")
+ print("Last command failed!")
print(" ".join(command))
- print('*********************************************\n\n')
+ print("*********************************************\n\n")
# We used to rewrap the text to 78 columns in this function (hence
# the name), but we no longer do this. Check the history for the
# implementation.
- return [startwith+line for line in lines]
+ return [startwith + line for line in lines]
+
# strips whitespace and leading "*" from each lines
def remove_junk(lines):
out.append(line)
return out
+
# returns True if at least one entry in @p list is contained in @p str
def one_in(list, str):
for li in list:
return True
return False
+
# returns True if @p str starts with one of the entries in @p list
def starts_with_one(list, str):
for li in list:
return True
return False
+
# take a doxygen comment block "/** bla ... */" given as a list of lines and
# format it in a pretty way rewrapping lines while taking care to keep certain
# structure.
def format_block(lines, infostr=""):
- if len(lines)==1 and "/*" in lines[0] and "*/" in lines[0]:
+ if len(lines) == 1 and "/*" in lines[0] and "*/" in lines[0]:
return lines
- if (not "/**" in lines[0]
- or not "*/" in lines[-1]):
- print("%s not a code block"%infostr, file=sys.stderr)
+ if not "/**" in lines[0] or not "*/" in lines[-1]:
+ print("%s not a code block" % infostr, file=sys.stderr)
return lines
for line in lines[1:-1]:
- assert(not "/*" in line)
- assert(not "*/" in line)
+ assert not "/*" in line
+ assert not "*/" in line
- lines[-1]=lines[-1].replace("**/","*/")
+ lines[-1] = lines[-1].replace("**/", "*/")
if not lines[0].strip().startswith("/**"):
- print ("%s error, ignoring code block with junk in same line before"%infostr, file=sys.stderr)
+ print(
+ "%s error, ignoring code block with junk in same line before" % infostr,
+ file=sys.stderr,
+ )
return lines
if not lines[-1].strip().endswith("*/"):
- print ("%s error, ignoring code block not ending at end of line"%infostr, file=sys.stderr)
+ print(
+ "%s error, ignoring code block not ending at end of line" % infostr,
+ file=sys.stderr,
+ )
return lines
- if lines[0].strip()!="/**":
- #print ("%s warning code block not starting in separate line"%infostr, file=sys.stderr)
+ if lines[0].strip() != "/**":
+ # print ("%s warning code block not starting in separate line"%infostr, file=sys.stderr)
idx = lines[0].find("/**")
- temp = [lines[0][0:idx+3], lines[0][idx+3:]]
+ temp = [lines[0][0 : idx + 3], lines[0][idx + 3 :]]
temp.extend(lines[1:])
lines = temp
- if lines[-1].strip()!="*/":
- #print ("%s warning code block not ending in separate line"%infostr, file=sys.stderr)
+ if lines[-1].strip() != "*/":
+ # print ("%s warning code block not ending in separate line"%infostr, file=sys.stderr)
idx = lines[-1].find("*/")
temp = lines[0:-1]
temp.append(lines[-1][0:idx])
lines = temp
idx = lines[0].find("/**")
- start = lines[0][:idx]+" * "
-
+ start = lines[0][:idx] + " * "
+
out = [lines[0].rstrip()]
idx = 1
- endidx = len(lines)-1
+ endidx = len(lines) - 1
curlines = []
- ops_startline = ["<li>", "@param", "@returns", "@warning", "@ingroup", "@author", "@date", "@related", "@relates", "@relatesalso", "@deprecated", "@image", "@return", "@brief", "@attention", "@copydoc", "@addtogroup", "@todo", "@tparam", "@see", "@note", "@skip", "@skipline", "@until", "@line", "@dontinclude", "@include"]
+ ops_startline = [
+ "<li>",
+ "@param",
+ "@returns",
+ "@warning",
+ "@ingroup",
+ "@author",
+ "@date",
+ "@related",
+ "@relates",
+ "@relatesalso",
+ "@deprecated",
+ "@image",
+ "@return",
+ "@brief",
+ "@attention",
+ "@copydoc",
+ "@addtogroup",
+ "@todo",
+ "@tparam",
+ "@see",
+ "@note",
+ "@skip",
+ "@skipline",
+ "@until",
+ "@line",
+ "@dontinclude",
+ "@include",
+ ]
# subset of ops_startline that does not want stuff from the next line appended
# to this.
- ops_also_end_paragraph = ["@image", "@skip", "@skipline", "@until", "@line", "@dontinclude", "@include"]
+ ops_also_end_paragraph = [
+ "@image",
+ "@skip",
+ "@skipline",
+ "@until",
+ "@line",
+ "@dontinclude",
+ "@include",
+ ]
# stuff handled in the while loop down: @code, @verbatim, @f @ref
# separate and do not break:
ops_title_line = ["@page", "@name"]
- #todo:
- # @arg @c @cond @em @endcond @f{ @internal @name @post @pre @sa
+ # todo:
+ # @arg @c @cond @em @endcond @f{ @internal @name @post @pre @sa
- while idx<endidx:
+ while idx < endidx:
if one_in(ops_separate_line, lines[idx]):
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = remove_junk([lines[idx]])[0]
for it in ops_separate_line:
- if it in thisline and thisline!=it:
- print ("%s warning %s not in separate line"%(infostr, it), file=sys.stderr)
+ if it in thisline and thisline != it:
+ print(
+ "%s warning %s not in separate line" % (infostr, it),
+ file=sys.stderr,
+ )
out.append(start + thisline)
- elif re.match(r'\*\s+- ',lines[idx].strip()):
+ elif re.match(r"\*\s+- ", lines[idx].strip()):
# bullet ('-') list
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = lines[idx].strip()[2:]
out.append(start + thisline)
- elif lines[idx].strip().startswith("* ") and re.match(r'\s*\d+.',lines[idx][3:]):
+ elif lines[idx].strip().startswith("* ") and re.match(
+ r"\s*\d+.", lines[idx][3:]
+ ):
# numbered list
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = lines[idx].strip()[2:]
out.append(start + thisline)
-
+
elif one_in(ops_title_line, lines[idx]):
# do not break @page, etc.
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = remove_junk([lines[idx]])[0]
-
+
if not thisline.split(" ")[0] in ops_title_line:
- print ("%s warning: @page/@name not at start of line"%(infostr), file=sys.stderr)
+ print(
+ "%s warning: @page/@name not at start of line" % (infostr),
+ file=sys.stderr,
+ )
out.append(start + thisline.strip())
elif "@ref" in lines[idx]:
# @ref link "some long description"
# is special, and we mustn't break it
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = remove_junk([lines[idx]])[0]
if not thisline.startswith("@ref") and not thisline.startswith("(@ref"):
- print ("%s warning %s not at start of line"%(infostr, "@ref"), file=sys.stderr)
+ print(
+ "%s warning %s not at start of line" % (infostr, "@ref"),
+ file=sys.stderr,
+ )
# format:
# @ref name "some text" blub
# or @ref name blurb
withquotes = thisline.split('"')
- if len(withquotes)==3:
- thisline = withquotes[0]+'"'+withquotes[1]+'"'
+ if len(withquotes) == 3:
+ thisline = withquotes[0] + '"' + withquotes[1] + '"'
remain = withquotes[2]
- for st in [')', '.', ',', ':']:
+ for st in [")", ".", ",", ":"]:
if remain.startswith(st):
thisline = thisline + st
remain = remain[1:]
# do not wrap the @ref line:
out.append(start + thisline.strip())
- if len(withquotes[0].strip().split(' '))!=2:
- print ("%s warning @ref line looks broken"%(infostr), file=sys.stderr)
- elif len(withquotes)==1:
+ if len(withquotes[0].strip().split(" ")) != 2:
+ print(
+ "%s warning @ref line looks broken" % (infostr), file=sys.stderr
+ )
+ elif len(withquotes) == 1:
words = thisline.strip().split(" ")
- if len(words)<2 or len(words[0])==0 or len(words[1])==0:
- print ("%s warning @ref line looks broken"%(infostr), file=sys.stderr)
- thisline = words[0] + ' ' + words[1]
+ if len(words) < 2 or len(words[0]) == 0 or len(words[1]) == 0:
+ print(
+ "%s warning @ref line looks broken" % (infostr), file=sys.stderr
+ )
+ thisline = words[0] + " " + words[1]
out.append(start + thisline.strip())
remain = " ".join(words[2:])
else:
- print ("%s warning @ref quotes are not in single line"%(infostr), file=sys.stderr)
- remain = ''
+ print(
+ "%s warning @ref quotes are not in single line" % (infostr),
+ file=sys.stderr,
+ )
+ remain = ""
- if len(remain)>0:
+ if len(remain) > 0:
curlines.append(remain)
-
+
elif one_in(ops_startline, lines[idx]):
- if curlines!=[]:
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
thisline = remove_junk([lines[idx]])[0]
if not starts_with_one(ops_startline, thisline):
for it in ops_startline:
if it in thisline:
- print ("%s warning %s not at start of line"%(infostr, it), file=sys.stderr)
+ print(
+ "%s warning %s not at start of line" % (infostr, it),
+ file=sys.stderr,
+ )
if one_in(ops_also_end_paragraph, lines[idx]):
out.append(lines[idx].rstrip())
else:
elif one_in(["@code", "@verbatim", "@f[", "@f{"], lines[idx]):
if "@f{" in lines[idx]:
if not lines[idx].endswith("}{"):
- print ("%s warning malformed @f{*}{"%(infostr), file=sys.stderr)
- if curlines!=[]:
+ print("%s warning malformed @f{*}{" % (infostr), file=sys.stderr)
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
+ curlines = []
while True:
thisline = lines[idx].rstrip()
- if thisline.strip()=="*":
+ if thisline.strip() == "*":
thisline = start
- elif thisline.strip()=="@code" or thisline.strip()=="@endcode":
+ elif thisline.strip() == "@code" or thisline.strip() == "@endcode":
thisline = start + thisline.strip()
- elif thisline.strip()[0:2]!="* ":
- if thisline[0:len(start)].strip()=="":
+ elif thisline.strip()[0:2] != "* ":
+ if thisline[0 : len(start)].strip() == "":
# just a missing *, so keep old indentation
- thisline = start + thisline[len(start):]
+ thisline = start + thisline[len(start) :]
else:
# no way to recover indentation:
- print ("%s Error: wrong formatting inside @code block"%infostr, file=sys.stderr)
+ print(
+ "%s Error: wrong formatting inside @code block" % infostr,
+ file=sys.stderr,
+ )
thisline = start + thisline.strip()
else:
thisline = start + thisline.strip()[2:]
if one_in(["@endcode", "@endverbatim", "@f]", "@f}"], lines[idx]):
break
idx += 1
- elif lines[idx].strip()=="*":
- if curlines!=[]:
+ elif lines[idx].strip() == "*":
+ if curlines != []:
out.extend(wrap_block(remove_junk(curlines), start))
- curlines=[]
- out.append(start[:-1]) #skip whitespace at the end
+ curlines = []
+ out.append(start[:-1]) # skip whitespace at the end
else:
curlines.append(lines[idx])
idx += 1
- if curlines!=[]:
- out.extend(wrap_block(remove_junk(curlines), start))
+ if curlines != []:
+ out.extend(wrap_block(remove_junk(curlines), start))
out.append(start[0:-2] + lines[-1].strip())
# test the routines:
-lineI = [" * blub",
- " * two three ",
- " * four"]
-lineO = ["blub",
- "two three",
- "four"]
-assert(remove_junk(lineI)==lineO)
-
-lineI = ["blub",
- "two three",
- "four"]
-lineO = [" * blub",
- " * two three",
- " * four"]
-assert(wrap_block(lineI," * ")==lineO)
-
-lineI = [" * 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2",\
- " * A 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0"]
-assert(wrap_block(remove_junk(lineI)," * ")==lineI)
-
-lineI = [" * Structure which is passed to Triangulation::create_triangulation. It",\
- " * contains all data needed to construct a cell, namely the indices of the",\
- " * vertices and the material indicator."]
-assert(wrap_block(remove_junk(lineI)," * ")==lineI)
-
-lineI = [" /**",
- " * blub",
- " * two three",
- " * four",
- " */"]
-lineO = [" /**",
- " * blub two three four",
- " */"]
-assert(format_block(lineI)==lineI)
-
-lineI = [" /**",
- " * blub",
- " * two three",
- " * ",
- " * four",
- " */"]
-lineO = [" /**",
- " * blub",
- " * two three",
- " *",
- " * four",
- " */"]
-assert(format_block(lineI)==lineO)
-
-lineI = [" /**",
- " * blub",
- " * @code",
- " * two three",
- " * @endcode",
- " * four",
- " */"]
-assert(format_block(lineI)==lineI)
-
-lineI = [" /**",
- " * blub",
- " * @code ",
- " * two three",
- " * two three ",
- " * ",
- " * two three",
- " * @endcode ",
- " * four",
- " */"]
-lineO = [" /**",
- " * blub",
- " * @code",
- " * two three",
- " * two three",
- " *",
- " * two three",
- " * @endcode",
- " * four",
- " */"]
-assert(format_block(lineI)==lineO)
-
-lineI = [" /**",
- " * blub",
- " @code ",
- " two three",
- " @endcode ",
- " * four",
- " */"]
-lineO = [" /**",
- " * blub",
- " * @code",
- " * two three",
- " * @endcode",
- " * four",
- " */"]
-assert(format_block(lineI)==lineO)
-
-
-lineI = [" /**",
- " * blub",
- " * @code ",
- " * two three",
- " * two three ",
- " * ",
- " two three",
- " ",
- " * @endcode ",
- " * four",
- " */"]
-lineO = [" /**",
- " * blub",
- " * @code",
- " * two three",
- " * two three",
- " *",
- " * two three",
- " *",
- " * @endcode",
- " * four",
- " */"]
-assert(format_block(lineI)==lineO)
-
-
-
-lineI = [" /**",
- " * blub",
- " * <ul>",
- " * <li> bla",
- " * <li> blub",
- " * </ul>",
- " */"]
-assert(format_block(lineI)==lineI)
-
-lineI = [" /** @addtogroup Exceptions",
- " * @{ */"]
-lineO = [" /**",
- " * @addtogroup Exceptions",
- " * @{",
- " */"]
-assert(format_block(lineI)==lineO)
-
-lineI = [" /** ",
- " * bla",
- " * @image testing.png",
- " * blub",
- " */"]
-lineO = [" /**",
- " * bla",
- " * @image testing.png",
- " * blub",
- " */"]
-assert(format_block(lineI)==lineO)
-
-lineI = [" /** ",
- " * @ref a b c d e",
- " * @ref a \"b c\" d dd",
- " */"]
-lineO = [" /**",
- " * @ref a",
- " * b c d e",
- " * @ref a \"b c\"",
- " * d dd",
- " */"]
-assert(format_block(lineI)==lineO)
-
-long = "long "*20
-lineI = [" /** ",
- " * @ref a \""+long+"\" d",
- " */"]
-lineO = [" /**",
- " * @ref a \""+long+"\"",
- " * d",
- " */"]
-assert(format_block(lineI)==lineO)
-
-lineI = [" /** ",
- " * @ref a. c",
- " * @ref a \"b c\". c2",
- " */"]
-lineO = [" /**",
- " * @ref a.",
- " * c",
- " * @ref a \"b c\".",
- " * c2",
- " */"]
-assert(format_block(lineI)==lineO)
+lineI = [" * blub", " * two three ", " * four"]
+lineO = ["blub", "two three", "four"]
+assert remove_junk(lineI) == lineO
+
+lineI = ["blub", "two three", "four"]
+lineO = [" * blub", " * two three", " * four"]
+assert wrap_block(lineI, " * ") == lineO
+
+lineI = [
+ " * 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0 1 2",
+ " * A 4 5 6 7 9 0 1 2 3 4 5 6 7 9 0",
+]
+assert wrap_block(remove_junk(lineI), " * ") == lineI
+
+lineI = [
+ " * Structure which is passed to Triangulation::create_triangulation. It",
+ " * contains all data needed to construct a cell, namely the indices of the",
+ " * vertices and the material indicator.",
+]
+assert wrap_block(remove_junk(lineI), " * ") == lineI
+
+lineI = [" /**", " * blub", " * two three", " * four", " */"]
+lineO = [" /**", " * blub two three four", " */"]
+assert format_block(lineI) == lineI
+
+lineI = [" /**", " * blub", " * two three", " * ", " * four", " */"]
+lineO = [" /**", " * blub", " * two three", " *", " * four", " */"]
+assert format_block(lineI) == lineO
+
+lineI = [
+ " /**",
+ " * blub",
+ " * @code",
+ " * two three",
+ " * @endcode",
+ " * four",
+ " */",
+]
+assert format_block(lineI) == lineI
+
+lineI = [
+ " /**",
+ " * blub",
+ " * @code ",
+ " * two three",
+ " * two three ",
+ " * ",
+ " * two three",
+ " * @endcode ",
+ " * four",
+ " */",
+]
+lineO = [
+ " /**",
+ " * blub",
+ " * @code",
+ " * two three",
+ " * two three",
+ " *",
+ " * two three",
+ " * @endcode",
+ " * four",
+ " */",
+]
+assert format_block(lineI) == lineO
+
+lineI = [
+ " /**",
+ " * blub",
+ " @code ",
+ " two three",
+ " @endcode ",
+ " * four",
+ " */",
+]
+lineO = [
+ " /**",
+ " * blub",
+ " * @code",
+ " * two three",
+ " * @endcode",
+ " * four",
+ " */",
+]
+assert format_block(lineI) == lineO
+
+
+lineI = [
+ " /**",
+ " * blub",
+ " * @code ",
+ " * two three",
+ " * two three ",
+ " * ",
+ " two three",
+ " ",
+ " * @endcode ",
+ " * four",
+ " */",
+]
+lineO = [
+ " /**",
+ " * blub",
+ " * @code",
+ " * two three",
+ " * two three",
+ " *",
+ " * two three",
+ " *",
+ " * @endcode",
+ " * four",
+ " */",
+]
+assert format_block(lineI) == lineO
+
+
+lineI = [
+ " /**",
+ " * blub",
+ " * <ul>",
+ " * <li> bla",
+ " * <li> blub",
+ " * </ul>",
+ " */",
+]
+assert format_block(lineI) == lineI
+
+lineI = [" /** @addtogroup Exceptions", " * @{ */"]
+lineO = [" /**", " * @addtogroup Exceptions", " * @{", " */"]
+assert format_block(lineI) == lineO
+
+lineI = [" /** ", " * bla", " * @image testing.png", " * blub", " */"]
+lineO = [" /**", " * bla", " * @image testing.png", " * blub", " */"]
+assert format_block(lineI) == lineO
+
+lineI = [" /** ", " * @ref a b c d e", ' * @ref a "b c" d dd', " */"]
+lineO = [" /**", " * @ref a", " * b c d e", ' * @ref a "b c"', " * d dd", " */"]
+assert format_block(lineI) == lineO
+
+long = "long " * 20
+lineI = [" /** ", ' * @ref a "' + long + '" d', " */"]
+lineO = [" /**", ' * @ref a "' + long + '"', " * d", " */"]
+assert format_block(lineI) == lineO
+
+lineI = [" /** ", " * @ref a. c", ' * @ref a "b c". c2', " */"]
+lineO = [" /**", " * @ref a.", " * c", ' * @ref a "b c".', " * c2", " */"]
+assert format_block(lineI) == lineO
# do not break @page:
-longtext = "bla bla"*20
-lineI = [" /**",
- " * @page " + longtext,
- " * hello",
- " */"]
-assert(format_block(lineI)==lineI)
+longtext = "bla bla" * 20
+lineI = [" /**", " * @page " + longtext, " * hello", " */"]
+assert format_block(lineI) == lineI
# do not break $very_long_formula_without_spacing$:
-longtext = "blabla"*20
-lineI = [" /**",
- " * a $" + longtext + "$",
- " */"]
-lineO = [" /**",
- " * a",
- " * $" + longtext + "$",
- " */"]
-assert(format_block(lineI)==lineI)
+longtext = "blabla" * 20
+lineI = [" /**", " * a $" + longtext + "$", " */"]
+lineO = [" /**", " * a", " * $" + longtext + "$", " */"]
+assert format_block(lineI) == lineI
# nested lists
-lineI = [" /**",
- " * Hello:",
- " * - A",
- " * - B",
- " * - C",
- " * - D",
- " * - E",
- " * - very indented",
- " */"]
+lineI = [
+ " /**",
+ " * Hello:",
+ " * - A",
+ " * - B",
+ " * - C",
+ " * - D",
+ " * - E",
+ " * - very indented",
+ " */",
+]
lineO = lineI
-assert(format_block(lineI)==lineO)
+assert format_block(lineI) == lineO
# @f{}
-lineI = [" /**",
- " * Hello:",
- " * @f{aligned*}{",
- " * A\\\\",
- " * B",
- " * @f}",
- " * bla",
- " */"]
+lineI = [
+ " /**",
+ " * Hello:",
+ " * @f{aligned*}{",
+ " * A\\\\",
+ " * B",
+ " * @f}",
+ " * bla",
+ " */",
+]
lineO = lineI
-assert(format_block(lineI)==lineO)
-
-# @until
-lineI = [" /**",
- " * Hello:",
- " * @include a",
- " * bla",
- " * @dontinclude a",
- " * bla",
- " * @line a",
- " * bla",
- " * @skip a",
- " * bla",
- " * @until a",
- " * bla",
- " */"]
+assert format_block(lineI) == lineO
+
+# @until
+lineI = [
+ " /**",
+ " * Hello:",
+ " * @include a",
+ " * bla",
+ " * @dontinclude a",
+ " * bla",
+ " * @line a",
+ " * bla",
+ " * @skip a",
+ " * bla",
+ " * @until a",
+ " * bla",
+ " */",
+]
lineO = lineI
-assert(format_block(lineI)==lineO)
+assert format_block(lineI) == lineO
# lists
-lineI = [" /**",
- " * Hello:",
- " * - a",
- " * - b",
- " * the end.",
- " */"]
+lineI = [" /**", " * Hello:", " * - a", " * - b", " * the end.", " */"]
lineO = lineI
-assert(format_block(lineI)==lineO)
+assert format_block(lineI) == lineO
# numbered lists
-lineI = [" /**",
- " * Hello:",
- " * 1. a",
- " * 2. b",
- " * the end.",
- " */"]
+lineI = [" /**", " * Hello:", " * 1. a", " * 2. b", " * the end.", " */"]
lineO = lineI
-assert(format_block(lineI)==lineO)
+assert format_block(lineI) == lineO
# do not break @name:
-longtext = "bla bla"*20
-lineI = [" /**",
- " * @name " + longtext,
- " * hello",
- " */"]
-assert(format_block(lineI)==lineI)
-
-
-#print (lineI)
-#print (format_block(lineI))
+longtext = "bla bla" * 20
+lineI = [" /**", " * @name " + longtext, " * hello", " */"]
+assert format_block(lineI) == lineI
+# print (lineI)
+# print (format_block(lineI))
# now open the file and do the work
-args=sys.argv
+args = sys.argv
args.pop(0)
-if len(args)!=1:
+if len(args) != 1:
print("Usage: wrapcomments.py infile >outfile")
exit(0)
lineidx = 0
for line in lines:
lineidx += 1
- line = line.replace("\n","")
+ line = line.replace("\n", "")
if not inblock and "/**" in line:
inblock = True
cur = []
else:
out.append(line)
if inblock and "*/" in line:
- out.extend(format_block(cur, args[0]+":%d"%lineidx))
+ out.extend(format_block(cur, args[0] + ":%d" % lineidx))
cur = []
inblock = False
-assert(cur==[])
+assert cur == []
for line in out:
- print (line)
+ print(line)
from sympy.physics.vector import ReferenceFrame, gradient, divergence
from sympy.vector import CoordSysCartesian
-R = ReferenceFrame('R')
+R = ReferenceFrame("R")
x = R[0]
y = R[1]
-a=-0.5
-b=1.5
-visc=1e-1
-lambda_=(1/(2*visc)-sqrt(1/(4*visc**2)+4*pi**2))
+a = -0.5
+b = 1.5
+visc = 1e-1
+lambda_ = 1 / (2 * visc) - sqrt(1 / (4 * visc ** 2) + 4 * pi ** 2)
print(" visc=%f" % visc)
-u=[0,0]
-u[0]=1-exp(lambda_*x)*cos(2*pi*y)
-u[1]=lambda_/(2*pi)*exp(lambda_*x)*sin(2*pi*y)
-p=(exp(3*lambda_)-exp(-lambda_))/(8*lambda_)-exp(2*lambda_*x)/2
-p=p - integrate(p, (x,a,b))
+u = [0, 0]
+u[0] = 1 - exp(lambda_ * x) * cos(2 * pi * y)
+u[1] = lambda_ / (2 * pi) * exp(lambda_ * x) * sin(2 * pi * y)
+p = (exp(3 * lambda_) - exp(-lambda_)) / (8 * lambda_) - exp(2 * lambda_ * x) / 2
+p = p - integrate(p, (x, a, b))
grad_p = gradient(p, R).to_matrix(R)
-f0 = -divergence(visc*gradient(u[0], R), R) + grad_p[0]
-f1 = -divergence(visc*gradient(u[1], R), R) + grad_p[1]
-f2 = divergence(u[0]*R.x + u[1]*R.y, R)
+f0 = -divergence(visc * gradient(u[0], R), R) + grad_p[0]
+f1 = -divergence(visc * gradient(u[1], R), R) + grad_p[1]
+f2 = divergence(u[0] * R.x + u[1] * R.y, R)
print("\n * RHS:")
-print(ccode(f0, assign_to = "values[0]"))
-print(ccode(f1, assign_to = "values[1]"))
-print(ccode(f2, assign_to = "values[2]"))
+print(ccode(f0, assign_to="values[0]"))
+print(ccode(f1, assign_to="values[1]"))
+print(ccode(f2, assign_to="values[2]"))
print("\n * ExactSolution:")
-print(ccode(u[0], assign_to = "values[0]"))
-print(ccode(u[1], assign_to = "values[1]"))
-print(ccode(p, assign_to = "values[2]"))
+print(ccode(u[0], assign_to="values[0]"))
+print(ccode(u[1], assign_to="values[1]"))
+print(ccode(p, assign_to="values[2]"))
print("")
-print("pressure mean:", N(integrate(p,(x,a,b))))
+print("pressure mean:", N(integrate(p, (x, a, b))))