def geometry_3d():
    """Prepares 3D geometry. Returns facet function with 1, 2 on parts of
    the boundary."""
    mesh = Mesh('lego_beam.xml')
    gdim = mesh.geometry().dim()
    x0 = mesh.coordinates()[:, 0].min()
    x1 = mesh.coordinates()[:, 0].max()
    boundary_parts = FacetFunction('size_t', mesh)
    left = AutoSubDomain(lambda x: near(x[0], x0))
    right = AutoSubDomain(lambda x: near(x[0], x1))
    left.mark(boundary_parts, 1)
    right.mark(boundary_parts, 2)
    boundary_parts._mesh = mesh  # Workaround issue #467
    return boundary_parts
Beispiel #2
0
    def __init__(self, args, tc, metadata):
        self.has_analytic_solution = False
        self.problem_code = 'FACB'
        super(Problem, self).__init__(args, tc, metadata)

        self.name = 'test on real mesh'
        self.status_functional_str = 'not selected'

        # input parameters
        self.factor = args.factor
        self.scale_factor.append(self.factor)

        self.nu = 0.001 * args.nufactor  # kinematic viscosity

        # Import gmsh mesh
        self.compatible_meshes = ['bench3D_1', 'bench3D_2', 'bench3D_3']
        if args.mesh not in self.compatible_meshes:
            exit('Bad mesh, should be some from %s' % str(self.compatible_meshes))

        self.mesh = Mesh("meshes/" + args.mesh + ".xml")
        self.cell_function = MeshFunction("size_t", self.mesh, "meshes/" + args.mesh + "_physical_region.xml")
        self.facet_function = MeshFunction("size_t", self.mesh, "meshes/" + args.mesh + "_facet_region.xml")
        self.dsIn = Measure("ds", subdomain_id=2, subdomain_data=self.facet_function)
        self.dsOut = Measure("ds", subdomain_id=3, subdomain_data=self.facet_function)
        self.dsWall = Measure("ds", subdomain_id=1, subdomain_data=self.facet_function)
        self.dsCyl = Measure("ds", subdomain_id=5, subdomain_data=self.facet_function)
        self.normal = FacetNormal(self.mesh)
        print("Mesh name: ", args.mesh, "    ", self.mesh)
        print("Mesh norm max: ", self.mesh.hmax())
        print("Mesh norm min: ", self.mesh.hmin())

        self.actual_time = None
        self.v_in = None
def get_dolfin_mesh_from_hdf5(mesh_filename):

    # convert mesh
    dolfin_filename = convert_hdf5_to_dolfin_mesh(mesh_filename)

    # load dolfin mesh
    return Mesh(dolfin_filename)
Beispiel #4
0
  def __init__(self, problem, verbosity=0):
    """

    :param ProblemData problem:
    :param int verbosity:
    :return:
    """
    self.parameters = parameters["discretization"]

    self.verb = verbosity
    self.vis_folder = os.path.join(problem.out_folder, "MESH")
    self.core = problem.core
    self.G = problem.G

    if self.verb > 1: print pid+"Loading mesh"
        
    t_load = Timer("DD: Data loading")

    if not problem.mesh_module:
      if self.verb > 1: print pid + "  mesh data"
      self.mesh = Mesh(problem.mesh_files.mesh)

      if self.verb > 1: print pid + "  physical data"
      self.cell_regions_fun = MeshFunction("size_t", self.mesh, problem.mesh_files.physical_regions)

      if self.verb > 1: print pid + "  boundary data"
      self.boundaries = MeshFunction("size_t", self.mesh, problem.mesh_files.facet_regions)
    else:
      self.mesh = problem.mesh_module.mesh
      self.cell_regions_fun = problem.mesh_module.regions

      try:
        self.boundaries = problem.mesh_module.boundaries
      except AttributeError:
        self.boundaries = None

    assert self.mesh
    assert self.boundaries is None or self.boundaries.array().size > 0

    if self.verb > 2:
      print pid+"  mesh info: " + str(self.mesh)

    if self.verb > 1: print0("Defining function spaces" )

    self.t_spaces = Timer("DD: Function spaces construction")

    # Spaces that must be specified by the respective subclasses
    self.V = None     # solution space
    self.Vphi1 = None # 1-g scalar flux space
    
    # XS / TH space
    self.V0 = FunctionSpace(self.mesh, "DG", 0)
    self.ndof0 = self.V0.dim()

    dofmap = self.V0.dofmap()
    self.local_ndof0 = dofmap.local_dimension("owned")

    self.cell_regions = self.cell_regions_fun.array()
    assert self.cell_regions.size == self.local_ndof0
    def __init__(self, args, tc, metadata):
        self.has_analytic_solution = False
        self.problem_code = 'FACB'
        super(Problem, self).__init__(args, tc, metadata)

        self.name = 'test on real mesh'
        self.status_functional_str = 'not selected'

        # input parameters
        self.factor = args.factor
        self.scale_factor.append(self.factor)

        self.nu = 0.001 * args.nufactor  # kinematic viscosity

        # Import gmsh mesh
        self.compatible_meshes = ['bench3D_1', 'bench3D_2', 'bench3D_3']
        if args.mesh not in self.compatible_meshes:
            exit('Bad mesh, should be some from %s' %
                 str(self.compatible_meshes))

        self.mesh = Mesh("meshes/" + args.mesh + ".xml")
        self.cell_function = MeshFunction(
            "size_t", self.mesh,
            "meshes/" + args.mesh + "_physical_region.xml")
        self.facet_function = MeshFunction(
            "size_t", self.mesh, "meshes/" + args.mesh + "_facet_region.xml")
        self.dsIn = Measure("ds",
                            subdomain_id=2,
                            subdomain_data=self.facet_function)
        self.dsOut = Measure("ds",
                             subdomain_id=3,
                             subdomain_data=self.facet_function)
        self.dsWall = Measure("ds",
                              subdomain_id=1,
                              subdomain_data=self.facet_function)
        self.dsCyl = Measure("ds",
                             subdomain_id=5,
                             subdomain_data=self.facet_function)
        self.normal = FacetNormal(self.mesh)
        print("Mesh name: ", args.mesh, "    ", self.mesh)
        print("Mesh norm max: ", self.mesh.hmax())
        print("Mesh norm min: ", self.mesh.hmin())

        self.actual_time = None
        self.v_in = None
Beispiel #6
0
 def loadMesh(mesh):
     """
     :param mesh: name of mesh file (without extension)
     :return: tuple mesh, facet function read from .hdf5 file
     """
     f = HDF5File(mpi_comm_world(), 'meshes/'+mesh+'.hdf5', 'r')
     mesh = Mesh()
     f.read(mesh, 'mesh', False)
     facet_function = MeshFunction("size_t", mesh)
     f.read(facet_function, 'facet_function')
     return mesh, facet_function
Beispiel #7
0
    def testMarkSquare(self):

        geo = Geometry(

            # Points used for face elements
            (Point(0.0, 0.0), Point(1.0, 0.0), Point(1.0, 1.0), Point(
                0.0, 1.0)),

            # Face elements
            ((0, 1), (1, 2), (2, 3), (3, 0)))

        mesh = Mesh("triangle.7.nml.gz")

        faceSubdomains = markBoundariesOfMesh(mesh, geo)

        self.assertTrue(isinstance(faceSubdomains, MeshFunction),
                        "faceSubdomains is not a MeshFunction")
Beispiel #8
0
from dolfin.cpp.io import interactive
from dolfin.cpp.la import has_krylov_solver_preconditioner
from dolfin.cpp.mesh import Mesh

parameters["std_out_all_processes"] = False


def get_project_path():
    (project_path,
     src_folder) = os.path.split(os.path.abspath(os.path.dirname(__file__)))
    #(project_path, src_folder) = os.path.split(os.path.abspath(src_path))
    return project_path


# Load mesh from file
mesh = Mesh(get_project_path() + '/data/lshape.xml')

# Define function spaces (P2-P1)
V = VectorFunctionSpace(mesh, "CG", 2)
Q = FunctionSpace(mesh, "CG", 1)

# Define trial and test functions
u = TrialFunction(V)
p = TrialFunction(Q)
v = TestFunction(V)
q = TestFunction(Q)

# Set parameter values
dt = 0.01
T = 3
nu = 0.01
Beispiel #9
0
class Problem(gp.GeneralProblem):
    def __init__(self, args, tc, metadata):
        self.has_analytic_solution = False
        self.problem_code = 'FACB'
        super(Problem, self).__init__(args, tc, metadata)

        self.name = 'test on real mesh'
        self.status_functional_str = 'not selected'

        # input parameters
        self.factor = args.factor
        self.scale_factor.append(self.factor)

        self.nu = 0.001 * args.nufactor  # kinematic viscosity

        # Import gmsh mesh
        self.compatible_meshes = ['bench3D_1', 'bench3D_2', 'bench3D_3']
        if args.mesh not in self.compatible_meshes:
            exit('Bad mesh, should be some from %s' % str(self.compatible_meshes))

        self.mesh = Mesh("meshes/" + args.mesh + ".xml")
        self.cell_function = MeshFunction("size_t", self.mesh, "meshes/" + args.mesh + "_physical_region.xml")
        self.facet_function = MeshFunction("size_t", self.mesh, "meshes/" + args.mesh + "_facet_region.xml")
        self.dsIn = Measure("ds", subdomain_id=2, subdomain_data=self.facet_function)
        self.dsOut = Measure("ds", subdomain_id=3, subdomain_data=self.facet_function)
        self.dsWall = Measure("ds", subdomain_id=1, subdomain_data=self.facet_function)
        self.dsCyl = Measure("ds", subdomain_id=5, subdomain_data=self.facet_function)
        self.normal = FacetNormal(self.mesh)
        print("Mesh name: ", args.mesh, "    ", self.mesh)
        print("Mesh norm max: ", self.mesh.hmax())
        print("Mesh norm min: ", self.mesh.hmin())

        self.actual_time = None
        self.v_in = None

    def __str__(self):
        return 'flow around cylinder 3D benchmark'

    @staticmethod
    def setup_parser_options(parser):
        super(Problem, Problem).setup_parser_options(parser)
        parser.add_argument('-F', '--factor', help='Velocity scale factor', type=float, default=1.0)
        parser.add_argument('--nufactor', help='kinematic viscosity factor', type=float, default=1.0)

    def initialize(self, V, Q, PS, D):
        super(Problem, self).initialize(V, Q, PS, D)

        print("Velocity scale factor = %4.2f" % self.factor)

        self.v_in = Problem.InputVelocityProfile(self.factor)
        # plot(interpolate(self.v_in, self.vSpace), interactive=True)
        # scalarSpace = FunctionSpace(self.mesh, "Lagrange", 2)
        # area = assemble(interpolate(Expression("1.0"), scalarSpace) * self.dsIn)
        # expr = Expression("factor*0.45*(x[1]*(0.41-x[1]) * x[2]*(0.41-x[2]))/(0.205*0.205*0.205*0.205)",
        #                   factor=self.factor)
        # average = assemble((1.0/area) * interpolate(expr, scalarSpace) * self.dsIn)
        # print('Average velocity:', average)
        # re = average * 0.1 / self.nu  # average_velocity*cylinger_diameter/kinematic_viscosity
        re = 20.0 * self.factor / self.args.nufactor  # average_velocity*cylinger_diameter/kinematic_viscosity
        print('Reynolds number:', re)

        one = (interpolate(Expression('1.0'), Q))
        self.mesh_volume = assemble(one*dx)
        self.outflow_area = assemble(one*self.dsOut)
        print('Outflow area:', self.outflow_area)

    # parabolic profile on square normed so centerline velocity = 1m/s * factor
    class InputVelocityProfile(Expression):
        def __init__(self, factor):
            # super(Expression, self).__init__()
            super(Problem.InputVelocityProfile, self).__init__()
            self.factor = factor
            # self.t = 0.0

        def eval(self, value, x):
            value[0] = self.factor*0.45*(x[1]*(0.41-x[1]) * x[2]*(0.41-x[2]))/(0.205*0.205*0.205*0.205)
            value[1] = 0.0
            value[2] = 0.0

        def value_shape(self):
            return (3,)

    def get_boundary_conditions(self, use_pressure_BC, v_space, p_space):
        # boundary parts: 1 walls, 2, 4 inflow, 3, 5 outflow
        # Boundary conditions
        bc_wall = DirichletBC(v_space, (0.0, 0.0, 0.0), self.facet_function, 1)
        bc_cyl = DirichletBC(v_space, (0.0, 0.0, 0.0), self.facet_function, 5)
        inflow = DirichletBC(v_space, self.v_in, self.facet_function, 2)
        bcu = [inflow, bc_cyl, bc_wall]
        bcp = []
        if use_pressure_BC:
            outflow = DirichletBC(p_space, 0.0, self.facet_function, 3)
            bcp = [outflow]
        return bcu, bcp

    def get_initial_conditions(self, function_list):
        out = []
        for d in function_list:
            if d['type'] == 'v':
                f = Function(self.vSpace)
            if d['type'] == 'p':
                f = Function(self.pSpace)
            out.append(f)
        return out

    def update_time(self, actual_time, step_number):
        super(Problem, self).update_time(actual_time, step_number)
        if self.actual_time > 0.5 and int(round(self.actual_time * 1000)) % 1000 == 0:
            self.isWholeSecond = True
            seconds = int(round(self.actual_time))
            self.second_list.append(seconds)
            self.N1 = seconds*self.stepsInCycle
            self.N0 = (seconds-1)*self.stepsInCycle
        else:
            self.isWholeSecond = False

        # Update boundary condition
        # self.tc.start('updateBC')
        # self.v_in.t = actual_time
        # self.tc.end('updateBC')

    def save_pressure(self, is_tent, pressure):
        super(Problem, self).save_pressure(is_tent, pressure)
    def construct_mesh(self, nx0, nx1, nx2, res, project_path):
        """
        :param nx0, nx1, nx2: mesh-sizes wrt to X, Y, Z directions
        :param res: mesh resolution if defined with mesh_generator function
        :param project_path: path of the project to load the mesh
        :return: mesh:discretization of the domain
        """
        if self.domain == "unit-domain":
            if self.dim == 1:
                # Create mesh on the unit interval
                mesh = UnitIntervalMesh(nx0)
            elif self.dim == 2:
                # Create mesh on the unit square
                mesh = UnitSquareMesh(nx0, nx1)
            elif self.dim == 3:
                # Create mesh on the unit cube
                mesh = UnitCubeMesh(nx0, nx1, nx2)

        elif self.domain == "l-shape-domain":

            if self.dim == 2:

                #data_path = '/data/%dd/test-%d/' % (self.dim, test_num)
                # file_name = 'l-shape-3d-mmg3d.xml'
                # file_name = 'l-shape-diam-2sqrt2-33-vertices.xml'
                #file_name = 'l-shape-3.xml'
                # file_name = 'l-shape-15-verts.xml'
                # file_name = 'l-shape-adapt.xml'

                # file_name = 'l-shape-3d-twice-refined.xml'
                # file_name = 'l-shape-3d-once-refined.xml'
                # plot(mesh, interactive=True)

                # Load mesh from the xml-file
                #mesh = Mesh(project_path + data_path + file_name)
                #plot(mesh)

                #                '''
                #res = 4
                big_square = Rectangle(Point(-1.0, -1.0), Point(1.0, 1.0))
                small_square = Rectangle(Point(0.0, -1.0), Point(1.0, 0.0))
                mesh = generate_mesh(big_square - small_square, res)
                #plot(mesh)

#               '''

            elif dim == 3:
                mesh = generate_mesh(
                    Box(Point(0, 0, 0), Point(1, 1, 1)) +
                    Box(Point(0, 0, 0), Point(-1, 1, 1)) +
                    Box(Point(0, 0, 0), Point(-1, -1, 1)), res)

        elif self.domain == "pi-shape-domain":
            data_path = '/data/%dd/test-%d/' % (self.dim, test_num)
            file_name = 'pi-shape-2.xml'

            # Load mesh from the xml-file
            mesh = Mesh(project_path + data_path + file_name)
            plot(mesh, interactive=True)

        elif self.domain == "circle-domain":

            mesh = generate_mesh(Circle(dolfin.Point(0, 0), 1), res)

        print "num", mesh.num_cells()
        return mesh
    },
    {
        'number': 5,
        'normal': [-0.8325, 0.545089, -0.0991071],
        'center': [40.4424, 13.6561, 5.91043]
    },
    {
        'number': 6,
        'normal': [-0.924775, -0.0804152, -0.37192],
        'center': [40.0173, 25.4672, 6.58901]
    },
]
number_list = [2, 3, 4, 5,
               6]  # numbers of inflows, outflows, '1' is reserved for walls
# END OF INPUT ==============================
mesh = Mesh("meshes/" + meshName + ".xml")
tdim = mesh.topology().dim()
mesh.init(tdim - 1, tdim)  # needed for facet.exterior()
normal = FacetNormal(mesh)
print("Mesh name: ", meshName, "    ", mesh)
print("Mesh norm max: ", mesh.hmax())
print("Mesh norm min: ", mesh.hmin())
edge_min = 1000
edge_max = 0
for e in edges(mesh):
    l = e.length()
    if l > edge_max:
        edge_max = l
    if l < edge_min:
        edge_min = l
print('edge length max/min:', edge_max, edge_min)
Beispiel #12
0
    def construct_mesh(self, nx0, nx1, nx2, res, project_path):
        """
        :param nx0, nx1, nx2: mesh-sizes wrt to X, Y, Z directions
        :param res: mesh resolution if defined with mesh_generator function
        :param project_path: path of the project to load the mesh
        :return: mesh:discretization of the domain
        """
        # --------------------------------------------------------------------------------------------------------------#
        if self.domain == "unit-domain":

            if self.dim == 1:
                # Create mesh on the unit interval
                mesh = UnitIntervalMesh(nx0)

            elif self.dim == 2:
                # Create mesh on the unit square
                mesh = UnitSquareMesh(nx0, nx1)

            elif self.dim == 3:
                # Create mesh on the unit cube
                mesh = UnitCubeMesh(nx0, nx1, nx2)
        # --------------------------------------------------------------------------------------------------------------#
        elif self.domain == "circle-domain":
            # Define the 'resolution' of the mesh
            res = 4

            # Define the radius of the circle
            rad = 2.0

            # Create the circle geometry
            circle = Circle(Point(0.0, 0.0), rad)

            # Generate the mesh based on the geometry and the resolution of the mesh
            mesh = generate_mesh(circle, res)
        # --------------------------------------------------------------------------------------------------------------#
        elif self.domain == "l-shape-domain":
            # Define the data path depending on the problem parameters
            file_path = '/data/%dd/test-%d/' % (self.dim, test_num)

            # 2d l-shaped domain mesh
            file_name = 'l-shape-diam-2sqrt2-33-vertices.xml'

            # 3d l-shaped domain mesh
            # file_name = 'l-shape-3d-twice-refined.xml'
            # file_name = 'l-shape-3d-once-refined.xml'
            # file_name = 'l-shape-3d-three-refined.xml'

            # Load mesh from the xml-file
            mesh = Mesh(project_path + file_path + file_name)
        # --------------------------------------------------------------------------------------------------------------#
        elif self.domain == "ring-domain":

            # Define the 'resolution' of the mesh
            res = 4

            # Define the radius of the circle
            big_rad = 1.0
            small_rad = 0.5

            # Create the circle geometry
            big_circle = Circle(Point(0.0, 0.0), big_rad)
            small_circle = Circle(Point(0.0, 0.0), small_rad)

            # Generate the mesh based on the geometry and the resolution of the mesh
            mesh = generate_mesh(big_circle - small_circle, res)

        return mesh
class Problem(gp.GeneralProblem):
    def __init__(self, args, tc, metadata):
        self.has_analytic_solution = False
        self.problem_code = 'FACB'
        super(Problem, self).__init__(args, tc, metadata)

        self.name = 'test on real mesh'
        self.status_functional_str = 'not selected'

        # input parameters
        self.factor = args.factor
        self.scale_factor.append(self.factor)

        self.nu = 0.001 * args.nufactor  # kinematic viscosity

        # Import gmsh mesh
        self.compatible_meshes = ['bench3D_1', 'bench3D_2', 'bench3D_3']
        if args.mesh not in self.compatible_meshes:
            exit('Bad mesh, should be some from %s' %
                 str(self.compatible_meshes))

        self.mesh = Mesh("meshes/" + args.mesh + ".xml")
        self.cell_function = MeshFunction(
            "size_t", self.mesh,
            "meshes/" + args.mesh + "_physical_region.xml")
        self.facet_function = MeshFunction(
            "size_t", self.mesh, "meshes/" + args.mesh + "_facet_region.xml")
        self.dsIn = Measure("ds",
                            subdomain_id=2,
                            subdomain_data=self.facet_function)
        self.dsOut = Measure("ds",
                             subdomain_id=3,
                             subdomain_data=self.facet_function)
        self.dsWall = Measure("ds",
                              subdomain_id=1,
                              subdomain_data=self.facet_function)
        self.dsCyl = Measure("ds",
                             subdomain_id=5,
                             subdomain_data=self.facet_function)
        self.normal = FacetNormal(self.mesh)
        print("Mesh name: ", args.mesh, "    ", self.mesh)
        print("Mesh norm max: ", self.mesh.hmax())
        print("Mesh norm min: ", self.mesh.hmin())

        self.actual_time = None
        self.v_in = None

    def __str__(self):
        return 'flow around cylinder 3D benchmark'

    @staticmethod
    def setup_parser_options(parser):
        super(Problem, Problem).setup_parser_options(parser)
        parser.add_argument('-F',
                            '--factor',
                            help='Velocity scale factor',
                            type=float,
                            default=1.0)
        parser.add_argument('--nufactor',
                            help='kinematic viscosity factor',
                            type=float,
                            default=1.0)

    def initialize(self, V, Q, PS, D):
        super(Problem, self).initialize(V, Q, PS, D)

        print("Velocity scale factor = %4.2f" % self.factor)

        self.v_in = Problem.InputVelocityProfile(self.factor)
        # plot(interpolate(self.v_in, self.vSpace), interactive=True)
        # scalarSpace = FunctionSpace(self.mesh, "Lagrange", 2)
        # area = assemble(interpolate(Expression("1.0"), scalarSpace) * self.dsIn)
        # expr = Expression("factor*0.45*(x[1]*(0.41-x[1]) * x[2]*(0.41-x[2]))/(0.205*0.205*0.205*0.205)",
        #                   factor=self.factor)
        # average = assemble((1.0/area) * interpolate(expr, scalarSpace) * self.dsIn)
        # print('Average velocity:', average)
        # re = average * 0.1 / self.nu  # average_velocity*cylinger_diameter/kinematic_viscosity
        re = 20.0 * self.factor / self.args.nufactor  # average_velocity*cylinger_diameter/kinematic_viscosity
        print('Reynolds number:', re)

        one = (interpolate(Expression('1.0'), Q))
        self.mesh_volume = assemble(one * dx)
        self.outflow_area = assemble(one * self.dsOut)
        print('Outflow area:', self.outflow_area)

    # parabolic profile on square normed so centerline velocity = 1m/s * factor
    class InputVelocityProfile(Expression):
        def __init__(self, factor):
            # super(Expression, self).__init__()
            super(Problem.InputVelocityProfile, self).__init__()
            self.factor = factor
            # self.t = 0.0

        def eval(self, value, x):
            value[0] = self.factor * 0.45 * (x[1] * (0.41 - x[1]) * x[2] *
                                             (0.41 - x[2])) / (0.205 * 0.205 *
                                                               0.205 * 0.205)
            value[1] = 0.0
            value[2] = 0.0

        def value_shape(self):
            return (3, )

    def get_boundary_conditions(self, use_pressure_BC, v_space, p_space):
        # boundary parts: 1 walls, 2, 4 inflow, 3, 5 outflow
        # Boundary conditions
        bc_wall = DirichletBC(v_space, (0.0, 0.0, 0.0), self.facet_function, 1)
        bc_cyl = DirichletBC(v_space, (0.0, 0.0, 0.0), self.facet_function, 5)
        inflow = DirichletBC(v_space, self.v_in, self.facet_function, 2)
        bcu = [inflow, bc_cyl, bc_wall]
        bcp = []
        if use_pressure_BC:
            outflow = DirichletBC(p_space, 0.0, self.facet_function, 3)
            bcp = [outflow]
        return bcu, bcp

    def get_initial_conditions(self, function_list):
        out = []
        for d in function_list:
            if d['type'] == 'v':
                f = Function(self.vSpace)
            if d['type'] == 'p':
                f = Function(self.pSpace)
            out.append(f)
        return out

    def update_time(self, actual_time, step_number):
        super(Problem, self).update_time(actual_time, step_number)
        if self.actual_time > 0.5 and int(round(
                self.actual_time * 1000)) % 1000 == 0:
            self.isWholeSecond = True
            seconds = int(round(self.actual_time))
            self.second_list.append(seconds)
            self.N1 = seconds * self.stepsInCycle
            self.N0 = (seconds - 1) * self.stepsInCycle
        else:
            self.isWholeSecond = False

        # Update boundary condition
        # self.tc.start('updateBC')
        # self.v_in.t = actual_time
        # self.tc.end('updateBC')

    def save_pressure(self, is_tent, pressure):
        super(Problem, self).save_pressure(is_tent, pressure)
# planes can intersect rest of the geometry, as is improbable that any exterior facet will have all vertices in given planes
# otherwise it would be necessary to check distance from centerpoint

inflows = [
    {'number': 2, 'normal': [0.0, 1.0, 0.0], 'center': [1.59128, -13.6391, 7.24912], 'radius': 1.01077,
     'reference_radius': 1.01077},
    {'number': 4, 'normal': [0.1, -1.0, -0.37], 'center': [-4.02584, 7.70146, 8.77694], 'radius': 0.553786,
     'reference_radius': 0.553786},
]
outflows = [
    {'number': 3, 'normal': [-0.838444, 0.0, 0.544988], 'center': [11.3086, -0.985461, -5.64479]},
    {'number': 5, 'normal': [-1.0, 0.0, 0.0], 'center': [20.6585, -1.38651, -1.24815]},
]
number_list = [2, 3, 4, 5]  # numbers of inflows, outflows, '1' is reserved for walls
# END OF INPUT ==============================
mesh = Mesh("meshes/" + meshName + ".xml")
tdim = mesh.topology().dim()
mesh.init(tdim-1, tdim)  # needed for facet.exterior()
normal = FacetNormal(mesh)
print("Mesh name: ", meshName, "    ", mesh)
print("Mesh norm max: ", mesh.hmax())
print("Mesh norm min: ", mesh.hmin())
edge_min = 1000
edge_max = 0
for e in edges(mesh):
    l = e.length()
    if l > edge_max:
        edge_max = l
    if l < edge_min:
        edge_min = l
print('edge length max/min:', edge_max, edge_min)
elif alpha == 29 * DOLFIN_PI / 30:

    file_names = ['alpha-29pi30-h-1.xml']
    # Define the file path
    file_path = '/data/29-pi-30/'

# Maximal N in the power series or in the fourier series
N_power = numpy.array([6, 7])

for file_name in file_names: # if the there are list of xml-file we run through the loop

    # Load mesh from the xml-file
    project_path = postprocess.get_project_path()
    mesh = Mesh(project_path +
                file_path +
                file_name)
    print "mesh: %s, h_max = %f" % (file_name, mesh.hmax())


    class ZeroBoundary(SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary and x[1] <= DOLFIN_EPS

    # Mark boundaries
    zero_boundary = ZeroBoundary()
    boundaries = FacetFunction("uint", mesh)
    boundaries.set_all(0)
    zero_boundary.mark(boundaries, 1)

    # Redefine boundary measure
from demos.params.galerkin import finiteElement
# Load Newmark parameters
import demos.params.newmark as newmark
# Time interval
from demos.params.timeInterval import timeInterval

###
### Configuration
###

### Load elasticity module
import demos.data.elasticity as elasticity

# Load mesh
if isfile(meshPath):
    mesh = Mesh(meshPath)
else:
    print("Mesh bndFile does not exist!")
    exit(1)
#plot(mesh, interactive=True)

###
### Mesh
###

# Here we consider 0 as a internal face
bndSubdomains = markBoundariesOfMesh(mesh, geo, outputPvd="localBoundary.pvd")
globalBndSubdomains = MeshFunction("size_t", mesh, geo._nDim - 1)

# If there exist marked boundary
if 'boundaries' in dir(physics):
Beispiel #17
0
class Discretization(object):
  def __init__(self, problem, verbosity=0):
    """

    :param ProblemData problem:
    :param int verbosity:
    :return:
    """
    self.parameters = parameters["discretization"]

    self.verb = verbosity
    self.vis_folder = os.path.join(problem.out_folder, "MESH")
    self.core = problem.core
    self.G = problem.G

    if self.verb > 1: print pid+"Loading mesh"
        
    t_load = Timer("DD: Data loading")

    if not problem.mesh_module:
      if self.verb > 1: print pid + "  mesh data"
      self.mesh = Mesh(problem.mesh_files.mesh)

      if self.verb > 1: print pid + "  physical data"
      self.cell_regions_fun = MeshFunction("size_t", self.mesh, problem.mesh_files.physical_regions)

      if self.verb > 1: print pid + "  boundary data"
      self.boundaries = MeshFunction("size_t", self.mesh, problem.mesh_files.facet_regions)
    else:
      self.mesh = problem.mesh_module.mesh
      self.cell_regions_fun = problem.mesh_module.regions

      try:
        self.boundaries = problem.mesh_module.boundaries
      except AttributeError:
        self.boundaries = None

    assert self.mesh
    assert self.boundaries is None or self.boundaries.array().size > 0

    if self.verb > 2:
      print pid+"  mesh info: " + str(self.mesh)

    if self.verb > 1: print0("Defining function spaces" )

    self.t_spaces = Timer("DD: Function spaces construction")

    # Spaces that must be specified by the respective subclasses
    self.V = None     # solution space
    self.Vphi1 = None # 1-g scalar flux space
    
    # XS / TH space
    self.V0 = FunctionSpace(self.mesh, "DG", 0)
    self.ndof0 = self.V0.dim()

    dofmap = self.V0.dofmap()
    self.local_ndof0 = dofmap.local_dimension("owned")

    self.cell_regions = self.cell_regions_fun.array()
    assert self.cell_regions.size == self.local_ndof0

  def __create_cell_dof_mapping(self, dofmap):
    """
    Generate cell -> dof mapping for all cells of current partition.
    Note: in DG(0) space, there is one dof per element and no ghost cells.

    :param GenericDofMap dofmap: DG(0) dofmap
    """

    if self.verb > 2: print0("Constructing cell -> dof mapping")
    timer = Timer("DD: Cell->dof construction")

    code = \
    '''
      #include <dolfin/mesh/Cell.h>

      namespace dolfin
      {
        void fill_in(Array<int>& local_cell_dof_map, const Mesh& mesh, const GenericDofMap& dofmap)
        {
          std::size_t local_dof_range_start = dofmap.ownership_range().first;
          int* cell_dof_data = local_cell_dof_map.data();

          for (CellIterator c(mesh); !c.end(); ++c)
            *cell_dof_data++ = dofmap.cell_dofs(c->index())[0] - local_dof_range_start;
        }
      }
    '''

    cell_mapping_module = compile_extension_module(code)
    cell_dof_array = IntArray(self.local_ndof0)
    cell_mapping_module.fill_in(cell_dof_array, self.mesh, dofmap)
    self._local_cell_dof_map = cell_dof_array.array()

    timer.stop()

  def __create_cell_layers_mapping(self):
    """
    Generate a cell -> axial layer mapping for all cells of current partition. Note that keys are ordered by the
    associated DG(0) dof, not by the cell index in the mesh.
    """

    if self.verb > 2: print0("Constructing cell -> layer mapping")
    timer = Timer("DD: Cell->layer construction")

    code = \
    '''
      #include <dolfin/mesh/Cell.h>

      namespace dolfin
      {
        void fill_in(Array<int>& local_cell_layers,
                     const Mesh& mesh, const Array<int>& cell_dofs, const Array<double>& layer_boundaries)
        {
          std::size_t num_layers = layer_boundaries.size() - 1;
          unsigned int layer;

          for (CellIterator c(mesh); !c.end(); ++c)
          {
            double midz = c->midpoint().z();
            for (layer = 0; layer < num_layers; layer++)
              if (layer_boundaries[layer] <= midz && midz <= layer_boundaries[layer+1])
                break;

            int dof = cell_dofs[c->index()];
            local_cell_layers[dof] = layer;
          }
        }
      }
    '''

    cell_mapping_module = compile_extension_module(code)

    cell_layers_array =  IntArray(self.local_ndof0)
    cell_mapping_module.fill_in(cell_layers_array, self.mesh, self.local_cell_dof_map, self.core.layer_boundaries)
    self._local_cell_layers = cell_layers_array.array()

    timer.stop()

  def __create_cell_vol_mapping(self):
    """
    Generate cell -> volume mapping for all cells of current partition. Note that keys are ordered by the
    associated DG(0) dof, not by the cell index in the mesh.

    This map is required for calculating various densities from total region integrals (like cell power densities from
    cell-integrated powers).
    """

    if self.verb > 2: print0("Constructing cell -> volume mapping")
    timer = Timer("DD: Cell->vol construction")

    code = \
    '''
      #include <dolfin/mesh/Cell.h>

      namespace dolfin
      {
        void fill_in(Array<double>& cell_vols, const Mesh& mesh, const Array<int>& cell_dofs)
        {
          for (CellIterator c(mesh); !c.end(); ++c)
            cell_vols[cell_dofs[c->index()]] = c->volume();
        }
      }
    '''

    cell_mapping_module = compile_extension_module(code)
    cell_vol_array = DoubleArray(self.local_ndof0)
    cell_mapping_module.fill_in(cell_vol_array, self.mesh, self.local_cell_dof_map)
    self._local_cell_volumes = cell_vol_array.array()

    timer.stop()

  @property
  def local_cell_dof_map(self):
    try:
      self._local_cell_dof_map
    except AttributeError:
      self.__create_cell_dof_mapping(self.V0.dofmap())
    return self._local_cell_dof_map

  @property
  def local_cell_volumes(self):
    try:
      self._local_cell_volumes
    except AttributeError:
      self.__create_cell_vol_mapping()
    return self._local_cell_volumes

  @property
  def local_cell_layers(self):
    try:
      self._local_cell_layers
    except AttributeError:
      self.__create_cell_layers_mapping()
    return self._local_cell_layers

  def visualize_mesh_data(self):
    timer = Timer("DD: Mesh data visualization")
    if self.verb > 2: print0("Visualizing mesh data")

    File(os.path.join(self.vis_folder, "mesh.pvd"), "compressed") << self.mesh
    if self.boundaries:
      File(os.path.join(self.vis_folder, "boundaries.pvd"), "compressed") << self.boundaries
    File(os.path.join(self.vis_folder, "mesh_regions.pvd"), "compressed") << self.cell_regions_fun

    # Create MeshFunction to hold cell process rank
    processes = CellFunction('size_t', self.mesh, MPI.rank(comm))
    File(os.path.join(self.vis_folder, "mesh_partitioning.pvd"), "compressed") << processes

  def print_diagnostics(self):
    print "\nDiscretization diagnostics"

    print MPI.rank(comm), self.mesh.num_entities(self.mesh.topology().dim())

    dofmap = self.V0.dofmap()

    print MPI.rank(comm), dofmap.ownership_range()
    print MPI.rank(comm), numpy.min(dofmap.collapse(self.mesh)[1].values()), \
          numpy.max(dofmap.collapse(self.mesh)[1].values())

    print "#Owned by {}: {}".format(MPI.rank(comm), dofmap.local_dimension("owned"))
    print "#Unowned by {}: {}".format(MPI.rank(comm), dofmap.local_dimension("unowned"))