Пример #1
0
def plot_function_2d(mesh, f, result_path):
    n = mesh.num_vertices()
    d = mesh.geometry().dim()

    # Create the triangulation
    mesh_coordinates = mesh.coordinates().reshape((n, d))
    triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    # Get the z values as face colors for each triangle(midpoint)
    plt.figure()
    zfaces = np.asarray([f(cell.midpoint()) for cell in cells(mesh)])
    plt.tripcolor(triangulation, facecolors=zfaces, edgecolors='k')
    fig = plt.gcf()
    fig.savefig(result_path + "-faces.eps")

    # Get the z values for each vertex
    plt.figure()
    z = np.asarray([f(point) for point in mesh_coordinates])
    plt.tripcolor(triangulation, z, edgecolors='k')
    plt.xlabel('x')
    plt.ylabel('u')

    fig = plt.gcf()
    fig.savefig(result_path + "-vertices.eps")
Пример #2
0
def bulk_marking(mesh, distr, theta):
    marking = CellFunction("bool", mesh)
    distr_0 = sorted(distr, reverse=True)[int(len(distr) * theta)]
    for cell in cells(mesh):
        marking[cell] = distr[cell.index()] > distr_0

    return marking
Пример #3
0
    def estimate(self, solution):
        mesh = solution.function_space().mesh()

        # Define cell and facet residuals
        R_T = -(self.rhs_f + div(grad(solution)))
        n = FacetNormal(mesh)
        R_dT = dot(grad(solution), n)

        # Will use space of constants to localize indicator form
        Constants = FunctionSpace(mesh, "DG", 0)
        w = TestFunction(Constants)
        h = CellSize(mesh)

        # Define form for assembling error indicators
        form = (h ** 2 * R_T ** 2 * w * dx + avg(h) * avg(R_dT) ** 2 * 2 * avg(w) * dS)
    #            + h * R_dT ** 2 * w * ds)

        # Assemble error indicators
        indicators = assemble(form)

        # Calculate error
        error_estimate = sqrt(sum(i for i in indicators.array()))

        # Take sqrt of indicators
        indicators = np.array([sqrt(i) for i in indicators])

        # Mark cells for refinement based on maximal marking strategy
        largest_error = max(indicators)
        cell_markers = MeshFunction("bool", mesh, mesh.topology().dim())
        for c in cells(mesh):
            cell_markers[c] = indicators[c.index()] > (self.fraction * largest_error)

        return error_estimate, cell_markers
Пример #4
0
def averaged_marking(mesh, distr):
    cells_num = mesh.num_cells()
    marking = CellFunction("bool", mesh)
    distr_aver = sum(distr) / cells_num
    for c in cells(mesh):
        marking[c] = distr[c.index()] >= distr_aver
    return marking
Пример #5
0
def error_majorant_distribution_nd(mesh, dim, ed_var, md_var, mf_var, V_exact):

    cell_num = mesh.num_cells()
    ed_distr = allocate_array_1d(cell_num)
    md_distr = allocate_array_1d(cell_num)
    maj_distr = allocate_array_1d(cell_num)

    md = project(md_var, V_exact)
    mf = project(mf_var, V_exact)
    ed = project(ed_var, V_exact)

    scheme_order = 4
    gauss = integrators.SpaceIntegrator(scheme_order, dim)
    for c in cells(mesh):

        # Obtaining the coordinates of the vertices in the cell
        verts = c.get_vertex_coordinates().reshape(dim + 1, dim)
        x_n_transpose = verts.T

        # Calculating the area of the cell
        matrix = postprocess.allocate_array_2d(dim + 1, dim + 1)
        matrix[0:dim, 0:dim + 1] = x_n_transpose
        matrix[dim, 0:dim + 1] = numpy.array([1.0 for i in range(dim + 1)])

        meas = float(1.0 / math.factorial(dim)) * abs(numpy.linalg.det(matrix))

        ed_distr[c.index()] = gauss.integrate(ed, meas, x_n_transpose)
        md_distr[c.index()] = gauss.integrate(md, meas, x_n_transpose)
        maj_distr[c.index()] = gauss.integrate(mf, meas, x_n_transpose)

    print "ed_distr  int total = %8.2e" % numpy.sum(ed_distr)
    print "md_distr  int total = %8.2e" % numpy.sum(md_distr)
    print "maj_distr int total = %8.2e\n" % numpy.sum(maj_distr)

    return ed_distr, md_distr, maj_distr, ed, md, mf
Пример #6
0
def plot_carpet_2d(mesh, f, result_path):
    num_vert = mesh.num_vertices()
    num_cells = mesh.num_cells()

    d = mesh.geometry().dim()

    # Create the triangulation
    mesh_coordinates = mesh.coordinates().reshape((num_vert, d))
    triangles = numpy.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    fig = plt.figure()

    # add labels
    plt.figure()
    plt.xlabel('x')
    plt.ylabel('y')

    # change the font
    matplotlib.rcParams.update({'font.size': 16, 'font.family': 'serif'})

    z = numpy.asarray([f(point) for point in mesh_coordinates])
    plt.tripcolor(triangulation, z, cmap=cm.coolwarm, edgecolors='k')
    fig = plt.gcf()
    fig.savefig(result_path + "-cells-%d-vertices-%d.eps" %
                (num_cells, num_vert))
Пример #7
0
def get_2d_slice_of_3d_function_on_Oz(mesh, u, T, dim, v_degree):

    # create a boundary mesh
    bmesh = BoundaryMesh(mesh, "exterior")
    cell_func = CellFunction('size_t', bmesh, 0)
    coordinates = bmesh.coordinates()
    z_indeces = postprocess.allocate_array(dim)

    for cell in cells(bmesh):
        indx = 0
        for vertex in vertices(cell):
            z_indeces[indx] = coordinates[vertex.index()][dim - 1]
            indx += 1
            #print "Vertex index with coordinates", vertex.index(), coordinates[vertex.index()][dim-1]
        if (dim == 3 and near(z_indeces[0], T) and near(z_indeces[1], T)
                and near(z_indeces[2], T)) or (dim == 2 and near(
                    z_indeces[0], T) and near(z_indeces[1], T)):
            #print "right cell", cell.index()
            cell_func[cell] = 1

    submesh = SubMesh(bmesh, cell_func, 1)

    # create a FunctionSpace on the submesh-
    Vs = FunctionSpace(submesh, "Lagrange", v_degree)
    us = interpolate(u, Vs)

    return us, submesh
Пример #8
0
def plot_carpet_2d(mesh, f, result_path):
    num_vert = mesh.num_vertices()
    num_cells = mesh.num_cells()

    d = mesh.geometry().dim()

    # Create the triangulation
    mesh_coordinates = mesh.coordinates().reshape((num_vert, d))
    triangles = numpy.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    # Get the z values as face colors for each triangle(midpoint)
    fig = plt.figure()

    # Get the z values for each vertex
    plt.figure()
    plt.xlabel('x')
    plt.ylabel('y')
    z = numpy.asarray([f(point) for point in mesh_coordinates])
    plt.tripcolor(triangulation, z, cmap=cm.coolwarm, edgecolors='k')
    fig = plt.gcf()
    fig.savefig(result_path + "-cells-%d-vertices-%d.eps" %
                (num_cells, num_vert))
    plt.close('all')
Пример #9
0
def construct_A_from_mesh_functions(dim, A_expr, mesh):

    if dim == 2:
        a01 = MeshFunction("double", mesh, dim)
        a11 = MeshFunction("double", mesh, dim)

    A1 = A_expr[0]
    A2 = A_expr[1]

    a00 = MeshFunction("double", mesh, dim)

    for cell in cells(mesh):
        if cell.midpoint().x() < 0.5:
            if dim == 2:
                a00[cell] = A1[0][0]
                a11[cell] = A1[1][1]
                a01[cell] = A1[0][1]
        else:
            if dim == 2:
                a00[cell] = A2[0][0]
                a11[cell] = A2[1][1]
                a01[cell] = A2[0][1]

    # Code for C++ evaluation of conductivity
    conductivity_code = """

    class Conductivity : public Expression
    {
    public:

      // Create expression with 3 components
      Conductivity() : Expression(3) {}

      // Function for evaluating expression on each cell
      void eval(Array<double>& values, const Array<double>& x, const ufc::cell& cell) const
      {
        const uint D = cell.topological_dimension;
        const uint cell_index = cell.index;
        values[0] = (*a00)[cell_index];
        values[1] = (*a01)[cell_index];
        values[2] = (*a11)[cell_index];
      }

      // The data stored in mesh functions
      std::shared_ptr<MeshFunction<double> > a00;
      std::shared_ptr<MeshFunction<double> > a01;
      std::shared_ptr<MeshFunction<double> > a11;

    };
    """

    a = Expression(cppcode=conductivity_code)
    a.a00 = a00
    a.a01 = a01
    a.a11 = a11
    A = as_matrix(((a[0], a[1]), (a[1], a[2])))

    return A
Пример #10
0
def error_majorant_distribution_nd(mesh, domain, dim, u_e, grad_u_e, u,
                                   V_exact, y, f, lmbd, beta):

    cell_num = mesh.num_cells()
    #e_distr = postprocess.allocate_array(cell_num)
    #m_distr = postprocess.allocate_array(cell_num)
    ed_distr = postprocess.allocate_array(cell_num)
    md_distr = postprocess.allocate_array(cell_num)

    # Define error and residuals
    r_d = abs(Grad(u, dim) - y)
    r_f = abs(f + Div(y, dim) - lmbd * u)

    #C_FD = calculate_CF_of_domain(domain, dim)

    u_ve = interpolate(u, V_exact)
    u_exact_ve = interpolate(u_e, V_exact)
    e = u_ve - u_exact_ve

    #w_opt = (C_FD ** 2) * (1 + beta) / (beta + (C_FD ** 2) * (1 + beta) * lmbd)

    # Project UFL forms on the high-order functional space to obtain functions
    #ed = project(sqrt(inner(Grad(e, dim), Grad(e, dim))), V_exact)
    #md = project(sqrt(inner(r_d, r_d)), V_exact)
    ed = project(inner(Grad(e, dim), Grad(e, dim)), V_exact)
    md = project(inner(r_d, r_d), V_exact)

    #ed_test = assemble(sqrt(inner(Grad(e, dim), Grad(e, dim))) * dx)
    #md_test = assemble(sqrt(inner(r_d, r_d)) * dx)
    #e = project(sqrt(inner(Grad(e, dim), Grad(e, dim)) + lmbd * inner(e, e)), V_exact)
    #m = project(sqrt((1 + beta) * inner(r_d, r_d) + w_opt * inner(r_f, r_f)), V_exact)

    dofmap = V_exact.dofmap()

    scheme_order = 4
    gauss = integration.SpaceIntegrator(scheme_order, dim)

    for c in cells(mesh):
        verts = dofmap.tabulate_coordinates(c)
        x_n = verts[0:dim + 1, :]
        x_n_transpose = x_n.transpose()

        matrix = postprocess.allocate_array_2d(dim + 1, dim + 1)
        matrix[0:dim, 0:dim + 1] = x_n_transpose
        matrix[dim, 0:dim + 1] = numpy.array([1.0 for i in range(dim + 1)])
        meas = abs(numpy.linalg.det(matrix))

        ed_distr[c.index()] = gauss.integrate(ed, meas, x_n_transpose)
        md_distr[c.index()] = gauss.integrate(md, meas, x_n_transpose)

        #e_distr[c.index()] = gauss.integrate(e, meas, x_n_transpose)
        #m_distr[c.index()] = gauss.integrate(m, meas, x_n_transpose)

    print 'sum of m_cells', numpy.sum(md_distr)
    print 'sum of e_cells', numpy.sum(ed_distr)

    return ed_distr, md_distr
Пример #11
0
def smoothness_distribution(u, mesh, dim):
    cell_num = mesh.num_cells()
    smoothness = postprocess.allocate_array(cell_num)

    for c in cells(mesh):
        # vert: num of vertices
        # horiz: dimension
        verts = c.get_vertex_coordinates().reshape(dim + 1, dim)
        u_inf_norm = l_inf_norm(u, verts, dim)

        h = c.h()
        denominator = h / 2 * assemble_local(inner(
            grad(u), grad(u)) * dx, c) + 2 / h * assemble_local(u * u * dx, c)
        F_c = u_inf_norm**2 / denominator
        smoothness[c.index()] = F_c
    return smoothness
Пример #12
0
def plot_function_3d(mesh, f, result_path):

    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm

    num_vert = mesh.num_vertices()
    num_cells = mesh.num_cells()

    d = mesh.geometry().dim()

    mesh_coordinates = mesh.coordinates().reshape((num_vert, d))
    triangles = numpy.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)
    z = numpy.asarray([f(point) for point in mesh_coordinates])

    # change the font
    matplotlib.rcParams.update({'font.size': 10, 'font.family': 'serif'})

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    '''
    # customize ticks on the axises
    start, end = ax.get_zlim()
    ax.zaxis.set_ticks(numpy.arange(start, end, (end - start) / 3))
    ax.zaxis.set_major_formatter(ticker.FormatStrFormatter('%0.2f'))

    start, end = ax.get_xlim()
    ax.xaxis.set_ticks(numpy.arange(start, end, (end - start) / 3))
    ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.2f'))

    start, end = ax.get_ylim()
    ax.yaxis.set_ticks(numpy.arange(start, end, (end - start) / 3))
    ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.2f'))
    '''

    # add labels
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('u')

    # ax.plot_trisurf(triangulation, z, cmap=cm.gray, linewidth=0.2) RdGy
    ax.plot_trisurf(triangulation, z, cmap=cm.BrBG, linewidth=0.2)
    # ax.plot_trisurf(triangulation, z, cmap=cm.jet, linewidth=0.2)
    fig.savefig(result_path + '-cells-%d-vertices-%d.eps' %
                (num_cells, num_vert))
    plt.close('all')
Пример #13
0
def error_majorant_distribution_nd(mesh, dim, V_exact, var_grad_e, var_delta_e,
                                   var_m_d, var_m_f_w_opt, beta, C_FD):
    cell_num = mesh.num_cells()
    ed_distr = postprocess.allocate_array(cell_num)
    delta_e_distr = postprocess.allocate_array(cell_num)
    md_distr = postprocess.allocate_array(cell_num)
    maj_distr = postprocess.allocate_array(cell_num)

    # Project UFL forms on the high-order functional space to obtain functions
    ed = project((var_grad_e), V_exact)
    delta_e = project(var_delta_e, V_exact)
    md = project((var_m_d), V_exact)
    mf_wopt = project(var_m_f_w_opt, V_exact)

    scheme_order = 4
    gauss = integration.SpaceIntegrator(scheme_order, dim)

    for c in cells(mesh):
        # Obtaining the coordinates of the vertices in the cell
        verts = c.get_vertex_coordinates().reshape(dim + 1, dim)
        x_n_transpose = verts.T

        # Calculating the area of the cell
        matrix = postprocess.allocate_array_2d(dim + 1, dim + 1)
        matrix[0:dim, 0:dim + 1] = x_n_transpose
        matrix[dim, 0:dim + 1] = numpy.array([1.0 for i in range(dim + 1)])
        # print "matrix = ", matrix
        meas = abs(numpy.linalg.det(matrix))

        # Integrating over the cell
        ed_distr[c.index()] = gauss.integrate(ed, meas, x_n_transpose)
        delta_e_distr[c.index()] = gauss.integrate(delta_e, meas,
                                                   x_n_transpose)
        md_distr[c.index()] = gauss.integrate(md, meas, x_n_transpose)
        #maj_distr[c.index()] = gauss.integrate(mdf, meas, x_n_transpose)

    #print 'num md_cells', md_distr
    #print 'ed_cells', ed_distr
    #print 'delta_e_cells', delta_e_distr

    #print 'maj_cells', maj_distr
    #print 'e_cells', e_distr

    print '\nmd = Sum_K md_K = %8.2e' % sum(md_distr)
    print 'ed = Sum_K ed_K = %8.2e' % sum(ed_distr)

    return ed_distr, md_distr, maj_distr
Пример #14
0
def predefined_amount_of_elements_marking(mesh, distr, theta):

    cells_num = mesh.num_cells()
    marking = CellFunction("bool", mesh)
    marking.set_all(False)

    i_cut = int(math.floor(theta * cells_num))
    index_sorted = sorted(range(len(distr)),
                          key=lambda k: distr[k],
                          reverse=True)
    cells_indices_to_refine = index_sorted[0:i_cut]

    for cell in cells(mesh):
        if cell.index() in cells_indices_to_refine:
            marking[cell] = True

    return marking
Пример #15
0
def plot_function_3d(mesh, f, result_path):
    from matplotlib import cm

    n_vert = mesh.num_vertices()
    n_cells = mesh.num_cells()

    d = mesh.geometry().dim()

    mesh_coordinates = mesh.coordinates().reshape((n_vert, d))
    triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)
    z = np.asarray([f(point) for point in mesh_coordinates])

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    ax.plot_trisurf(triangulation, z, cmap=cm.coolwarm, linewidth=0.2)
    fig.savefig(result_path + "-cells-%d-vertices-%d.eps" % (n_cells, n_vert))
Пример #16
0
def construct_from_mesh_functions(dim, A_expr, mesh):
    """
    :param dim: geometrical dimension
    :param A_expr: expression defining diffusion matrix
    :param mesh: mesh-discretization of the domain
    :return: cell-wise function
    """

    # Define scalar cell-wise function for dim = 1
    a00 = MeshFunction("double", mesh, dim)
    # Define function expression from the problem data (depending on how many of the conditions are discussed )
    A1 = A_expr[0]
    A2 = A_expr[1]

    # Case for dimension higher then one (symmetric case)
    if dim >= 2:
        a01 = MeshFunction("double", mesh, dim)
        a11 = MeshFunction("double", mesh, dim)
    # Case for dimension higher then two (symmetric case)
    if dim >= 3:
        a02 = MeshFunction("double", mesh, dim)
        a12 = MeshFunction("double", mesh, dim)
        a22 = MeshFunction("double", mesh, dim)

    for cell in cells(mesh):
        if cell.midpoint().x(
        ) < 0.5:  # this condition checks whethe the elements on the left part of the domain
            A = A_expr[0]
        else:
            A = A_expr[1]

        a00[cell] = A[0][0]
        if dim >= 2:
            a11[cell] = A[1][1]
            a01[cell] = A[0][1]
        if dim >= 3:
            a02[cell] = A[0][2]
            a12[cell] = A[1][2]
            a22[cell] = A[2][2]

    # Code for C++ evaluation of conductivity
    conductivity_code = """

    class Conductivity : public Expression
    {
    public:

      // Create expression with 3 components
      Conductivity() : Expression(3) {}

      // Function for evaluating expression on each cell
      void eval(Array<double>& values, const Array<double>& x, const ufc::cell& cell) const
      {
        const uint D = cell.topological_dimension;
        const uint cell_index = cell.index;
        values[0] = (*a00)[cell_index];
        values[1] = (*a01)[cell_index];
        values[2] = (*a11)[cell_index];
      }

      // The data stored in mesh functions
      std::shared_ptr<MeshFunction<double> > a00;
      std::shared_ptr<MeshFunction<double> > a01;
      std::shared_ptr<MeshFunction<double> > a11;

    };
    """
    # Define expression via C++ code
    a = Expression(cppcode=conductivity_code)
    a.a00 = a00
    if dim >= 2:
        a.a01 = a01
        a.a11 = a11
    if dim >= 3:
        a.a02 = a02
        a.a12 = a12
        a.a22 = a22
    # Define matrix depending on the dimension
    if dim == 1:
        A = a[0]
    elif dim == 2:
        # A = |a[0] a[1]|
        #     |a[1] a[2]|
        A = as_matrix(((a[0], a[1]), (a[1], a[2])))
    elif dim == 3:
        # A = |a[0] a[1] a[2]|
        #     |a[1] a[3] a[4]|
        #     |a[2] a[4] a[5]|
        A = as_matrix(
            ((a[0], a[1], a[2]), (a[1], a[3], a[4]), (a[2], a[3], a[5])))

    return A
Пример #17
0
def error_majorant_distribution_nd(mesh, dim, V_exact, var_grad_e, var_delta_e,
                                   var_m_d, var_m_f_w_opt, beta):

    # Allocate arrays for error and majorant distributions
    cell_num = mesh.num_cells()
    ed_distr = postprocess.allocate_array(cell_num)
    delta_e_distr = postprocess.allocate_array(cell_num)
    md_distr = postprocess.allocate_array(cell_num)
    mf_distr = postprocess.allocate_array(cell_num)

    # Project UFL forms on the high-order functional space to obtain functions
    ed = project(var_grad_e, V_exact)
    delta_e = project(var_delta_e, V_exact)
    md = project(var_m_d, V_exact)
    mf_wopt = project(var_m_f_w_opt, V_exact)

    # Obtained the mapping
    #dofmap = V_exact
    #mesh_coordimates = dofmap.
    # Define integration scheme order and assign the integrator
    scheme_order = 4
    gauss = integration.SpaceIntegrator(scheme_order, dim)

    # Iterate over cells of the mesh and obtain local value of the majorant
    for c in cells(mesh):

        # Obtaining the coordinates of the vertices in the cell
        verts = c.get_vertex_coordinates().reshape(dim + 1, dim)
        x_n_transpose = verts.T

        # Calculating the area of the cell
        matrix = postprocess.allocate_array_2d(dim + 1, dim + 1)
        matrix[0:dim, 0:dim + 1] = x_n_transpose
        matrix[dim, 0:dim + 1] = numpy.array([1.0 for i in range(dim + 1)])
        #print "matrix = ", matrix
        meas = abs(numpy.linalg.det(matrix))

        # Integrating over the cell
        ed_distr[c.index()] = gauss.integrate(ed, meas, x_n_transpose)
        delta_e_distr[c.index()] = gauss.integrate(delta_e, meas,
                                                   x_n_transpose)
        md_distr[c.index()] = gauss.integrate(md, meas, x_n_transpose)
        mf_distr[c.index()] = gauss.integrate(mf_wopt, meas, x_n_transpose)

    # Calculate majorant based on the parameter value
    if sum(mf_distr) <= DOLFIN_EPS:
        maj_distr = md_distr
    else:
        if sum(md_distr) <= DOLFIN_EPS:
            maj_distr = mf_distr
        else:
            maj_distr = (
                1.0 + beta
            ) * md_distr + mf_distr  # here (1 + 1/beta) weight is ommited since it is included into the optimal mf_wopt

    e_distr = ed_distr + delta_e_distr

    #print 'md_cells', md_distr
    #print 'ed_cells', ed_distr

    print 'sum md_cells', sum(md_distr)
    print 'sum maj_cells', sum(maj_distr)
    print 'sum e_cells', sum(e_distr)

    return ed_distr, delta_e_distr, e_distr, md_distr, mf_distr, maj_distr, ed, md