示例#1
0
    def assign(self, *args, **kwargs):
        annotate = annotate_tape(kwargs)
        outputs = Enlist(args[0])
        inputs = Enlist(args[1])

        if annotate:
            for i, o in enumerate(outputs):
                if not isinstance(o, OverloadedType):
                    outputs[i] = create_overloaded_object(o)

            for j, i in enumerate(outputs):
                if not isinstance(i, OverloadedType):
                    inputs[j] = create_overloaded_object(i)

            block = FunctionAssignerBlock(self, inputs)
            tape = get_working_tape()
            tape.add_block(block)

        with stop_annotating():
            ret = backend.FunctionAssigner.assign(self, outputs.delist(), inputs.delist(), **kwargs)

        if annotate:
            for output in outputs:
                block.add_output(output.block_variable)
        return ret
示例#2
0
    def wrapper(*args, **kwargs):
        """When a form is assembled, the information about its nonlinear dependencies is lost,
        and it is no longer easy to manipulate. Therefore, we decorate :func:`.assemble`
        to *attach the form to the assembled object*. This lets the automatic annotation work,
        even when the user calls the lower-level :py:data:`solve(A, x, b)`.
        """
        ad_block_tag = kwargs.pop("ad_block_tag", None)
        annotate = annotate_tape(kwargs)
        with stop_annotating():
            output = assemble(*args, **kwargs)

        form = args[0]
        if isinstance(output, numbers.Complex):
            if not annotate:
                return output

            if not isinstance(output, float):
                raise NotImplementedError(
                    "Taping for complex-valued 0-forms not yet done!")
            output = create_overloaded_object(output)
            block = AssembleBlock(form, ad_block_tag=ad_block_tag)

            tape = get_working_tape()
            tape.add_block(block)

            block.add_output(output.block_variable)
        else:
            # Assembled a vector or matrix
            output.form = form

        return output
示例#3
0
    def _ad_convert_type(self, value, options=None):
        options = {} if options is None else options
        riesz_representation = options.get("riesz_representation", "l2")

        if riesz_representation == "l2":
            return create_overloaded_object(
                compat.function_from_vector(self.function_space(),
                                            value,
                                            cls=backend.Function))
        elif riesz_representation == "L2":
            ret = compat.create_function(self.function_space())
            u = backend.TrialFunction(self.function_space())
            v = backend.TestFunction(self.function_space())
            M = backend.assemble(backend.inner(u, v) * backend.dx)
            compat.linalg_solve(M, ret.vector(), value)
            return ret
        elif riesz_representation == "H1":
            ret = compat.create_function(self.function_space())
            u = backend.TrialFunction(self.function_space())
            v = backend.TestFunction(self.function_space())
            M = backend.assemble(
                backend.inner(u, v) * backend.dx +
                backend.inner(backend.grad(u), backend.grad(v)) * backend.dx)
            compat.linalg_solve(M, ret.vector(), value)
            return ret
        elif callable(riesz_representation):
            return riesz_representation(value)
        else:
            raise NotImplementedError("Unknown Riesz representation %s" %
                                      riesz_representation)
示例#4
0
 def sub(self, i, deepcopy=False, **kwargs):
     from .function_assigner import FunctionAssigner, FunctionAssignerBlock
     annotate = annotate_tape(kwargs)
     if deepcopy:
         ret = create_overloaded_object(
             backend.Function.sub(self, i, deepcopy, **kwargs))
         if annotate:
             fa = FunctionAssigner(ret.function_space(),
                                   self.function_space())
             block = FunctionAssignerBlock(fa, Enlist(self))
             tape = get_working_tape()
             tape.add_block(block)
             block.add_output(ret.block_variable)
     else:
         extra_kwargs = {}
         if annotate:
             extra_kwargs = {
                 "block_class": FunctionSplitBlock,
                 "_ad_floating_active": True,
                 "_ad_args": [self, i],
                 "_ad_output_args": [i],
                 "output_block_class": FunctionMergeBlock,
                 "_ad_outputs": [self],
             }
         ret = compat.create_function(self, i, **extra_kwargs)
     return ret
示例#5
0
def interpolate(*args, **kwargs):
    """Interpolation is overloaded to ensure that the returned Function object is overloaded.
    We are not able to annotate the interpolation call at the moment.

    """
    output = backend.interpolate(*args, **kwargs)
    return create_overloaded_object(output)
示例#6
0
def get_mesh(Ln,Lr,Ll,resolution,delta,theta):
	cosdt = cos(atan2(delta*theta,1.))
	sindt = sin(atan2(delta*theta,1.))

	# input edges
	top_left = edgeinput([Point(0.,1.0),Point(-Ll, 1.0)])
	top_mid = edgeinput([Point(Ln,1-0.5*theta),Point(0., 1.)])
	top_right = edgeinput([Point(Ln+Lr,1-0.5*theta),Point(Ln, 1-0.5*theta)])
	right_top = edgeinput([Point(Ln+Lr,0.5*theta),Point(Ln+Lr, 1.-0.5*theta)])
	right_bottom = edgeinput([Point(Ln+Lr,-0.5*theta),Point(Ln+Lr, 0.5*theta)])
	mid_right = edgeinput([Point(Ln,0.5*theta ),Point(Ln+Lr,0.5*theta )])
	mid_left = edgeinput([Point(0.,0.),Point(0., 1.)])
	mid_bottom = edgeinput([Point(0.,0.),Point(Ln, 0.5*theta)])
	left = edgeinput([Point(-Ll,1.),Point(-Ll, 0.)])
	bottom_left = edgeinput([Point(-Ll,0.),Point(0., 0.)])
	bottom_mid = edgeinput([Point(0.,0.),Point(Ln,-0.5*theta )])
	bottom_right = edgeinput([Point(Ln,-0.5*theta ),Point(Ln+Lr,-0.5*theta )])

	# define a vector with the edges
	edges = [top_left,top_mid,top_right,right_top,right_bottom,mid_right,mid_left,mid_bottom,left,bottom_left,bottom_mid,bottom_right]
	edges_number = len(edges)

	# input domain
	domain_complete = subdomaininput([top_left,left,bottom_left, bottom_mid, bottom_right, right_bottom, right_top, top_right, top_mid],[0,0,0,0,0,0,0,0,0],0)

	# input subdomains
	domain_left = subdomaininput([top_left,left,bottom_left,mid_left],[0,0,0,0],0)
	domain_top = subdomaininput([mid_bottom,mid_right,right_top,top_right,top_mid,mid_left],[0,0,0,0,0,1],0)
	domain_bottom = subdomaininput([bottom_mid,bottom_right,right_bottom,mid_right,mid_bottom],[0,0,0,1,1],0)

	# define vector of subdomains
	subdomains = [domain_left,domain_top,domain_bottom]
	subdomain_number = len(subdomains)

	# defining the domain, and the subdomains
	domain = Polygon(domain_complete.get_polygon())
	for i in range(0, subdomain_number):
		domain.set_subdomain (i+1, Polygon((subdomains[i]).get_polygon()))

	# generat the mesh
	mesh = generate_mesh (domain, resolution)
	mesh = create_overloaded_object(mesh)
	print ("Anzahl Knoten:", mesh.num_vertices())

	# defining coefficients on subdomains
	X = FunctionSpace (mesh, "DG", 0)
	dm = X.dofmap()
	sudom = MeshFunction ('size_t', mesh, 2, mesh.domains())
	sudom_arr = numpy.asarray (sudom.array(), dtype=numpy.int)
	for cell in cells (mesh): sudom_arr [dm.cell_dofs (cell.index())] = sudom [cell]

	def sudom_fct (sudom_arr, vals, fctspace):
		f = Function (fctspace)
		f.vector()[:] = numpy.choose (sudom_arr, vals)
		return f

	chi_a = sudom_fct (sudom_arr, [0,1,0,1], X)
	chi_b = sudom_fct (sudom_arr, [0,0,1,0], X)
	chi_test = sudom_fct (sudom_arr, [0,1,2,1], X)
	return mesh, edges, edges_number, chi_a, chi_b, chi_test,mesh.num_vertices()
示例#7
0
    def wrapper(*args, **kwargs):
        """The project call performs an equation solve, and so it too must be annotated so that the
        adjoint and tangent linear models may be constructed automatically by pyadjoint.

        To disable the annotation of this function, just pass :py:data:`annotate=False`. This is useful in
        cases where the solve is known to be irrelevant or diagnostic for the purposes of the adjoint
        computation (such as projecting fields to other function spaces for the purposes of
        visualisation)."""

        annotate = annotate_tape(kwargs)
        with stop_annotating():
            output = project(*args, **kwargs)
        output = create_overloaded_object(output)

        if annotate:
            bcs = kwargs.pop("bcs", [])
            sb_kwargs = ProjectBlock.pop_kwargs(kwargs)
            block = ProjectBlock(args[0], args[1], output, bcs, **sb_kwargs)

            tape = get_working_tape()
            tape.add_block(block)

            block.add_output(output.block_variable)

        return output
示例#8
0
def refine(*args, **kwargs):
    """ Refine is overloaded to ensure that the returned mesh is overloaded.
    """
    with stop_annotating():
        output = backend.refine(*args, **kwargs)
    overloaded = create_overloaded_object(output)
    return overloaded
示例#9
0
def assemble(*args, **kwargs):
    """When a form is assembled, the information about its nonlinear dependencies is lost,
    and it is no longer easy to manipulate. Therefore, fenics_adjoint overloads the :py:func:`dolfin.assemble`
    function to *attach the form to the assembled object*. This lets the automatic annotation work,
    even when the user calls the lower-level :py:data:`solve(A, x, b)`.
    """
    annotate = annotate_tape(kwargs)
    with stop_annotating():
        output = backend.assemble(*args, **kwargs)

    form = args[0]
    if isinstance(output, float):
        output = create_overloaded_object(output)

        if annotate:
            block = AssembleBlock(form)

            tape = get_working_tape()
            tape.add_block(block)

            block.add_output(output.block_variable)
    else:
        # Assembled a vector or matrix
        output.form = form

    return output
示例#10
0
 def split(self, deepcopy=False, **kwargs):
     from .function_assigner import FunctionAssigner, FunctionAssignerBlock
     ad_block_tag = kwargs.pop("ad_block_tag", None)
     annotate = annotate_tape(kwargs)
     num_sub_spaces = backend.Function.function_space(self).num_sub_spaces()
     if not annotate:
         if deepcopy:
             ret = tuple(
                 create_overloaded_object(
                     backend.Function.sub(self, i, deepcopy, **kwargs))
                 for i in range(num_sub_spaces))
         else:
             ret = tuple(
                 compat.create_function(self, i)
                 for i in range(num_sub_spaces))
     elif deepcopy:
         ret = []
         fs = []
         for i in range(num_sub_spaces):
             f = create_overloaded_object(
                 backend.Function.sub(self, i, deepcopy, **kwargs))
             fs.append(f.function_space())
             ret.append(f)
         fa = FunctionAssigner(fs, self.function_space())
         block = FunctionAssignerBlock(fa,
                                       Enlist(self),
                                       ad_block_tag=ad_block_tag)
         tape = get_working_tape()
         tape.add_block(block)
         for output in ret:
             block.add_output(output.block_variable)
         ret = tuple(ret)
     else:
         ret = tuple(
             compat.create_function(self,
                                    i,
                                    block_class=FunctionSplitBlock,
                                    _ad_floating_active=True,
                                    _ad_args=[self, i],
                                    _ad_output_args=[i],
                                    output_block_class=FunctionMergeBlock,
                                    _ad_outputs=[self])
             for i in range(num_sub_spaces))
     return ret
示例#11
0
    def __getitem__(self, item):
        annotate = annotate_tape()
        if annotate:
            block = NumpyArraySliceBlock(self, item)
            tape = get_working_tape()
            tape.add_block(block)

        with stop_annotating():
            out = numpy.ndarray.__getitem__(self, item)

        if annotate:
            out = create_overloaded_object(out)
            block.add_output(out.create_block_variable())
        return out
示例#12
0
    def copy(self, *args, **kwargs):
        annotate = annotate_tape(kwargs)
        c = backend.Function.copy(self, *args, **kwargs)
        func = create_overloaded_object(c)

        if annotate:
            if kwargs.pop("deepcopy", False):
                block = FunctionAssignBlock(func, self)
                tape = get_working_tape()
                tape.add_block(block)
                block.add_output(func.create_block_variable())
            else:
                # TODO: Implement. Here we would need to use floating types.
                pass

        return func
示例#13
0
    def project(self, b, *args, **kwargs):
        annotate = annotate_tape(kwargs)
        with stop_annotating():
            output = super(Function, self).project(b, *args, **kwargs)
        output = create_overloaded_object(output)

        if annotate:
            bcs = kwargs.pop("bcs", [])
            block = ProjectBlock(b, self.function_space(), output, bcs)

            tape = get_working_tape()
            tape.add_block(block)

            block.add_output(output.create_block_variable())

        return output
示例#14
0
def transfer_to_boundary(*args, **kwargs):
    """
    Transfers values from a CG1 function on a mesh to its corresponding
    BoundaryMesh.
    """
    annotate = annotate_tape(kwargs)
    with stop_annotating():
        output = vector_mesh_to_boundary(*args)
    output = create_overloaded_object(output)

    if annotate:
        block = VolumeTransferBlock(args[0], args[1])
        tape = get_working_tape()
        tape.add_block(block)
        block.add_output(output.block_variable)

    return output
示例#15
0
    def assign(self, *args, **kwargs):
        annotate_tape = kwargs.pop("annotate_tape", True)
        if annotate_tape:
            other = args[0]
            if not isinstance(other, OverloadedType):
                other = create_overloaded_object(other)

            block = AssignBlock(self, other)
            tape = get_working_tape()
            tape.add_block(block)

        ret = backend.Constant.assign(self, *args, **kwargs)

        if annotate_tape:
            block.add_output(self.create_block_variable())

        return ret
示例#16
0
        def wrapper(self, *args, **kwargs):
            annotate = annotate_tape(kwargs)
            if annotate:
                other = args[0]
                if not isinstance(other, OverloadedType):
                    other = create_overloaded_object(other)

                block = ConstantAssignBlock(other)
                tape = get_working_tape()
                tape.add_block(block)

            ret = assign(self, *args, **kwargs)

            if annotate:
                block.add_output(self.create_block_variable())

            return ret
示例#17
0
def transfer_from_boundary(*args, **kwargs):
    """
    Transfers values from a CG1 function on the BoundaryMesh to its
    original mesh
    """
    annotate = annotate_tape(kwargs)
    with stop_annotating():
        output = vector_boundary_to_mesh(*args)
    output = create_overloaded_object(output)

    if annotate:
        block = SurfaceTransferBlock(args[0], args[1])
        tape = get_working_tape()
        tape.add_block(block)
        block.add_output(output.block_variable)

    return output
示例#18
0
    def __call__(self, *args, **kwargs):
        annotate = False
        if len(args) == 1 and isinstance(args[0], (numpy.ndarray, )):
            annotate = annotate_tape(kwargs)

        if annotate:
            block = FunctionEvalBlock(self, args[0])
            tape = get_working_tape()
            tape.add_block(block)

        with stop_annotating():
            out = backend.Function.__call__(self, *args, **kwargs)

        if annotate:
            out = create_overloaded_object(out)
            block.add_output(out.create_block_variable())

        return out
示例#19
0
def BaseHeight(x, y, ground, **kwargs):
    '''This is the adjoint version of RelativeHeight. It's goal is to 
    calculate the height of the turbine's base. At the same time, it creates
    a block that helps propagate the adjoint information.'''
    annotate = annotate_tape(kwargs)
    with stop_annotating():
        output = backend_BaseHeight(x, y, ground)
    output = create_overloaded_object(output)

    if annotate:
        block = BaseHeightBlock(x, y, ground, output)

        tape = get_working_tape()
        tape.add_block(block)

        block.add_output(output.block_variable)

    return output
示例#20
0
    def assign(self, *args, **kwargs):
        ad_block_tag = kwargs.pop("ad_block_tag", None)
        annotate = annotate_tape(kwargs)
        if annotate:
            other = args[0]
            if not isinstance(other, OverloadedType):
                other = create_overloaded_object(other)

            block = ConstantAssignBlock(other, ad_block_tag=ad_block_tag)
            tape = get_working_tape()
            tape.add_block(block)

        with stop_annotating():
            ret = backend.Constant.assign(self, *args, **kwargs)

        if annotate:
            block.add_output(self.create_block_variable())

        return ret
示例#21
0
    def assign(self, other, *args, **kwargs):
        """To disable the annotation, just pass :py:data:`annotate=False` to this routine, and it acts exactly like the
        Dolfin assign call."""
        # do not annotate in case of self assignment
        annotate = annotate_tape(kwargs) and self != other
        if annotate:
            if not isinstance(other, ufl.core.operator.Operator):
                other = create_overloaded_object(other)
            block = FunctionAssignBlock(self, other)
            tape = get_working_tape()
            tape.add_block(block)

        with stop_annotating():
            ret = super(Function, self).assign(other, *args, **kwargs)

        if annotate:
            block.add_output(self.create_block_variable())

        return ret
示例#22
0
parameters ["form_compiler"]["cpp_optimize"] = True
parameters ["form_compiler"]["representation"] = "uflacs"

Ll = 2; Ln = 4.5; Lr = 7.5
theta = 0.22
a1=11.56; a2=-17.44; a3=10.04; a4=-9.38
delta = 0.1

# Create domain with subdomains
domain = Rectangle (Point (-Ll, -0.5), Point (Ln+Lr, 0.5)) 
domain.set_subdomain (1, Rectangle (Point (-Ll, -0.5), Point (0, 0.5)))
domain.set_subdomain (2, Rectangle (Point (0, -0.5), Point (Ln, 0.5)))
domain.set_subdomain (3, Polygon ([Point (0, 0), Point (Ln, -0.5*theta), Point (Ln, 0.5*theta)]))
domain.set_subdomain (4, Polygon ([Point (Ln, -0.5*theta), Point (Ln+Lr, -0.5*theta), Point (Ln+Lr, 0.5*theta), Point (Ln, 0.5*theta)]))
with Timer ("mesh"): mesh = create_overloaded_object (generate_mesh (domain, 126)) # 126 253 505 1011 2022

class PeriodicBoundary (SubDomain):
    # bottom boundary is target domain
    def inside (self, x, on_boundary): return bool (near (x[1], -0.5) and on_boundary)
    # Map top boundary to bottom boundary
    def map (self, x, y): y[0] = x[0]; y[1] = x[1]-1.0

U = FunctionSpace (mesh, "CG", 1)
V = VectorFunctionSpace (mesh, "CG", 1, constrained_domain=PeriodicBoundary())
Vnp = VectorFunctionSpace (mesh, "CG", 1)
W = TensorFunctionSpace (mesh, "DG", 0)
X = FunctionSpace (mesh, "DG", 0)

x = SpatialCoordinate (mesh)
    
示例#23
0
mu = 5.
weight = 1.5
volweight = 0.02
ftol = 1e-10
gtol = 1e-8

#         defining the domain and the function spaces
domain = Rectangle(dolfin.Point(0., 0.), dolfin.Point(1., 1.))
for i in range(0, n):
    for j in range(0, n):
        domain = domain - Circle(dolfin.Point((0.5 + i) / n,
                                              (0.5 + j) / n), 1 / (4 * n))

# define mesh and function space
mesh = generate_mesh(domain, resolution)
mesh = create_overloaded_object(mesh)
x = SpatialCoordinate(mesh)

# Function spaces
U = VectorFunctionSpace(mesh, 'CG', 1)
V = FunctionSpace(mesh, 'CG', 1)
density = Function(V)
u = Function(U)
uu = TrialFunction(U)

xx = Function(U, name="xx")
xx.assign(project(x, U))

#             define subdomain for top boundary
subdomains = MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
subdomains.set_all(0)
示例#24
0
 def inner(*args, **kwargs):
     "Creating an overloaded Mesh that will be used in shape optimization"
     with stop_annotating():
         mesh = constructor(*args, **kwargs)
     return create_overloaded_object(mesh)
示例#25
0
文件: needles.py 项目: jan-v97/fenics
def get_mesh(ILt1,ILt2,ILr1,ILr2,ILtt,ILrr,Ipt,Ipr,phi,theta_t,theta_r,resolution,c_periodic):
	rounded = 12

	# input edges)
	a_x = round(0.,rounded)
	a_y = round(Ipt+ILt1+ILtt-(1-theta_t)*sin(phi),rounded)
	b_x = round((1-theta_t)*cos(phi),rounded)
	b_y = round(Ipt+ILt1+ILtt,rounded)
	c_x = round(cos(phi),rounded)
	c_y = round(Ipt+ILt1+ILtt+theta_t*sin(phi),rounded)
	d_x = round(0.,rounded)
	d_y = round(ILt2,rounded)
	e_x = round((1-theta_t)*cos(phi),rounded)
	e_y = round(Ipt+ILt1,rounded)
	f_x = round(cos(phi),rounded)
	f_y = round(sin(phi) + ILt2,rounded)
	g_x = round(0.,rounded)
	g_y = round(0.,rounded)
	h_x = round(Ipr,rounded)
	h_y = round(Ipt,rounded)
	i_x = round(cos(phi),rounded)
	i_y = round(sin(phi),rounded)
	j_x = round(ILr1,rounded)
	j_y = round(Ipt-theta_r*sin(phi),rounded)
	k_x = round(Ipr+ILr2,rounded)
	k_y = round(Ipt,rounded)
	l_x = round(cos(phi)+ILr1,rounded)
	l_y = round(sin(phi)+Ipt-theta_r*sin(phi),rounded)
	m_x = round(ILr1+ILrr,rounded)
	m_y = round(Ipt-theta_r*sin(phi),rounded)
	n_x = round(ILr1+ILrr+theta_r*cos(phi),rounded)
	n_y = round(Ipt,rounded)
	o_x = round(ILr1+ILrr+cos(phi),rounded)
	o_y = round(sin(phi)+Ipt-theta_r*sin(phi),rounded)

	
	tl = edgeinput([dolfin.Point(b_x,b_y),dolfin.Point(a_x, a_y)])
	tr = edgeinput([dolfin.Point(c_x,c_y),dolfin.Point(b_x, b_y)])
	rb = edgeinput([dolfin.Point(m_x, m_y),dolfin.Point(n_x, n_y)])
	rt = edgeinput([dolfin.Point(n_x, n_y),dolfin.Point(o_x, o_y)])
	mt = edgeinput([dolfin.Point(e_x,e_y),dolfin.Point(b_x, b_y)])
	mr = edgeinput([dolfin.Point(k_x, k_y),dolfin.Point(n_x, n_y)])
	lt = edgeinput(get_points(True,a_x,a_y,d_x,d_y,resolution,c_periodic))
	lt2 = edgeinput(get_points(False,f_x,f_y,c_x,c_y,resolution,c_periodic))
	br = edgeinput(get_points(True,j_x,j_y,m_x,m_y,resolution,c_periodic))
	br2 = edgeinput(get_points(False,o_x,o_y,l_x,l_y,resolution,c_periodic))
	t1 = edgeinput([dolfin.Point(h_x,h_y),dolfin.Point(e_x,e_y)])
	t2 = edgeinput(get_points(True,d_x,d_y,g_x,g_y,resolution,c_periodic))
	t3 = edgeinput([dolfin.Point(h_x,h_y),dolfin.Point(i_x,i_y)])
	t4 = edgeinput(get_points(False,i_x,i_y,f_x,f_y,resolution,c_periodic))
	r1 = edgeinput(get_points(True,g_x,g_y,j_x,j_y,resolution,c_periodic))
	r2 = edgeinput([dolfin.Point(h_x,h_y),dolfin.Point(k_x,k_y)])
	r3 = edgeinput([dolfin.Point(g_x,g_y),dolfin.Point(h_x,h_y)])
	r4 = edgeinput(get_points(False,l_x,l_y,i_x,i_y,resolution,c_periodic))

	# define a vector with the edges
	edges = [tl,tr,rb,rt,mt,mr,lt,lt2,br,br2,t1,t2,t3,t4,r1,r2,r3,r4]
	edges_number = len(edges)

	# define the complete domain
	domain_complete = subdomaininput([lt,t2,r1,br,rb,rt,br2,r4,t4,lt2,tr,tl],[0,0,0,0,0,0,0,0,0,0,0,0],0)

	# input subdomains
	domain_left = subdomaininput([lt,t2,r3,t1,mt,tl],[0,0,0,0,0,0],0)
	domain_top = subdomaininput([t3,t4,lt2,tr,mt,t1],[0,0,0,0,1,1],0)
	domain_right = subdomaininput([r2,mr,rt,br2,r4,t3],[0,0,0,0,0,1],0)
	domain_bottom = subdomaininput([r1,br,rb,mr,r2,r3],[0,0,0,1,1,1],0)


	# define a vector with the subdomains
	subdomains = [domain_left,domain_top,domain_right,domain_bottom]
	subdomain_number = len(subdomains)

	# defining the domain, and the subdomains
	domain = Polygon(domain_complete.get_polygon())
	for i in range(0, subdomain_number):
		domain.set_subdomain (i+1, Polygon((subdomains[i]).get_polygon()))

	# generat the mesh
	#domain2 = Polygon([Point(0,0),dolfin.Point(3,0),dolfin.Point(3,3),dolfin.Point(0,3)])
	mesh = generate_mesh (domain, resolution)
	sudom = MeshFunction ('size_t', mesh, 2, mesh.domains())
	print ("Anzahl Knoten:", mesh.num_vertices())
	

	# refining the mesh everywhere but in the laminate
	maximumt = max(ILt1,Ipt+ILt2)
	maximumr = max(ILr1,Ipr+ILr2)
	tanphi = tan(phi)
	cell_markers = MeshFunction("bool", mesh,2)
	cell_markers.set_all(False)
	for cell in cells(mesh):
		if ((cell.get_vertex_coordinates()[1]< maximumt*1. + tanphi * cell.get_vertex_coordinates()[0]) and (cell.get_vertex_coordinates()[0]< maximumr*1. + (1/tanphi) * cell.get_vertex_coordinates()[1])):
			cell_markers[cell]=True
	mesh = refine(mesh, cell_markers)
	sudom = adapt(sudom, mesh)
	print ("Anzahl Knoten:", mesh.num_vertices())

	# cell_markers = MeshFunction("bool", mesh,2)
	# cell_markers.set_all(False)
	# for cell in cells(mesh):
	# 	if ((cell.get_vertex_coordinates()[1]< maximumt*1.25 + tanphi * cell.get_vertex_coordinates()[0]) and (cell.get_vertex_coordinates()[0]< maximumr*1.25 + (1/tanphi) * cell.get_vertex_coordinates()[1])):
	# 		cell_markers[cell]=True
	# mesh = refine(mesh, cell_markers)
	# sudom = adapt(sudom, mesh)
	# print ("Anzahl Knoten:", mesh.num_vertices())

	# cell_markers = MeshFunction("bool", mesh,2)
	# cell_markers.set_all(False)
	# for cell in cells(mesh):
	# 	if ((cell.get_vertex_coordinates()[1]< maximumt*1. + tanphi * cell.get_vertex_coordinates()[0]) and (cell.get_vertex_coordinates()[0]< maximumr*1. + (1/tanphi) * cell.get_vertex_coordinates()[1])):
	# 		cell_markers[cell]=True
	# mesh = refine(mesh, cell_markers)
	# sudom = adapt(sudom, mesh)
	# print ("Anzahl Knoten:", mesh.num_vertices())

	# cell_markers = MeshFunction("bool", mesh,2)
	# cell_markers.set_all(False)
	# for cell in cells(mesh):
	# 	if ((cell.get_vertex_coordinates()[1]< 0.5 + 0.5*Ipt - 0.5*Ipt*tanphi + tanphi * cell.get_vertex_coordinates()[0]) and (cell.get_vertex_coordinates()[0]< 0.5 + 0.5*Ipr - 0.5*Ipt * (1/tanphi) + (1/tanphi) * cell.get_vertex_coordinates()[1])):
	# 		cell_markers[cell]=True
	# mesh = refine(mesh, cell_markers)
	# sudom = adapt(sudom, mesh)
	# print ("Anzahl Knoten:", mesh.num_vertices())
	
	# refining the mesh at the endpoint of edges
	# ref_rad=0.05
	# for k in range(0,1):
	# 	cell_markers = MeshFunction("bool", mesh,2)
	# 	cell_markers.set_all(False)
	# 	for cell in cells(mesh):
	# 		if (cell.distance(Point(d_x,d_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(e_x,e_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(f_x,f_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(j_x,j_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(k_x,k_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(l_x,l_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 	mesh = refine(mesh, cell_markers)
	# 	sudom = adapt(sudom, mesh)
	# 	print ("Anzahl Knoten:", mesh.num_vertices())

	# for k in range(0,1):
	# 	cell_markers = MeshFunction("bool", mesh,2)
	# 	cell_markers.set_all(False)
	# 	for cell in cells(mesh):
	# 		if (cell.distance(Point(g_x,g_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(h_x,h_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 		elif (cell.distance(Point(i_x,i_y))<ref_rad*2**(-k)):
	# 			cell_markers[cell]=True
	# 	mesh = refine(mesh, cell_markers)
	# 	sudom = adapt(sudom, mesh)
	# 	print ("Anzahl Knoten:", mesh.num_vertices())

	mesh = create_overloaded_object(mesh)

	# defining coefficients on subdomains
	X = FunctionSpace (mesh, "DG", 0)
	dm = X.dofmap()
	sudom_arr = numpy.asarray (sudom.array(), dtype=numpy.int64)
	for cell in cells (mesh): 
		sudom_arr [dm.cell_dofs (cell.index())] = sudom [cell]
	#sudom_arr = numpy.asarray (sudom.array(), dtype=numpy.int64)
	#for cell in cells (mesh): sudom_arr [dm.cell_dofs (cell.index())] = sudom [cell]

	def sudom_fct (sudom_arr, vals, fctspace):
		f = Function (fctspace)
		f.vector()[:] = numpy.choose (sudom_arr, vals)
		return f

	chi_a = sudom_fct (sudom_arr, [0,1,0,1,0], X)
	chi_b = sudom_fct (sudom_arr, [0,0,1,0,1], X)
	return mesh, edges, edges_number, chi_a, chi_b,mesh.num_vertices()
示例#26
0
 def recompute_component(self, inputs, block_variable, idx, prepared):
     form = prepared
     output = backend.assemble(form)
     output = create_overloaded_object(output)
     return output