Exemplo n.º 1
0
def compute_velocity(mesh, Vh, a, u):
    #export the velocity field v = - exp( a ) \grad u: then we solve ( exp(-a) v, w) = ( u, div w)
    Vv = dl.FunctionSpace(mesh, 'RT', 1)
    v = dl.Function(Vv, name="velocity")
    vtrial = dl.TrialFunction(Vv)
    vtest = dl.TestFunction(Vv)
    afun = dl.Function(Vh[PARAMETER], a)
    ufun = dl.Function(Vh[STATE], u)
    Mv = dl.exp(-afun) * dl.inner(vtrial, vtest) * dl.dx
    n = dl.FacetNormal(mesh)

    class TopBoundary(dl.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary and x[1] > 1 - dl.DOLFIN_EPS

    Gamma_M = TopBoundary()
    boundaries = dl.FacetFunction("size_t", mesh)
    boundaries.set_all(0)
    Gamma_M.mark(boundaries, 1)
    dss = dl.Measure("ds")[boundaries]
    rhs = ufun * dl.div(vtest) * dl.dx - dl.dot(vtest, n) * dss(1)
    bcv = dl.DirichletBC(Vv, dl.Expression(("0.0", "0.0")), v_boundary)
    dl.solve(Mv == rhs, v, bcv)

    return v
    def __init__(self, mesh, Vh_STATE, x0):
        """
        Constructor.
        INPUTS:
        
        - mesh: the mesh
        - Vh_STATE: the finite element space for the state variable
        - x0: location at which we want to compute the jet-thickness
        """

        Vh_help = dl.FunctionSpace(mesh, "CG", 1)
        xfun = dl.interpolate(dl.Expression("x[0]", degree=1), Vh_help)
        x_coord = xfun.vector().gather_on_zero()

        mpi_comm = mesh.mpi_comm()
        rank = dl.MPI.rank(mpi_comm)
        nproc = dl.MPI.size(mpi_comm)

        # round x0 so that it is aligned with the mesh
        if nproc > 1:
            from mpi4py import MPI
            comm = MPI.COMM_WORLD
            if rank == 0:
                idx = (np.abs(x_coord - x0)).argmin()
                self.x0 = x_coord[idx]
            else:
                self.x0 = None

            self.x0 = comm.bcast(self.x0, root=0)
        else:
            idx = (np.abs(x_coord - x0)).argmin()
            self.x0 = x_coord[idx]

        line_segment = dl.AutoSubDomain(lambda x: dl.near(x[0], self.x0))
        markers_f = dl.FacetFunction("size_t", mesh)
        markers_f.set_all(0)
        line_segment.mark(markers_f, 1)
        dS = dl.dS[markers_f]

        x_test = dl.TestFunctions(Vh_STATE)
        u_test = x_test[0]

        e1 = dl.Constant(("1.", "0."))

        self.int_u = dl.assemble(dl.avg(dl.dot(u_test, e1)) * dS(1))
        #self.u_cl = dl.assemble( dl.dot(u_test,e1)*dP(1) )

        self.u_cl = dl.Function(Vh_STATE).vector()
        ps = dl.PointSource(Vh_STATE.sub(0).sub(0), dl.Point(self.x0, 0.), 1.)
        ps.apply(self.u_cl)

        scaling = self.u_cl.sum()
        if np.abs(scaling - 1.) > 1e-6:
            print scaling
            raise ValueError()

        self.state = dl.Function(Vh_STATE).vector()
        self.help = dl.Function(Vh_STATE).vector()
Exemplo n.º 3
0
    def read(self, h5_file_name, read_input=True, read_results=True):
        """
        Read an HDF5 restart file on the format written by _write_hdf5()
        """
        # Check file format and read metadata
        t, it, dt, inpdata, funcnames = self.read_metadata(h5_file_name)

        sim = self.simulation
        h5 = dolfin.HDF5File(dolfin.MPI.comm_world, h5_file_name, 'r')

        # This flag is used in sim.setup() to to skip mesh creation
        # and may be used by user code etc
        sim.restarted = True

        if read_input:
            # Read the input file
            sim.input.read_yaml(yaml_string=inpdata)
            sim.input.file_name = h5_file_name
            sim.input.set_value('time/tstart', t)
            sim.input.set_value('time/dt', dt)

            # Read mesh data
            mesh = dolfin.Mesh()
            h5.read(mesh, '/mesh', False)
            if h5.has_dataset('/mesh_facet_regions'):
                mesh_facet_regions = dolfin.FacetFunction('size_t', mesh)
                h5.read(mesh_facet_regions, '/mesh_facet_regions')
            else:
                mesh_facet_regions = None
            sim.set_mesh(mesh, mesh_facet_regions)

            # Setup needs to know that the simulation was restarted for
            # XDMF file renaming (among other possible uses)
            sim.timestep = it

        if read_results:
            sim.log.info('Reading fields from restart file %r' % h5_file_name)
            sim.timestep = it

            # Read result field functions
            for name in funcnames:
                sim.log.info('    Function %s' % name)
                h5.read(sim.data[name], '/%s' % name)

            h5.close()  # Close dolfin.HDF5File

            # Read persisted data dictionaries with h5py
            with h5py.File(h5_file_name, 'r') as hdf:
                pdd = hdf.get('ocellaris_data', {})
                for pdi in pdd.values():
                    name = pdi['name'].value
                    data = pdi['data'].value

                    # Parse YAML data and update the persistent data store
                    data2 = yaml.load(data)
                    data3 = self.persisted_python_data.setdefault(name, {})
                    data3.update(data2)
Exemplo n.º 4
0
def load_h5_mesh(fname):
    mesh = df.Mesh()
    comm = mesh.mpi_comm()
    hdf = df.HDF5File(comm, fname, "r")
    hdf.read(mesh, "/mesh", False)
    subdomains = df.CellFunction("size_t", mesh)
    hdf.read(subdomains, "/subdomains")
    boundaries = df.FacetFunction("size_t", mesh)
    hdf.read(boundaries, "/boundaries")
    return mesh, boundaries, comm
Exemplo n.º 5
0
    def __init__(self, box, nx, ny):
        """
        Constructor
        
        INPUTS:
        - box = [x_min, x_max, y_min, y_max]: the bounding box of the computational domain
        - nx, ny: number of elements in the horizontal (axial) and vertical (transversal) direction
        """
        self.box = box
        self.mesh = dl.UnitSquareMesh(nx, ny)

        grade = GradingFunctionLin(coordinate=1, cut_point=[.6, .7], slope=6)
        remap = Remap(box=box)

        self.mesh.move(grade)
        self.mesh.move(remap)

        class InletBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[0] - box[0]) < dl.DOLFIN_EPS

        class SymmetryBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[1] - box[2]) < dl.DOLFIN_EPS

        class FarfieldBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and (abs(x[0] - box[1]) < dl.DOLFIN_EPS
                                        or abs(x[1] - box[3]) < dl.DOLFIN_EPS)

        self.boundary_parts = dl.FacetFunction("size_t", self.mesh)
        self.boundary_parts.set_all(0)

        Gamma_inlet = InletBoundary()
        Gamma_inlet.mark(self.boundary_parts, self.INLET)
        Gamma_axis = SymmetryBoundary()
        Gamma_axis.mark(self.boundary_parts, self.AXIS)
        Gamma_farfield = FarfieldBoundary()
        Gamma_farfield.mark(self.boundary_parts, self.FARFIELD)

        self.ds = dl.Measure("ds")[self.boundary_parts]

        class DNSDomain(dl.SubDomain):
            def inside(self, x, on_boundary):
                return x[0] < 20. + dl.DOLFIN_EPS

        self.domain_parts = dl.CellFunction("size_t", self.mesh)
        self.domain_parts.set_all(self.OUTSIDE)
        DNS_Domain = DNSDomain()
        DNS_Domain.mark(self.domain_parts, self.DNS)

        self.dx = dl.Measure("dx")[self.domain_parts]
Exemplo n.º 6
0
    def setUp(self):
        self.mesh = mesh = dolfin.UnitSquareMesh(20, 2, "left")
        self.DG0_element = DG0e = dolfin.FiniteElement("DG", mesh.ufl_cell(),
                                                       0)
        self.DG0v_element = DG0ve = dolfin.VectorElement(
            "DG", mesh.ufl_cell(), 0)
        self.DG0 = DG0 = dolfin.FunctionSpace(mesh, DG0e)
        self.DG0v = DG0v = dolfin.FunctionSpace(mesh, DG0ve)

        self.fsr = fsr = FunctionSubspaceRegistry()
        fsr.register(DG0)
        fsr.register(DG0v)

        self.cellmid = cm = CellMidpointExpression(mesh, element=DG0ve)
        self.n = n = dolfin.FacetNormal(mesh)

        self.u = u = dolfin.Function(DG0)
        self.v = v = dolfin.TestFunction(DG0)

        u_bc = dolfin.Expression('x[0]', degree=2)

        x = dolfin.SpatialCoordinate(mesh)
        self.rho = rho = dolfin.conditional(
            dolfin.lt((x[0] - 0.5)**2 + (x[1] - 0.5)**2, 0.2**2), 0.0, 0.0)

        dot = dolfin.dot
        cellsize = dolfin.CellSize(mesh)
        self.h = h = cm('+') - cm('-')
        self.h_boundary = h_boundary = 2 * n * dot(x - cm, n)
        self.E = E = h / dot(h, h) * (u('-') - u('+'))
        self.E_boundary = E_boundary = h_boundary / dot(
            h_boundary, h_boundary) * (u - u_bc)
        dS = dolfin.dS

        eps = 1e-8

        class BL(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return abs(x[0]) < eps

        class BR(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return abs(x[0] - 1) < eps

        ff = dolfin.FacetFunction('size_t', mesh, 0)
        BL().mark(ff, 1)
        BR().mark(ff, 1)

        ds = dolfin.Measure('ds', domain=mesh, subdomain_data=ff)

        self.F = (dot(E, n('+')) * v('+') * dS + dot(E, n('-')) * v('-') * dS -
                  v * rho * dolfin.dx + dot(E_boundary, n) * v * ds(1))
    def __init__(self, mesh, x0, y0, x1, y1):
        #: A :class:`dolfin.Mesh` containing the mesh.
        self.mesh = mesh

        class Left(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and dolfin.near(x[0], x0)

        class Right(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and dolfin.near(x[0], x1)

        class Sides(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and (dolfin.near(x[1], y0) or dolfin.near(x[1], y1))

        #NEW
        class TurbineArea(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return True if (x[0] <= 1250 and x[1] <= 650 and 750 <= x[0] and 350 <= x[1]) else False
        #NEW

        # Initialize sub-domain instances
        left = Left()
        right = Right()
        sides = Sides()
        turbine_area = TurbineArea()
        
        # Create facet markers
        #: A :class:`dolfin.FacetFunction` containing the surface markers.
        self.facet_ids = dolfin.FacetFunction('size_t', self.mesh)
        self.facet_ids.set_all(0)
        left.mark(self.facet_ids, 1)
        right.mark(self.facet_ids, 2)
        sides.mark(self.facet_ids, 3)
        #: A :class:`dolfin.Measure` for the facet parts.
        self._ds = dolfin.Measure('ds')[self.facet_ids]

        #: A :class:`dolfin.CellFunction` containing the area markers.
        self.cell_ids = dolfin.CellFunction("size_t", self.mesh)
        self.cell_ids.set_all(0)
        
        #NEW
        turbine_area.mark(self.cell_ids,1)
        #NEWa

        #: A :class:`dolfin.Measure` for the cell cell_ids.
        self._dx = dolfin.Measure("dx")[self.cell_ids]
Exemplo n.º 8
0
    def init_bc(self):
        eps = 1e-10

        class BL(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return abs(x[0]) < eps

        class BR(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return abs(x[0] - 1) < eps

        ff = dolfin.FacetFunction('size_t', mesh, 0)
        BL().mark(ff, 1)
        BR().mark(ff, 1)

        ds = dolfin.Measure('ds', domain=mesh, subdomain_data=ff)
Exemplo n.º 9
0
    def __init__(self):
        pyurdme.URDMEModel.__init__(self, name="simple_diffusion2")

        A = pyurdme.Species(name="A", diffusion_constant=0.1, dimension=2)
        B = pyurdme.Species(name="B", diffusion_constant=0.1, dimension=1)

        self.add_species([A, B])

        # Import a circle mesh
        self.mesh = pyurdme.URDMEMesh.read_dolfin_mesh("circle.xml")

        # A mesh function for the cells
        cell_function = dolfin.CellFunction("size_t", self.mesh)
        cell_function.set_all(1)

        # Create a mesh function over then edges of the mesh
        facet_function = dolfin.FacetFunction("size_t", self.mesh)
        facet_function.set_all(0)

        # Mark the boundary points
        membrane = Membrane()
        membrane.mark(facet_function, 2)

        membrane_patch = MembranePatch()
        membrane_patch.mark(facet_function, 3)

        self.add_subdomain(cell_function)
        self.add_subdomain(facet_function)

        k1 = pyurdme.Parameter(name="k1", expression=100.0)
        self.add_parameter([k1])

        R1 = pyurdme.Reaction(name="R1",
                              reactants={A: 1},
                              products={B: 1},
                              massaction=True,
                              rate=k1,
                              restrict_to=3)
        self.add_reaction([R1])

        # Restrict species B to the membrane subdomain
        self.restrict(species=B, subdomains=[2, 3])
        self.timespan(numpy.linspace(0, 1, 50))

        # Place the A molecules in the voxel nearest to the center of the square
        self.set_initial_condition_place_near({A: 10000}, point=[0, 0])
Exemplo n.º 10
0
def unit_mesh(N, ext_bnd_id=1):
    """
    Given a list of cell divisions, N, returns a mesh with unit size in each
    spatial direction.
    """
    d = len(N)
    mesh_types = [df.UnitIntervalMesh, df.UnitSquareMesh, df.UnitCubeMesh]
    mesh = mesh_types[d - 1](*N)
    facet_func = df.FacetFunction('size_t', mesh)
    facet_func.set_all(0)

    class ExtBnd(df.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary

    bnd = ExtBnd()
    bnd.mark(facet_func, ext_bnd_id)
    return mesh, facet_func
Exemplo n.º 11
0
                def __init__(self, mesh):
                    class InFlow(dolfin.SubDomain):
                        def inside(self, x, on_boundary):
                            return dolfin.near(x[0], -100)

                    class OutFlow(dolfin.SubDomain):
                        def inside(self, x, on_boundary):
                            return dolfin.near(x[0], 900)

                    inflow = InFlow()
                    outflow = OutFlow()

                    self.mesh = mesh
                    self.boundaries = dolfin.FacetFunction("size_t", mesh)
                    self.boundaries.set_all(0)
                    inflow.mark(self.boundaries, 1)
                    outflow.mark(self.boundaries, 2)

                    self.ds = dolfin.Measure('ds')[self.boundaries]
Exemplo n.º 12
0
def markers(mesh, objects):
    """
    Marks the facets on the boundary of the objects.

    Args:
         mesh   : The mesh of the simulation domain
         objects: A list containing all the objects

    returns:
            The marked facets of the objects.
    """
    num_objects = len(objects)

    facet_func = df.FacetFunction('size_t', mesh)
    facet_func.set_all(num_objects)

    for i, o in enumerate(objects):
        facet_func = o.mark_facets(facet_func, i)

    return facet_func
Exemplo n.º 13
0
    def set_FEM(self):
        """
        Define finite element space of elliptic PDE.
        """
        self.mesh = df.UnitSquareMesh(self.nx, self.ny)
        self.mpi_comm = self.mesh.mpi_comm()

        # boundaries
        self.boundaries = df.FacetFunction("size_t", self.mesh, 0)
        self.ds = df.ds(subdomain_data=self.boundaries)

        # 2. Define the finite element spaces and build mixed space
        try:
            V_fe = df.FiniteElement("CG", self.mesh.ufl_cell(), 2)
            L_fe = df.FiniteElement("CG", self.mesh.ufl_cell(), 2)
            self.V = df.FunctionSpace(self.mesh, V_fe)
            self.W = df.FunctionSpace(self.mesh, V_fe * L_fe)
        except TypeError:
            print('Warning: '
                  'MixedFunctionSpace'
                  ' has been deprecated in DOLFIN version 1.7.0.')
            print('It will be removed from version 2.0.0.')
            self.V = df.FunctionSpace(self.mesh, 'CG', 2)
            L = df.FunctionSpace(self.mesh, 'CG', 2)
            self.W = self.V * L

        # 3. Define boundary conditions
        bc_lagrange = df.DirichletBC(
            self.W.sub(1), df.Constant(0.0),
            "fabs(x[0])>2.0*DOLFIN_EPS & fabs(x[0]-1.0)>2.0*DOLFIN_EPS & fabs(x[1])>2.0*DOLFIN_EPS & fabs(x[1]-1.0)>2.0*DOLFIN_EPS"
        )

        self.ess_bc = [bc_lagrange]

        # Create adjoint boundary conditions (homogenized forward BCs)
        def homogenize(bc):
            bc_copy = df.DirichletBC(bc)
            bc_copy.homogenize()
            return bc_copy

        self.adj_bcs = [homogenize(bc) for bc in self.ess_bc]
Exemplo n.º 14
0
    def __init__(self, x0, y0, x1, y1, nx, ny):
        #: A :class:`dolfin.Mesh` containing the mesh.
        mpi_comm = dolfin.mpi_comm_world()
        self.mesh = dolfin.RectangleMesh(mpi_comm, dolfin.Point(x0, y0),
                                         dolfin.Point(x1, y1), nx, ny)

        class Left(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and dolfin.near(x[0], x0)

        class Right(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and dolfin.near(x[0], x1)

        class Sides(dolfin.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and (dolfin.near(x[1], y0)
                                        or dolfin.near(x[1], y1))

        # Initialize sub-domain instances
        left = Left()
        right = Right()
        sides = Sides()

        # Create facet markers
        #: A :class:`dolfin.FacetFunction` containing the surface markers.
        self.facet_ids = dolfin.FacetFunction('size_t', self.mesh)
        self.facet_ids.set_all(0)
        left.mark(self.facet_ids, 1)
        right.mark(self.facet_ids, 2)
        sides.mark(self.facet_ids, 3)
        #: A :class:`dolfin.Measure` for the facet parts.
        self._ds = dolfin.Measure('ds')[self.facet_ids]

        #: A :class:`dolfin.CellFunction` containing the area markers.
        self.cell_ids = dolfin.CellFunction("size_t", self.mesh)
        self.cell_ids.set_all(0)
        #: A :class:`dolfin.Measure` for the cell cell_ids.
        self._dx = dolfin.Measure("dx")[self.cell_ids]
Exemplo n.º 15
0
def simple_mesh(Ld, N, ext_bnd_id=1):
    """
    Returns a mesh for a given list, Ld, containing the size of domain in each
    spatial direction, and the corresponding number of cell divisions N.
    """
    d = len(N)
    mesh_types = [df.RectangleMesh, df.BoxMesh]

    if d == 1:
        mesh = df.IntervalMesh(N[0], 0.0, Ld[0])
    else:
        mesh = mesh_types[d - 2](df.Point(*np.zeros(len(Ld))), df.Point(*Ld),
                                 *N)

    facet_func = df.FacetFunction('size_t', mesh)
    facet_func.set_all(0)

    class ExtBnd(df.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary

    bnd = ExtBnd()
    bnd.mark(facet_func, ext_bnd_id)
    return mesh, facet_func
Exemplo n.º 16
0
def load_mesh(simulation):
    """
    Get the mesh from the simulation input

    Returns the facet regions contained in the mesh data
    or None if these do not exist
    """
    inp = simulation.input
    mesh_type = inp.get_value('mesh/type', required_type='string')
    mesh_facet_regions = None

    # For testing COMM_SELF may be specified
    comm_type = inp.get_value('mesh/mpi_comm', 'WORLD', required_type='string')
    verify_key('mesh/mpi_comm', comm_type, ('SELF', 'WORLD'))
    if comm_type == 'WORLD':
        comm = dolfin.MPI.comm_world
    else:
        comm = dolfin.MPI.comm_self

    if mesh_type == 'Rectangle':
        simulation.log.info('Creating rectangular mesh')

        startx = inp.get_value('mesh/startx', 0, 'float')
        starty = inp.get_value('mesh/starty', 0, 'float')
        start = dolfin.Point(startx, starty)
        endx = inp.get_value('mesh/endx', 1, 'float')
        endy = inp.get_value('mesh/endy', 1, 'float')
        end = dolfin.Point(endx, endy)
        Nx = inp.get_value('mesh/Nx', required_type='int')
        Ny = inp.get_value('mesh/Ny', required_type='int')
        diagonal = inp.get_value('mesh/diagonal',
                                 'right',
                                 required_type='string')

        mesh = dolfin.RectangleMesh(comm, start, end, Nx, Ny, diagonal)

    elif mesh_type == 'Box':
        simulation.log.info('Creating box mesh')

        startx = inp.get_value('mesh/startx', 0, 'float')
        starty = inp.get_value('mesh/starty', 0, 'float')
        startz = inp.get_value('mesh/startz', 0, 'float')
        start = dolfin.Point(startx, starty, startz)
        endx = inp.get_value('mesh/endx', 1, 'float')
        endy = inp.get_value('mesh/endy', 1, 'float')
        endz = inp.get_value('mesh/endz', 1, 'float')
        end = dolfin.Point(endx, endy, endz)
        Nx = inp.get_value('mesh/Nx', required_type='int')
        Ny = inp.get_value('mesh/Ny', required_type='int')
        Nz = inp.get_value('mesh/Nz', required_type='int')

        mesh = dolfin.BoxMesh(comm, start, end, Nx, Ny, Nz)

    elif mesh_type == 'UnitDisc':
        simulation.log.info('Creating circular mesh')

        N = inp.get_value('mesh/N', required_type='int')
        degree = inp.get_value('mesh/degree', 1, required_type='int')
        gdim = inp.get_value('mesh/gdim', 2, required_type='int')

        mesh = dolfin.UnitDiscMesh(comm, N, degree, gdim)

        if degree > 1 and dolfin.parameters['form_compiler'][
                'representation'] != 'uflacs':
            simulation.log.warning(
                'Using isoparametric elements without uflacs!')

    elif mesh_type == 'XML':
        simulation.log.info('Creating mesh from XML file')
        simulation.log.warning('(deprecated, please use meshio reader)')

        mesh_file = inp.get_value('mesh/mesh_file', required_type='string')
        facet_region_file = inp.get_value('mesh/facet_region_file',
                                          None,
                                          required_type='string')

        # Load the mesh from file
        pth = inp.get_input_file_path(mesh_file)
        mesh = dolfin.Mesh(comm, pth)

        # Load the facet regions if available
        if facet_region_file is not None:
            pth = inp.get_input_file_path(facet_region_file)
            mesh_facet_regions = dolfin.MeshFunction('size_t', mesh, pth)
        else:
            mesh_facet_regions = None

    elif mesh_type == 'XDMF':
        simulation.log.info('Creating mesh from XDMF file')
        simulation.log.warning('(deprecated, please use meshio reader)')

        mesh_file = inp.get_value('mesh/mesh_file', required_type='string')

        # Load the mesh from file
        pth = inp.get_input_file_path(mesh_file)
        mesh = dolfin.Mesh(comm)
        with dolfin.XDMFFile(comm, pth) as xdmf:
            xdmf.read(mesh, False)

    elif mesh_type == 'HDF5':
        simulation.log.info('Creating mesh from DOLFIN HDF5 file')
        h5_file_name = inp.get_value('mesh/mesh_file', required_type='string')

        with dolfin.HDF5File(comm, h5_file_name, 'r') as h5:
            # Read mesh
            mesh = dolfin.Mesh(comm)
            h5.read(mesh, '/mesh', False)

            # Read facet regions
            if h5.has_dataset('/mesh_facet_regions'):
                mesh_facet_regions = dolfin.FacetFunction('size_t', mesh)
                h5.read(mesh_facet_regions, '/mesh_facet_regions')
            else:
                mesh_facet_regions = None

    elif mesh_type == 'meshio':
        simulation.log.info('Creating mesh with meshio reader')
        file_name = inp.get_value('mesh/mesh_file', required_type='string')
        file_type = inp.get_value('mesh/meshio_type',
                                  None,
                                  required_type='string')
        sort_order = inp.get_value('mesh/sort_order',
                                   None,
                                   required_type='list(int)')

        if sort_order:
            simulation.log.info('    Ordering mesh elements by ' +
                                ', then '.join('xyz'[i] for i in sort_order))

        # Read mesh on rank 0
        t1 = time.time()
        mesh = dolfin.Mesh(comm)
        if comm.rank == 0:
            # Read a mesh file by use of meshio
            physical_regions = load_meshio_mesh(mesh, file_name, file_type,
                                                sort_order)
            simulation.log.info('    Read mesh with %d cells in %.2f seconds' %
                                (mesh.num_cells(), time.time() - t1))
        else:
            physical_regions = None

        # Distribute the mesh
        if comm.size > 1:
            physical_regions = comm.bcast(physical_regions)
            t1 = time.time()
            simulation.log.info('    Distributing mesh to %d processors' %
                                comm.size)
            build_distributed_mesh(mesh)
            simulation.log.info('    Distributed mesh in %.2f seconds' %
                                (time.time() - t1))
    else:
        ocellaris_error('Unknown mesh type',
                        'Mesh type %r is not supported' % mesh_type)

    # Optionally move the mesh (for simple grading etc)
    move = inp.get_value('mesh/move', None, required_type='list(string)')
    if move is not None:
        simulation.log.info('    Moving mesh')
        if len(move) != mesh.geometry().dim():
            ocellaris_error(
                'Mesh move not correct',
                'Length of move field is %d while geometric dimension is %r' %
                (len(move), mesh.geometry().dim()),
            )
        e_move = dolfin.Expression(move, degree=1)
        V_move = dolfin.VectorFunctionSpace(mesh, 'CG', 1)
        f_move = dolfin.interpolate(e_move, V_move)
        dolfin.ALE.move(mesh, f_move)
        mesh.bounding_box_tree().build(mesh)

    # Update the simulation
    simulation.set_mesh(mesh, mesh_facet_regions)

    # Load meshio facet regions
    if mesh_type == 'meshio' and physical_regions:
        mfr = dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
        conn_FV = simulation.data['connectivity_FV']
        vcoords = mesh.coordinates()
        for ifacet in range(mfr.size()):
            facet_vertices = conn_FV(ifacet)
            key = sorted([tuple(vcoords[vidx]) for vidx in facet_vertices])
            number = physical_regions.get(tuple(key), 0)
            mfr[ifacet] = number
        # Store the loaded regions
        simulation.data['mesh_facet_regions'] = mfr
        mesh_facet_regions = mfr

    # Optionally plot mesh right after loading (for debugging)
    if simulation.input.get_value('output/plot_mesh', False, 'bool'):
        prefix = simulation.input.get_value('output/prefix', '', 'string')
        pfile = prefix + '_mesh.xdmf'
        simulation.log.info(
            '    Plotting mesh with current MPI ranks to XDMF file %r' % pfile)
        V0 = dolfin.FunctionSpace(mesh, 'DG', 0)
        ranks = dolfin.Function(V0)
        ranks.vector().set_local(ranks.vector().get_local() * 0 + comm.rank)
        ranks.vector().apply('insert')
        ranks.rename('MPI_rank', 'MPI_rank')
        with dolfin.XDMFFile(comm, pfile) as xdmf:
            xdmf.write(ranks)

    # Optionally plot facet regions to file
    if simulation.input.get_value('output/plot_facet_regions', False, 'bool'):
        prefix = simulation.input.get_value('output/prefix', '', 'string')
        pfile = prefix + '_input_facet_regions.xdmf'
        simulation.log.info(
            '    Plotting input mesh facet regions to XDMF file %r' % pfile)
        if mesh_facet_regions is None:
            simulation.log.warning(
                'Cannot plot mesh facet regions, no regions found!')
        else:
            with dolfin.XDMFFile(comm, pfile) as xdmf:
                xdmf.write(mesh_facet_regions)
def spreadFunction(u, mesh, x_max=None):
    """
    This routine computes the following quantities as a function of the distance x from the inflow:
    - The centerline velocity: u_cl
    - The integral jet thickness: L
    - The spread function (derivative of jet thickness): S
    - The jet thickness: y_1/2
    
    INPUTS:
    - the velocity u
    - the mesh mesh
    """
    boundary_mesh = dl.BoundaryMesh(mesh, "exterior")
    x = boundary_mesh.coordinates()
    x_coord = x[np.abs(x[:, 1]) < 1e-9, 0]
    if x_max is not None:
        x_coord = x_coord[x_coord <= x_max]
    e1 = dl.Expression(("1.", "0."))
    u1, u2 = u.split(deepcopy=True)

    Vh_grad = dl.FunctionSpace(mesh, 'RT', 1)
    grad_u1 = dl.Function(Vh_grad)
    test = dl.TestFunction(Vh_grad)
    n = dl.FacetNormal(mesh)
    dl.solve(
        dl.inner(grad_u1, test) * dl.dx + u1 * dl.div(test) * dl.dx -
        u1 * dl.dot(test, n) * dl.ds == 0, grad_u1)

    axis = dl.AutoSubDomain(lambda x: dl.near(x[1], 0.))
    axis_mesh = dl.SubMesh(boundary_mesh, axis)
    Vh_axis = dl.FunctionSpace(axis_mesh, "CG", 2)
    u1_axis = dl.interpolate(u1, Vh_axis)
    Vh_axis_grad = dl.FunctionSpace(axis_mesh, 'CG', 1)
    du1_dx = dl.Function(Vh_axis_grad)
    test_axis = dl.TestFunction(Vh_axis_grad)
    left_point = dl.AutoSubDomain(
        lambda x, on_boundary: dl.near(x[0], x_coord[0]) and on_boundary)
    right_point = dl.AutoSubDomain(
        lambda x, on_boundary: dl.near(x[0], x_coord[-1]) and on_boundary)
    bb_marker = dl.FacetFunction("size_t", axis_mesh)
    bb_marker.set_all(0)
    left_point.mark(bb_marker, 1)
    right_point.mark(bb_marker, 2)
    dss = dl.Measure("ds")[bb_marker]

    dl.solve(
        du1_dx * test_axis * dl.dx + u1_axis * test_axis.dx(0) * dl.dx +
        u1_axis * test_axis * dss(1) - u1_axis * test_axis * dss(2) == 0,
        du1_dx)

    u_cl = np.zeros(x_coord.shape)
    L = np.zeros(x_coord.shape)
    S = np.zeros(x_coord.shape)
    y_half = np.zeros(x_coord.shape)

    i = 0
    for xi in x_coord:
        line_segment = dl.AutoSubDomain(lambda x: dl.near(x[0], xi))
        markers = dl.FacetFunction("size_t", mesh)
        markers.set_all(0)
        line_segment.mark(markers, 1)

        if i == 0 or (i == (x_coord.shape[0] - 1) and x_max is None):
            ds = dl.ds[markers]
            int_u1 = dl.assemble(u1 * ds(1))
            int_du1_dx = dl.assemble(dl.dot(grad_u1, e1) * ds(1))
        else:
            dS = dl.dS[markers]
            int_u1 = dl.assemble(dl.avg(u1) * dS(1))
            int_du1_dx = dl.assemble(dl.avg(dl.dot(grad_u1, e1)) * dS(1))

        u_cl[i] = u1((xi, 0.))
        du_cl_dx = du1_dx((xi, 0.))
        L[i] = int_u1 / u_cl[i]
        S[i] = (int_du1_dx * u_cl[i] - int_u1 * du_cl_dx) / (u_cl[i] * u_cl[i])
        y_half[i] = _bisection(u1, 9., 0., .5 * u_cl[i], xi)

        i += 1

    out = np.zeros((x_coord.shape[0], 5), dtype=x_coord.dtype)
    out[:, 0] = x_coord
    out[:, 1] = u_cl
    out[:, 2] = L
    out[:, 3] = S
    out[:, 4] = y_half

    return out
def extractFeNiCsBiVFacet(ugrid, geometry="BiV"):

    tol = 1e-2

    #ugrid = vtk_py.readUGrid(meshfilename)

    # Extract surface
    geom = vtk.vtkGeometryFilter()
    if (vtk.vtkVersion().GetVTKMajorVersion() < 6):
        geom.SetInput(ugrid)
    else:
        geom.SetInputData(ugrid)
    geom.Update()
    surf = geom.GetOutput()

    bc_pts_locator = []
    bc_pts = []
    bc_pts_range = []
    bc_pts_map = []

    # Extract Surface Normal
    normal = vtk.vtkPolyDataNormals()
    if (vtk.vtkVersion().GetVTKMajorVersion() < 6):
        normal.SetInput(surf)
    else:
        normal.SetInputData(surf)
    normal.ComputeCellNormalsOn()
    normal.Update()
    surf_w_norm = normal.GetOutput()

    #vtk_py.writePData(normal.GetOutput(), "normal.vtk")

    zmax = surf_w_norm.GetBounds()[5]

    surf_w_norm.BuildLinks()
    idlist = vtk.vtkIdList()
    basecellidlist = vtk.vtkIdTypeArray()
    basesurf = vtk.vtkPolyData()
    for p in range(0, surf_w_norm.GetNumberOfCells()):
        zvec = surf_w_norm.GetCellData().GetNormals().GetTuple3(p)[2]

        surf_w_norm.GetCellPoints(p, idlist)
        zpos = surf_w_norm.GetPoints().GetPoint(idlist.GetId(0))[2]

        if ((abs(zvec - 1.0) < tol or abs(zvec + 1.0) < tol)
                and (abs(zmax - zpos) < tol)):
            surf_w_norm.DeleteCell(p)
            basecellidlist.InsertNextValue(p)

    basesurf = vtk_py.extractCellFromPData(basecellidlist, surf)
    baseptlocator = vtk.vtkPointLocator()
    baseptlocator.SetDataSet(basesurf)
    baseptlocator.BuildLocator()

    #######################################################################

    surf_w_norm.RemoveDeletedCells()

    cleanpdata = vtk.vtkCleanPolyData()
    if (vtk.vtkVersion().GetVTKMajorVersion() < 6):
        cleanpdata.SetInput(surf_w_norm)
    else:
        cleanpdata.SetInputData(surf_w_norm)
    cleanpdata.Update()

    connfilter = vtk.vtkPolyDataConnectivityFilter()
    if (vtk.vtkVersion().GetVTKMajorVersion() < 6):
        connfilter.SetInput(cleanpdata.GetOutput())
    else:
        connfilter.SetInputData(cleanpdata.GetOutput())
    connfilter.Update()

    print "Total_num_points = ", cleanpdata.GetOutput().GetNumberOfPoints()
    tpt = 0

    if (geometry == "BiV"):
        nsurf = 3
    else:
        nsurf = 2

    for p in range(0, nsurf):

        pts = vtk.vtkPolyData()

        connfilter.SetExtractionModeToSpecifiedRegions()
        [connfilter.DeleteSpecifiedRegion(k) for k in range(0, nsurf)]
        connfilter.AddSpecifiedRegion(p)
        connfilter.ScalarConnectivityOff()
        connfilter.FullScalarConnectivityOff()
        connfilter.Update()

        cleanpdata2 = vtk.vtkCleanPolyData()
        if (vtk.vtkVersion().GetVTKMajorVersion() < 6):
            cleanpdata2.SetInput(connfilter.GetOutput())
        else:
            cleanpdata2.SetInputData(connfilter.GetOutput())
        cleanpdata2.Update()

        pts.DeepCopy(cleanpdata2.GetOutput())

        tpt = tpt + cleanpdata2.GetOutput().GetNumberOfPoints()

        ptlocator = vtk.vtkPointLocator()
        ptlocator.SetDataSet(pts)
        ptlocator.BuildLocator()

        bc_pts_locator.append(ptlocator)
        bc_pts.append(pts)
        bc_pts_range.append([
            abs(pts.GetBounds()[k + 1] - pts.GetBounds()[k])
            for k in range(0, 6, 2)
        ])

    #vtk_py.writePData(connfilter.GetOutput(), "/home/likchuan/Research/fenicsheartmesh/ellipsoidal/Geometry/test.vtk")

    print "Total_num_points = ", tpt

    Epiid = np.argmax(np.array([max(pts) for pts in bc_pts_range]))
    maxzrank = np.array([pts[2] for pts in bc_pts_range]).argsort()

    if (geometry == "BiV"):
        LVid = maxzrank[1]
        RVid = 3 - (LVid + Epiid)
        bc_pts_map = [4, 4, 4, 4]
        bc_pts_map[Epiid] = 1
        bc_pts_map[LVid] = 2
        bc_pts_map[RVid] = 3
        baseid = 3
    else:
        LVid = maxzrank[0]
        bc_pts_map = [4, 4, 4]
        bc_pts_map[Epiid] = 1
        bc_pts_map[LVid] = 2
        baseid = 2

    bc_pts_locator.append(baseptlocator)
    bc_pts.append(basesurf)

    dolfin_mesh = vtk_py.convertUGridToXMLMesh(ugrid)
    dolfin_facets = dolfin.FacetFunction('size_t', dolfin_mesh)
    dolfin_facets.set_all(0)

    for facet in dolfin.SubsetIterator(dolfin_facets, 0):
        for locator in range(0, nsurf + 1):
            cnt = 0
            for p in range(0, 3):
                v0 = dolfin.Vertex(dolfin_mesh, facet.entities(0)[p]).x(0)
                v1 = dolfin.Vertex(dolfin_mesh, facet.entities(0)[p]).x(1)
                v2 = dolfin.Vertex(dolfin_mesh, facet.entities(0)[p]).x(2)
                ptid = bc_pts_locator[locator].FindClosestPoint(v0, v1, v2)
                x0 = bc_pts[locator].GetPoints().GetPoint(ptid)
                dist = vtk.vtkMath.Distance2BetweenPoints([v0, v1, v2], x0)
                if (dist < 1e-5):
                    cnt = cnt + 1
            if (cnt == 3):
                dolfin_facets[facet] = bc_pts_map[locator]

    dolfin_edges = dolfin.EdgeFunction('size_t', dolfin_mesh)
    dolfin_edges.set_all(0)

    epilocator = Epiid
    lvendolocator = LVid

    for edge in dolfin.SubsetIterator(dolfin_edges, 0):
        cnt_epi = 0
        cnt_lvendo = 0
        for p in range(0, 2):
            v0 = dolfin.Vertex(dolfin_mesh, edge.entities(0)[p]).x(0)
            v1 = dolfin.Vertex(dolfin_mesh, edge.entities(0)[p]).x(1)
            v2 = dolfin.Vertex(dolfin_mesh, edge.entities(0)[p]).x(2)

            epiptid = bc_pts_locator[epilocator].FindClosestPoint(v0, v1, v2)
            epix0 = bc_pts[epilocator].GetPoints().GetPoint(epiptid)
            epidist = vtk.vtkMath.Distance2BetweenPoints([v0, v1, v2], epix0)

            topptid = bc_pts_locator[baseid].FindClosestPoint(v0, v1, v2)
            topx0 = bc_pts[baseid].GetPoints().GetPoint(topptid)
            topdist = vtk.vtkMath.Distance2BetweenPoints([v0, v1, v2], topx0)

            lvendoptid = bc_pts_locator[lvendolocator].FindClosestPoint(
                v0, v1, v2)
            lvendox0 = bc_pts[lvendolocator].GetPoints().GetPoint(lvendoptid)
            lvendodist = vtk.vtkMath.Distance2BetweenPoints([v0, v1, v2],
                                                            lvendox0)

            if (topdist < 1e-5 and epidist < 1e-5):
                cnt_epi = cnt_epi + 1

            if (topdist < 1e-5 and lvendodist < 1e-5):
                cnt_lvendo = cnt_lvendo + 1

            if (cnt_epi == 2):
                dolfin_edges[edge] = 1

            if (cnt_lvendo == 2):
                dolfin_edges[edge] = 2

    return dolfin_mesh, dolfin_facets, dolfin_edges
Exemplo n.º 19
0
def dolfin_to_carpfile(mesh, basename, markers=None, \
                       vert_fields=None, cell_fields=None):
    """
    NOT DEBUGGED:
    Write carp mesh and fields to file from dolfin data

    mesh : dolfin.Mesh
        The dolfin.mesh which should be written to file
    basename : str
        Basename of file which all data will be written to
    markers : dict (optional)
        A dict of name to markers of facet booundaries contained in the mesh
    vert_fields : dict (optional)
        A dict between named vertex field data and dolfin Functions
    cell_fields : dict (optional)
        A dict between named cell field data and dolfin Functions
    
    """
    import dolfin as d
    import numpy as np

    boundary = d.CompiledSubDomain("on_boundary")

    d.warning("This function is not tested...")

    boundary_facets = d.FacetFunction("size_t", mesh, 0)
    boundary.mark(boundary_facets, 1)
    num_boundary_facets = np.sum(boundary_facets.array() == 1)

    with open(basename + ".pts", "w") as f:
        f.write("{0}\n".format(mesh.num_vertices()))
        [f.write("{0:.10f} {1:.10f} {2:.10f}\n".format(*coord)) \
         for coord in mesh.coordinates()]

    with open(basename + ".elem", "w") as f:
        f.write("{0}\n".format(mesh.num_cells()))
        [f.write("Tt {0} {1} {2} {3} 0\n".format(*cell)) \
         for cell in mesh.cells()]

    with open(basename + ".surf", "w") as f:
        f.write("{0}\n".format(num_boundary_facets))
        [f.write("Tr {0} {1} {2}\n".format(*facet.entities(0))) \
         for facet in d.SubsetIterator(boundary_facets, 1)]

    # If generating mapping between vertices and boundaries
    if markers:

        # Get the facet markers
        facet_markers = mesh.domains().facet_domains(mesh)

        # Iterate over markers
        for boundary_name, marker in markers.items():

            vertices = set()
            for face in SubsetIterator(facet_markers, marker):
                vertices.update(face.entities(0))

            with open(basename + "_" + boundary_name + ".vtx", "w") as f:
                f.write("{0:d}\nintra \n".format(int(len(vertices))))
                [f.write("{0}\n".format(vert)) for vert in vertices]

        # Apex node...
        #with open(basename+"_apex.vtx", "w") as f:
        #    f.write("{0:d}\nintra \n".format(1))
        #    f.write("{0:d}\n".format((apex_point.array()==1).nonzero()[0][0]))

    # If outputing vertex fields
    if vert_fields:

        # Get dof mapping
        dofs_to_vert, vectordofs_to_vert, vectordofs_to_subvert = \
                      dofs_to_verts(mesh)

        # Iterate over the passed fields
        for field_name, func in vert_fields.items():
            values = func.vector().array()

            # If scalar field
            if mesh.num_vertices() == len(dofs):
                reordered_values = values[dofs_to_vert]

                # Write the field to file
                with open(basename + "_" + field_name + ".dat", "w") as f:
                    [
                        f.write("{0:.10f}\n".format(value))
                        for value in reordered_values
                    ]

            # If vector field
            elif mesh.num_vertices() == 3 * len(dofs):
                raise NotImplementedError
            else:
                raise ValueError("Field and mesh do not match: " + field_name)
Exemplo n.º 20
0
    def __init__(self, box, sponge, nx, ny):
        """
        Constructor
        
        INPUTS:
        - box = [x_min, x_max, y_min, y_max]: the bounding box of the computational domain
        - nx, ny: number of elements in the horizontal (axial) and vertical (transversal) direction
        """
        self.box = box
        self.mesh = dl.UnitSquareMesh(nx, ny)
        box_sponge = [box[0], box[1] + sponge[0], box[2], box[3] + sponge[1]]

        grade = GradingFunctionLin(coordinate=1, cut_point=[.6, .7], slope=6)
        remap = Remap(box=box_sponge)

        self.mesh.move(grade)
        self.mesh.move(remap)

        class InletBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[0] -
                                           box_sponge[0]) < dl.DOLFIN_EPS

        class SymmetryBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[1] -
                                           box_sponge[2]) < dl.DOLFIN_EPS

        class OutletBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[0] -
                                           box_sponge[1]) < dl.DOLFIN_EPS

        class TopBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                return on_boundary and abs(x[1] -
                                           box_sponge[3]) < dl.DOLFIN_EPS

        self.boundary_parts = dl.FacetFunction("size_t", self.mesh)
        self.boundary_parts.set_all(0)

        Gamma_inlet = InletBoundary()
        Gamma_inlet.mark(self.boundary_parts, self.INLET)
        Gamma_axis = SymmetryBoundary()
        Gamma_axis.mark(self.boundary_parts, self.AXIS)
        Gamma_outlet = OutletBoundary()
        Gamma_outlet.mark(self.boundary_parts, self.OUTLET)
        Gamma_top = TopBoundary()
        Gamma_top.mark(self.boundary_parts, self.TOP)

        self.ds = dl.Measure("ds")[self.boundary_parts]

        class PhysicalDomain(dl.SubDomain):
            def inside(self, x, on_boundary):
                return x[0] < box[1] + dl.DOLFIN_EPS and x[
                    1] < box[3] + dl.DOLFIN_EPS

        self.domain_parts = dl.CellFunction("size_t", self.mesh)
        self.domain_parts.set_all(self.SPONGE)

        P_Domain = PhysicalDomain()
        P_Domain.mark(self.domain_parts, self.PHYSICAL)

        self.dx = dl.Measure("dx")[self.domain_parts]

        self.xfun, self.yfun = dl.MeshCoordinates(self.mesh)
        self.x_start = dl.Constant(box[1] + .5 * sponge[0])
        self.x_width = dl.Constant(.5 * sponge[0])
        self.y_start = dl.Constant(box[3] + .5 * sponge[1])
        self.y_width = dl.Constant(.5 * sponge[1])

        self.s_x = dl.Constant(1.) + (
            (dl.Constant(100) / self.x_width) *
            dl.max_value(self.xfun - self.x_start, dl.Constant(0.)))**2
        self.s_y = dl.Constant(1.) + (
            (dl.Constant(100) / self.y_width) *
            dl.max_value(self.yfun - self.y_start, dl.Constant(0.)))**2
        self.sponge_fun = self.s_x * self.s_y
Exemplo n.º 21
0
    # Modify mesh to use clustered grid
    mesh.coordinates()[:] = np.reshape(x, (n, 1))

    # Set up function space
    V = df.FunctionSpace(mesh, "CG", 1)
    u = df.TrialFunction(V)
    v = df.TestFunction(V)

    ux = u.dx(0)
    vx = v.dx(0)

    # Set up homogeneous Dirichlet boundary conditions
    left = BoundaryPoint(0)
    right = BoundaryPoint(1)

    boundaries = df.FacetFunction("size_t", mesh)
    left.mark(boundaries, 0)
    right.mark(boundaries, 1)

    bc = [
        df.DirichletBC(V, df.Constant(0.0), left),
        df.DirichletBC(V, df.Constant(0.0), right)
    ]

    # Variable coefficient
    p = df.Expression('1.001+cos(4*pi*x[0])')

    # Forms
    a = (vx * p * ux) * df.dx
    L = v * df.dx
Exemplo n.º 22
0
# of the domain


class Left(dolfin.SubDomain):
    def inside(self, x, on_boundary):
        return on_boundary and dolfin.near(x[0], 0.0)


# Initialize sub-domain instances
left = Left()

# Define mesh
mesh = dolfin.UnitSquareMesh(64, 64)

# Initialize mesh function for boundary domains
boundaries = dolfin.FacetFunction("size_t", mesh)
boundaries.set_all(0)
left.mark(boundaries, 1)

# Define function space and basis functions
V = dolfin.FunctionSpace(mesh, "CG", 2)
u = dolfin.TrialFunction(V)
v = dolfin.TestFunction(V)

# Define new measures associated with the interior domains and
# exterior boundaries
ds = dolfin.Measure('ds', domain=mesh, subdomain_data=boundaries)

aform = u * v * ds(1)
aform = dolfin.assemble(aform)
Exemplo n.º 23
0
def get_conv_diff_ls(n_points=25):
    # mesh and function space
    mesh = dolfin.RectangleMesh(-1, -1, 1, 1, n_points, n_points, 'crossed')
    V = dolfin.FunctionSpace(mesh, 'Lagrange', 1)

    wind = dolfin.Expression(('2*x[1]*(1-x[0]*x[0])', '-2*x[0]*(1-x[1]*x[1])'))

    # right hand side
    f = dolfin.Constant(0.)

    # diffusivity
    epsilon = 1. / 200

    # convection field
    delta = Stabilization(mesh, wind, epsilon)

    # define boundary conditions
    class Boundary(dolfin.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary

    class BoundaryRight(dolfin.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary and near(x[0], 1.)

    boundaries = dolfin.FacetFunction('size_t', mesh)
    boundary = Boundary()
    boundary.mark(boundaries, 1)
    boundary2 = BoundaryRight()
    boundary2.mark(boundaries, 2)
    boundary
    bcs = [
        dolfin.DirichletBC(V, dolfin.Constant(0.), boundaries, 1),
        dolfin.DirichletBC(V, dolfin.Constant(1.), boundaries, 2)
    ]

    # variational formulation
    u = dolfin.TrialFunction(V)
    v = dolfin.TestFunction(V)

    def get_conv_diff(u, v, epsilon, wind, stabilize=True):
        a = (epsilon * inner(nabla_grad(u), nabla_grad(v)) * dx +
             inner(nabla_grad(u), wind) * v * dx)
        L = f * v * dx
        if stabilize:
            a += delta * inner(wind, nabla_grad(u)) * inner(
                wind, nabla_grad(v)) * dx
            L += delta * f * inner(wind, nabla_grad(v)) * dx
        return a, L

    a, L = get_conv_diff(u, v, epsilon, wind)

    A = dolfin.assemble(a)
    b = dolfin.assemble(L)
    u0 = dolfin.Function(V).vector()
    u0.zero()

    [bc.apply(A, b) for bc in bcs]
    [bc.apply(u0) for bc in bcs]

    import scipy.sparse
    A_mat = scipy.sparse.csc_matrix(mat_dolfin2sparse(A))

    return A_mat, b.array(), u0.array()
Exemplo n.º 24
0
def get_stokessysmats(V,
                      Q,
                      nu=None,
                      bccontrol=False,
                      cbclist=None,
                      cbshapefuns=None):
    """ Assembles the system matrices for Stokes equation

    in mixed FEM formulation, namely

    .. math::

        \\begin{bmatrix} A & -J' \\\\ J & 0 \\end{bmatrix}\
        \\colon V \\times Q \\to V' \\times Q'

    as the discrete representation of

    .. math::

        \\begin{bmatrix} -\\Delta & \\text{grad} \\\\ \
        \\text{div} & 0 \\end{bmatrix}

    plus the velocity and pressure mass matrices

    for a given trial and test space W = V * Q
    not considering boundary conditions.

    Parameters
    ----------
    V : dolfin.VectorFunctionSpace
        Fenics VectorFunctionSpace for the velocity
    Q : dolfin.FunctionSpace
        Fenics FunctionSpace for the pressure
    nu : float, optional
        viscosity parameter - defaults to 1
    bccontrol : boolean, optional
        whether boundary control (via penalized Robin conditions)
        is applied, defaults to `False`
    cbclist : list, optional
        list of dolfin's Subdomain classes describing the control boundaries
    cbshapefuns : list, optional
        list of spatial shape functions of the control boundaries

    Returns
    -------
    stokesmats, dictionary
        a dictionary with the following keys:
            * ``M``: the mass matrix of the velocity space,
            * ``A``: the stiffness matrix \
                :math:`\\nu \\int_\\Omega (\\nabla \\phi_i, \\nabla \\phi_j)`
            * ``JT``: the gradient matrix,
            * ``J``: the divergence matrix, and
            * ``MP``: the mass matrix of the pressure space
            * ``Apbc``: (N, N) sparse matrix, \
                the contribution of the Robin conditions to `A` \
                :math:`\\nu \\int_\\Gamma (\\phi_i, \\phi_j)`
            * ``Bpbc``: (N, k) sparse matrix, the input matrix of the Robin \
                conditions :math:`\\nu \\int_\\Gamma (\\phi_i, g_k)`, \
                where :math:`g_k` is the shape function associated with the \
                j-th control boundary segment

    """

    u = dolfin.TrialFunction(V)
    p = dolfin.TrialFunction(Q)
    v = dolfin.TestFunction(V)
    q = dolfin.TestFunction(Q)

    if nu is None:
        nu = 1
        print('No viscosity provided -- we set `nu=1`')

    ma = inner(u, v) * dx
    mp = inner(p, q) * dx
    aa = nu * inner(grad(u), grad(v)) * dx
    grada = div(v) * p * dx
    diva = q * div(u) * dx

    # Assemble system
    M = dolfin.assemble(ma)
    A = dolfin.assemble(aa)
    Grad = dolfin.assemble(grada)
    Div = dolfin.assemble(diva)
    MP = dolfin.assemble(mp)

    # Convert DOLFIN representation to scipy arrays
    Ma = mat_dolfin2sparse(M)
    MPa = mat_dolfin2sparse(MP)
    Aa = mat_dolfin2sparse(A)
    JTa = mat_dolfin2sparse(Grad)
    Ja = mat_dolfin2sparse(Div)

    stokesmats = {'M': Ma, 'A': Aa, 'JT': JTa, 'J': Ja, 'MP': MPa}

    if bccontrol:
        amatrobl, bmatrobl = [], []
        mesh = V.mesh()
        for bc, bcfun in zip(cbclist, cbshapefuns):
            # get an instance of the subdomain class
            Gamma = bc()

            # bparts = dolfin.MeshFunction('size_t', mesh,
            #                              mesh.topology().dim() - 1)

            boundaries = dolfin.FacetFunction("size_t", mesh)
            boundaries.set_all(0)
            Gamma.mark(boundaries, 1)

            ds = dolfin.Measure('ds', domain=mesh, subdomain_data=boundaries)

            # Gamma.mark(bparts, 0)

            # Robin boundary form
            arob = dolfin.inner(u, v) * ds(1)  # , subdomain_data=bparts)
            brob = dolfin.inner(v, bcfun) * ds(1)  # , subdomain_data=bparts)

            amatrob = dolfin.assemble(arob)  # , exterior_facet_domains=bparts)
            bmatrob = dolfin.assemble(brob)  # , exterior_facet_domains=bparts)

            amatrob = mat_dolfin2sparse(amatrob)
            amatrob.eliminate_zeros()
            amatrobl.append(amatrob)
            bmatrobl.append(bmatrob.array().reshape((V.dim(), 1)))  # [ININDS]

        amatrob = amatrobl[0]
        for amatadd in amatrobl[1:]:
            amatrob = amatrob + amatadd
        bmatrob = np.hstack(bmatrobl)

        stokesmats.update({'amatrob': amatrob, 'bmatrob': bmatrob})

    return stokesmats
Exemplo n.º 25
0
# if dlversion() <= (1, 6, 0):
#     pde.solver = dl.PETScKrylovSolver("cg", amg_method())
#     pde.solver_fwd_inc = dl.PETScKrylovSolver("cg", amg_method())
#     pde.solver_adj_inc = dl.PETScKrylovSolver("cg", amg_method())
# else:
#     pde.solver = dl.PETScKrylovSolver(mesh.mpi_comm(), "cg", amg_method())
#     pde.solver_fwd_inc = dl.PETScKrylovSolver(mesh.mpi_comm(), "cg", amg_method())
#     pde.solver_adj_inc = dl.PETScKrylovSolver(mesh.mpi_comm(), "cg", amg_method())
# pde.solver.parameters["relative_tolerance"] = 1e-15
# pde.solver.parameters["absolute_tolerance"] = 1e-20
# pde.solver_fwd_inc.parameters = pde.solver.parameters
# pde.solver_adj_inc.parameters = pde.solver.parameters

# define the QOI
GC = GammaBottom()
marker = dl.FacetFunction("size_t", mesh)
marker.set_all(0)
GC.mark(marker, 1)
dss = dl.Measure("ds", subdomain_data=marker)
qoi = FluxQOI(Vh, dss(1))

# qoi = QoI(Vh)

# define the misfit
n1d = 15
ntargets = n1d**2
targets = np.zeros((ntargets, 2))
x1d = np.array(range(n1d)) / float(n1d + 1) + 1 / float(n1d + 1)
for i in range(n1d):
    for j in range(n1d):
        targets[i * n1d + j, 0] = x1d[i]
Exemplo n.º 26
0
    def __init__(self, model_name="mincde"):
        pyurdme.URDMEModel.__init__(self, model_name)

        # Species
        MinD_m = pyurdme.Species(name="MinD_m",
                                 diffusion_constant=1e-14,
                                 dimension=2)
        MinD_c_atp = pyurdme.Species(name="MinD_c_atp",
                                     diffusion_constant=2.5e-12,
                                     dimension=3)
        MinD_c_adp = pyurdme.Species(name="MinD_c_adp",
                                     diffusion_constant=2.5e-12,
                                     dimension=3)
        MinD_e = pyurdme.Species(name="MinD_e",
                                 diffusion_constant=2.5e-12,
                                 dimension=3)
        MinDE = pyurdme.Species(name="MinDE",
                                diffusion_constant=1e-14,
                                dimension=2)

        self.add_species([MinD_m, MinD_c_atp, MinD_c_adp, MinD_e, MinDE])

        # Make sure that we have the correct path to the mesh file even if we are not executing from the basedir.
        basedir = os.path.dirname(os.path.abspath(__file__))
        self.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(basedir +
                                                       "/mesh/coli.xml")

        interior = dolfin.CellFunction("size_t", self.mesh)
        interior.set_all(1)
        boundary = dolfin.FacetFunction("size_t", self.mesh)
        boundary.set_all(0)

        # Mark the boundary points
        membrane = Membrane()
        membrane.mark(boundary, 2)

        self.add_subdomain(interior)
        self.add_subdomain(boundary)

        # Average mesh size to feed into the propensity functions
        h = self.mesh.get_mesh_size()
        self.add_data_function(MeshSize(self.mesh))

        # Parameters
        NA = pyurdme.Parameter(name="NA", expression=6.022e23)
        sigma_d = pyurdme.Parameter(name="sigma_d", expression=2.5e-8)
        sigma_dD = pyurdme.Parameter(name="sigma_dD", expression=0.0016e-18)
        sigma_e = pyurdme.Parameter(name="sigma_e", expression=0.093e-18)
        sigma_de = pyurdme.Parameter(name="sigma_de", expression=0.7)
        sigma_dt = pyurdme.Parameter(name="sigma_dt", expression=1.0)

        self.add_parameter(
            [NA, sigma_d, sigma_dD, sigma_e, sigma_de, sigma_dt])

        # List of Physical domain markers that match those in the  Gmsh .geo file.
        interior = [1]
        boundary = [2]

        # Reactions
        R1 = pyurdme.Reaction(
            name="R1",
            reactants={MinD_c_atp: 1},
            products={MinD_m: 1},
            propensity_function="MinD_c_atp*sigma_d/MeshSize",
            restrict_to=boundary)
        R2 = pyurdme.Reaction(name="R2",
                              reactants={
                                  MinD_c_atp: 1,
                                  MinD_m: 1
                              },
                              products={MinD_m: 2},
                              massaction=True,
                              rate=sigma_dD)
        R3 = pyurdme.Reaction(name="R3",
                              reactants={
                                  MinD_m: 1,
                                  MinD_e: 1
                              },
                              products={MinDE: 1},
                              massaction=True,
                              rate=sigma_e)
        R4 = pyurdme.Reaction(name="R4",
                              reactants={MinDE: 1},
                              products={
                                  MinD_c_adp: 1,
                                  MinD_e: 1
                              },
                              massaction=True,
                              rate=sigma_de)
        R5 = pyurdme.Reaction(name="R5",
                              reactants={MinD_c_adp: 1},
                              products={MinD_c_atp: 1},
                              massaction=True,
                              rate=sigma_dt)
        R6 = pyurdme.Reaction(name="R6",
                              reactants={
                                  MinDE: 1,
                                  MinD_c_atp: 1
                              },
                              products={
                                  MinD_m: 1,
                                  MinDE: 1
                              },
                              massaction=True,
                              rate=sigma_dD)

        self.add_reaction([R1, R2, R3, R4, R5, R6])

        # Restrict to boundary
        self.restrict(MinD_m, boundary)
        self.restrict(MinDE, boundary)

        # Distribute molecules over the mesh according to their initial values
        self.set_initial_condition_scatter({MinD_c_adp: 4500})
        self.set_initial_condition_scatter({MinD_e: 1575})

        self.timespan(range(500))
Exemplo n.º 27
0
    def __init__(self, mesh, Vh, t_init, t_final, t_1, dt, wind_velocity,
                 gls_stab, Prior):
        self.mesh = mesh
        self.Vh = Vh
        self.t_init = t_init
        self.t_final = t_final
        self.t_1 = t_1
        self.dt = dt
        self.sim_times = np.arange(self.t_init, self.t_final + .5 * self.dt,
                                   self.dt)

        u = dl.TrialFunction(Vh[STATE])
        v = dl.TestFunction(Vh[STATE])

        kappa = dl.Constant(.001)
        dt_expr = dl.Constant(self.dt)

        r_trial = u + dt_expr * (-dl.div(kappa * dl.nabla_grad(u)) +
                                 dl.inner(wind_velocity, dl.nabla_grad(u)))
        r_test = v + dt_expr * (-dl.div(kappa * dl.nabla_grad(v)) +
                                dl.inner(wind_velocity, dl.nabla_grad(v)))

        h = dl.CellSize(mesh)
        vnorm = dl.sqrt(dl.inner(wind_velocity, wind_velocity))
        if gls_stab:
            tau = dl.Min((h * h) / (dl.Constant(2.) * kappa), h / vnorm)
        else:
            tau = dl.Constant(0.)

        self.M = dl.assemble(dl.inner(u, v) * dl.dx)
        self.M_stab = dl.assemble(dl.inner(u, v + tau * r_test) * dl.dx)
        self.Mt_stab = dl.assemble(dl.inner(u + tau * r_trial, v) * dl.dx)
        Nvarf = (dl.inner(kappa * dl.nabla_grad(u), dl.nabla_grad(v)) +
                 dl.inner(wind_velocity, dl.nabla_grad(u)) * v) * dl.dx
        Ntvarf = (dl.inner(kappa * dl.nabla_grad(v), dl.nabla_grad(u)) +
                  dl.inner(wind_velocity, dl.nabla_grad(v)) * u) * dl.dx
        self.N = dl.assemble(Nvarf)
        self.Nt = dl.assemble(Ntvarf)
        stab = dl.assemble(tau * dl.inner(r_trial, r_test) * dl.dx)
        self.L = self.M + dt * self.N + stab
        self.Lt = self.M + dt * self.Nt + stab

        boundaries = dl.FacetFunction("size_t", mesh)
        boundaries.set_all(0)

        class InsideBoundary(dl.SubDomain):
            def inside(self, x, on_boundary):
                x_in = x[0] > dl.DOLFIN_EPS and x[0] < 1 - dl.DOLFIN_EPS
                y_in = x[1] > dl.DOLFIN_EPS and x[1] < 1 - dl.DOLFIN_EPS
                return on_boundary and x_in and y_in

        Gamma_M = InsideBoundary()
        Gamma_M.mark(boundaries, 1)
        ds_marked = dl.Measure("ds")[boundaries]

        self.Q = dl.assemble(self.dt * dl.inner(u, v) * ds_marked(1))

        self.Prior = Prior

        self.solver = dl.PETScKrylovSolver("gmres", "ilu")
        self.solver.set_operator(self.L)

        self.solvert = dl.PETScKrylovSolver("gmres", "ilu")
        self.solvert.set_operator(self.Lt)

        self.ud = self.generate_vector(STATE)
        self.noise_variance = 0
Exemplo n.º 28
0
def get_conv_diff_ls(mesh,
                     V,
                     wind,
                     right_boundary,
                     f=None,
                     timed=False,
                     return_mat=False):
    # right hand side
    if f is None:
        f = dolfin.Constant(0.)

    # diffusivity
    epsilon = 1. / 200

    # convection field
    delta = Stabilization(mesh, wind, epsilon)

    # define boundary conditions
    class Boundary(dolfin.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary

    class BoundaryRight(dolfin.SubDomain):
        def inside(self, x, on_boundary):
            return on_boundary and near(x[0], 1.)

    boundaries = dolfin.FacetFunction('size_t', mesh)
    boundaries.set_all(0)
    boundary = Boundary()
    boundary.mark(boundaries, 1)
    boundary2 = BoundaryRight()
    boundary2.mark(boundaries, 2)
    boundary
    bcs = [
        dolfin.DirichletBC(V, dolfin.Constant(0.), boundaries, 1),
        dolfin.DirichletBC(V, right_boundary, boundaries, 2)
    ]

    # variational formulation
    u = dolfin.TrialFunction(V)
    v = dolfin.TestFunction(V)

    def get_conv_diff(u, v, epsilon, wind, stabilize=True):
        a = (epsilon * inner(nabla_grad(u), nabla_grad(v)) * dx +
             inner(nabla_grad(u), wind) * v * dx)
        L = f * v * dx
        if stabilize:
            a += delta * inner(wind, nabla_grad(u)) * inner(
                wind, nabla_grad(v)) * dx
            L += delta * f * inner(wind, nabla_grad(v)) * dx
        return a, L

    a, L = get_conv_diff(u, v, epsilon, wind)

    A = dolfin.assemble(a)
    b = dolfin.assemble(L)
    u0 = dolfin.Function(V).vector()
    u0.zero()

    [bc.apply(A, b) for bc in bcs]
    [bc.apply(u0) for bc in bcs]

    import scipy.sparse
    A_mat = scipy.sparse.csc_matrix(mat_dolfin2sparse(A))

    return A_mat, b.array(), u0.array()