xref: /libCEED/examples/python/ex2_surface.py (revision 7b3ff0698626cc2e5ce463afc10290072fd55c90)
1*7b3ff069SJeremy L Thompson#!/usr/bin/env python3
2*7b3ff069SJeremy L Thompson# Copyright (c) 2017-2025, Lawrence Livermore National Security, LLC and other CEED contributors.
3*7b3ff069SJeremy L Thompson# All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
4*7b3ff069SJeremy L Thompson#
5*7b3ff069SJeremy L Thompson# SPDX-License-Identifier: BSD-2-Clause
6*7b3ff069SJeremy L Thompson#
7*7b3ff069SJeremy L Thompson# This file is part of CEED:  http://github.com/ceed
8*7b3ff069SJeremy L Thompson#
9*7b3ff069SJeremy L Thompson# libCEED example using diffusion operator to compute surface area
10*7b3ff069SJeremy L Thompson#
11*7b3ff069SJeremy L Thompson# Sample runs:
12*7b3ff069SJeremy L Thompson#
13*7b3ff069SJeremy L Thompson#     python ex2_surface.py
14*7b3ff069SJeremy L Thompson#     python ex2_surface.py -c /cpu/self
15*7b3ff069SJeremy L Thompson#     python ex2_surface.py -c /gpu/cuda
16*7b3ff069SJeremy L Thompson
17*7b3ff069SJeremy L Thompsonimport sys
18*7b3ff069SJeremy L Thompsonimport os
19*7b3ff069SJeremy L Thompsonimport numpy as np
20*7b3ff069SJeremy L Thompsonimport libceed
21*7b3ff069SJeremy L Thompsonimport ex_common as common
22*7b3ff069SJeremy L Thompson
23*7b3ff069SJeremy L Thompson
24*7b3ff069SJeremy L Thompsondef main():
25*7b3ff069SJeremy L Thompson    """Main driver for surface area example"""
26*7b3ff069SJeremy L Thompson    args = common.parse_arguments()
27*7b3ff069SJeremy L Thompson    return example_2(args)
28*7b3ff069SJeremy L Thompson
29*7b3ff069SJeremy L Thompson
30*7b3ff069SJeremy L Thompsondef example_2(options):
31*7b3ff069SJeremy L Thompson    """Compute surface area using diffusion operator
32*7b3ff069SJeremy L Thompson
33*7b3ff069SJeremy L Thompson    Args:
34*7b3ff069SJeremy L Thompson        args: Parsed command line arguments
35*7b3ff069SJeremy L Thompson
36*7b3ff069SJeremy L Thompson    Returns:
37*7b3ff069SJeremy L Thompson        int: 0 on success, error code on failure
38*7b3ff069SJeremy L Thompson    """
39*7b3ff069SJeremy L Thompson    # Process arguments
40*7b3ff069SJeremy L Thompson    args = options
41*7b3ff069SJeremy L Thompson    dim = args.dim
42*7b3ff069SJeremy L Thompson    mesh_degree = max(args.mesh_degree, args.solution_degree)
43*7b3ff069SJeremy L Thompson    sol_degree = args.solution_degree
44*7b3ff069SJeremy L Thompson    num_qpts = args.quadrature_points
45*7b3ff069SJeremy L Thompson    problem_size = args.problem_size if args.problem_size > 0 else (500 * dim * dim if args.test else 256 * 1024)
46*7b3ff069SJeremy L Thompson    ncomp_x = dim  # Number of coordinate components
47*7b3ff069SJeremy L Thompson
48*7b3ff069SJeremy L Thompson    # Print configuration
49*7b3ff069SJeremy L Thompson    if not args.quiet:
50*7b3ff069SJeremy L Thompson        print("Selected options: [command line option] : <current value>")
51*7b3ff069SJeremy L Thompson        print(f"    Ceed specification [-c] : {args.ceed}")
52*7b3ff069SJeremy L Thompson        print(f"    Mesh dimension     [-d] : {dim}")
53*7b3ff069SJeremy L Thompson        print(f"    Mesh degree        [-m] : {mesh_degree}")
54*7b3ff069SJeremy L Thompson        print(f"    Solution degree    [-p] : {sol_degree}")
55*7b3ff069SJeremy L Thompson        print(f"    Num. 1D quadr. pts [-q] : {num_qpts}")
56*7b3ff069SJeremy L Thompson        print(f"    Approx. # unknowns [-s] : {problem_size}")
57*7b3ff069SJeremy L Thompson        print(f"    QFunction source   [-g] : {'gallery' if args.gallery else 'user'}")
58*7b3ff069SJeremy L Thompson
59*7b3ff069SJeremy L Thompson    # Initialize CEED
60*7b3ff069SJeremy L Thompson    ceed = libceed.Ceed(args.ceed)
61*7b3ff069SJeremy L Thompson
62*7b3ff069SJeremy L Thompson    # Create bases
63*7b3ff069SJeremy L Thompson    # Tensor-product Lagrange basis for mesh coordinates
64*7b3ff069SJeremy L Thompson    mesh_basis = ceed.BasisTensorH1Lagrange(
65*7b3ff069SJeremy L Thompson        dim, ncomp_x, mesh_degree + 1, num_qpts, libceed.GAUSS)
66*7b3ff069SJeremy L Thompson
67*7b3ff069SJeremy L Thompson    # Tensor-product Lagrange basis for solution
68*7b3ff069SJeremy L Thompson    solution_basis = ceed.BasisTensorH1Lagrange(
69*7b3ff069SJeremy L Thompson        dim, 1, sol_degree + 1, num_qpts, libceed.GAUSS)
70*7b3ff069SJeremy L Thompson
71*7b3ff069SJeremy L Thompson    # Create mesh
72*7b3ff069SJeremy L Thompson    # Determine mesh size
73*7b3ff069SJeremy L Thompson    num_xyz = common.get_cartesian_mesh_size(dim, sol_degree, problem_size)
74*7b3ff069SJeremy L Thompson    if not args.quiet:
75*7b3ff069SJeremy L Thompson        print("\nMesh size                   : nx = %d" % num_xyz[0], end="")
76*7b3ff069SJeremy L Thompson        if dim > 1:
77*7b3ff069SJeremy L Thompson            print(", ny = %d" % num_xyz[1], end="")
78*7b3ff069SJeremy L Thompson        if dim > 2:
79*7b3ff069SJeremy L Thompson            print(", nz = %d" % num_xyz[2], end="")
80*7b3ff069SJeremy L Thompson        print()
81*7b3ff069SJeremy L Thompson
82*7b3ff069SJeremy L Thompson    # Create element restrictions
83*7b3ff069SJeremy L Thompson    num_q_comp = dim * (dim + 1) // 2
84*7b3ff069SJeremy L Thompson    mesh_restriction, mesh_size, _, _, _ = common.build_cartesian_restriction(
85*7b3ff069SJeremy L Thompson        ceed, dim, num_xyz, mesh_degree, ncomp_x, num_q_comp, num_qpts, create_qdata=False)
86*7b3ff069SJeremy L Thompson    solution_restriction, sol_size, q_data_restriction, num_elem, elem_qpts = common.build_cartesian_restriction(
87*7b3ff069SJeremy L Thompson        ceed, dim, num_xyz, sol_degree, 1, num_q_comp, num_qpts, create_qdata=True)
88*7b3ff069SJeremy L Thompson
89*7b3ff069SJeremy L Thompson    if not args.quiet:
90*7b3ff069SJeremy L Thompson        print("Number of mesh nodes        : %d" % (mesh_size // dim))
91*7b3ff069SJeremy L Thompson        print("Number of solution nodes    : %d" % sol_size)
92*7b3ff069SJeremy L Thompson
93*7b3ff069SJeremy L Thompson    # Create and transform mesh coordinates
94*7b3ff069SJeremy L Thompson    mesh_coords = ceed.Vector(mesh_size)
95*7b3ff069SJeremy L Thompson    common.set_cartesian_mesh_coords(ceed, dim, num_xyz, mesh_degree, mesh_coords)
96*7b3ff069SJeremy L Thompson    _, exact_surface_area = common.transform_mesh_coords(dim, mesh_size, mesh_coords, use_sin=False)
97*7b3ff069SJeremy L Thompson
98*7b3ff069SJeremy L Thompson    # Create the QFunction that builds the diffusion operator (i.e. computes
99*7b3ff069SJeremy L Thompson    # its quadrature data) and set its context data
100*7b3ff069SJeremy L Thompson    qf_build = None
101*7b3ff069SJeremy L Thompson    if args.gallery:
102*7b3ff069SJeremy L Thompson        qf_build = ceed.QFunctionByName(f"Poisson{dim}DBuild")
103*7b3ff069SJeremy L Thompson    else:
104*7b3ff069SJeremy L Thompson        build_ctx = ceed.QFunctionContext()
105*7b3ff069SJeremy L Thompson        ctx_data = np.array([dim, dim], dtype=np.int32)
106*7b3ff069SJeremy L Thompson        build_ctx.set_data(ctx_data)
107*7b3ff069SJeremy L Thompson
108*7b3ff069SJeremy L Thompson        qfs_so = common.load_qfs_so()
109*7b3ff069SJeremy L Thompson        file_dir = os.path.dirname(os.path.abspath(__file__))
110*7b3ff069SJeremy L Thompson
111*7b3ff069SJeremy L Thompson        qf_build = ceed.QFunction(1, qfs_so.build_diff,
112*7b3ff069SJeremy L Thompson                                  os.path.join(file_dir, "ex2-surface.h:build_diff"))
113*7b3ff069SJeremy L Thompson        qf_build.add_input("dx", dim * dim, libceed.EVAL_GRAD)
114*7b3ff069SJeremy L Thompson        qf_build.add_input("weights", 1, libceed.EVAL_WEIGHT)
115*7b3ff069SJeremy L Thompson        qf_build.add_output("qdata", num_q_comp, libceed.EVAL_NONE)
116*7b3ff069SJeremy L Thompson        qf_build.set_context(build_ctx)
117*7b3ff069SJeremy L Thompson
118*7b3ff069SJeremy L Thompson    # Operator for building quadrature data
119*7b3ff069SJeremy L Thompson    op_build = ceed.Operator(qf_build)
120*7b3ff069SJeremy L Thompson    op_build.set_field("dx", mesh_restriction, mesh_basis, libceed.VECTOR_ACTIVE)
121*7b3ff069SJeremy L Thompson    op_build.set_field("weights", libceed.ELEMRESTRICTION_NONE, mesh_basis, libceed.VECTOR_NONE)
122*7b3ff069SJeremy L Thompson    op_build.set_field("qdata", q_data_restriction, libceed.BASIS_NONE, libceed.VECTOR_ACTIVE)
123*7b3ff069SJeremy L Thompson
124*7b3ff069SJeremy L Thompson    # Compute quadrature data
125*7b3ff069SJeremy L Thompson    q_data = ceed.Vector(num_elem * elem_qpts * num_q_comp)
126*7b3ff069SJeremy L Thompson    op_build.apply(mesh_coords, q_data)
127*7b3ff069SJeremy L Thompson
128*7b3ff069SJeremy L Thompson    # Create the QFunction that defines the action of the diffusion operator
129*7b3ff069SJeremy L Thompson    qf_diff = None
130*7b3ff069SJeremy L Thompson    if args.gallery:
131*7b3ff069SJeremy L Thompson        qf_diff = ceed.QFunctionByName(f"Poisson{dim}DApply")
132*7b3ff069SJeremy L Thompson    else:
133*7b3ff069SJeremy L Thompson        build_ctx = ceed.QFunctionContext()
134*7b3ff069SJeremy L Thompson        ctx_data = np.array([dim, dim], dtype=np.int32)
135*7b3ff069SJeremy L Thompson        build_ctx.set_data(ctx_data)
136*7b3ff069SJeremy L Thompson
137*7b3ff069SJeremy L Thompson        qfs_so = common.load_qfs_so()
138*7b3ff069SJeremy L Thompson        file_dir = os.path.dirname(os.path.abspath(__file__))
139*7b3ff069SJeremy L Thompson
140*7b3ff069SJeremy L Thompson        qf_diff = ceed.QFunction(1, qfs_so.apply_diff,
141*7b3ff069SJeremy L Thompson                                 os.path.join(file_dir, "ex2-surface.h:apply_diff"))
142*7b3ff069SJeremy L Thompson        qf_diff.add_input("du", dim, libceed.EVAL_GRAD)
143*7b3ff069SJeremy L Thompson        qf_diff.add_input("qdata", num_q_comp, libceed.EVAL_NONE)
144*7b3ff069SJeremy L Thompson        qf_diff.add_output("dv", dim, libceed.EVAL_GRAD)
145*7b3ff069SJeremy L Thompson        qf_diff.set_context(build_ctx)
146*7b3ff069SJeremy L Thompson
147*7b3ff069SJeremy L Thompson    # Diffusion operator
148*7b3ff069SJeremy L Thompson    op_diff = ceed.Operator(qf_diff)
149*7b3ff069SJeremy L Thompson    op_diff.set_field("du", solution_restriction, solution_basis, libceed.VECTOR_ACTIVE)
150*7b3ff069SJeremy L Thompson    op_diff.set_field("qdata", q_data_restriction, libceed.BASIS_NONE, q_data)
151*7b3ff069SJeremy L Thompson    op_diff.set_field("dv", solution_restriction, solution_basis, libceed.VECTOR_ACTIVE)
152*7b3ff069SJeremy L Thompson
153*7b3ff069SJeremy L Thompson    # Create vectors
154*7b3ff069SJeremy L Thompson    u = ceed.Vector(sol_size)  # Input vector
155*7b3ff069SJeremy L Thompson    v = ceed.Vector(sol_size)  # Output vector
156*7b3ff069SJeremy L Thompson
157*7b3ff069SJeremy L Thompson    # Initialize u with sum of coordinates (x + y + z)
158*7b3ff069SJeremy L Thompson    with mesh_coords.array_read() as x_array, u.array_write() as u_array:
159*7b3ff069SJeremy L Thompson        for i in range(sol_size):
160*7b3ff069SJeremy L Thompson            u_array[i] = sum(x_array[i + j * (sol_size)] for j in range(dim))
161*7b3ff069SJeremy L Thompson
162*7b3ff069SJeremy L Thompson    # Apply operator: v = K * u
163*7b3ff069SJeremy L Thompson    op_diff.apply(u, v)
164*7b3ff069SJeremy L Thompson
165*7b3ff069SJeremy L Thompson    # Compute surface area by summing absolute values of v
166*7b3ff069SJeremy L Thompson    surface_area = 0.0
167*7b3ff069SJeremy L Thompson    with v.array_read() as v_array:
168*7b3ff069SJeremy L Thompson        surface_area = np.sum(abs(v_array))
169*7b3ff069SJeremy L Thompson
170*7b3ff069SJeremy L Thompson    if not args.test:
171*7b3ff069SJeremy L Thompson        print()
172*7b3ff069SJeremy L Thompson        print(f"Exact mesh surface area    : {exact_surface_area:.14g}")
173*7b3ff069SJeremy L Thompson        print(f"Computed mesh surface area : {surface_area:.14g}")
174*7b3ff069SJeremy L Thompson        print(f"Surface area error         : {surface_area - exact_surface_area:.14g}")
175*7b3ff069SJeremy L Thompson    else:
176*7b3ff069SJeremy L Thompson        # Test mode - check if error is within tolerance
177*7b3ff069SJeremy L Thompson        tol = 10000 * libceed.EPSILON if dim == 1 else 1e-1
178*7b3ff069SJeremy L Thompson        if abs(surface_area - exact_surface_area) > tol:
179*7b3ff069SJeremy L Thompson            print(f"Surface area error : {surface_area - exact_surface_area:.14g}")
180*7b3ff069SJeremy L Thompson            sys.exit(1)
181*7b3ff069SJeremy L Thompson
182*7b3ff069SJeremy L Thompson    return 0
183*7b3ff069SJeremy L Thompson
184*7b3ff069SJeremy L Thompson
185*7b3ff069SJeremy L Thompsonif __name__ == "__main__":
186*7b3ff069SJeremy L Thompson    sys.exit(main())
187