Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 131 additions & 41 deletions python/examples/elliptic1D.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,139 @@
SPDX-License-Identifier: GPL-3.0-or-later
© 2008-2024 San Diego State University Research Foundation (SDSURF).
See LICENSE file or https://www.gnu.org/licenses/gpl-3.0.html for details.

One-dimensional elliptic problem with Robin boundary conditions.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: it would be great to state the problem definition in this context (BC, rhs, etc.)

"""

import numpy as np
import sys
import shutil
import matplotlib.pyplot as plt

from pymole import Grid, Gradient, Divergence, Laplacian, RobinBoundaryCondition

west = 0 # Domain's limits
east = 1

k = 6 # Operator's order of accuracy
m = 2 * k + 1 # Minimum number of cells to attain the desired accuracy

grid = Grid.generate(west, east, shape=m + 1)

L = Laplacian(grid, accuracy_order=k).matrix

terminal_width, _ = shutil.get_terminal_size()
np.set_printoptions(linewidth=terminal_width, suppress=True)

BC = RobinBoundaryCondition(grid, k, dirichlet_coefficient=1.0, neumann_coefficient=1.0)
L_BC = L + BC.matrix

x = np.r_[
west,
np.arange(
west + grid.spacing / 2,
east - grid.spacing / 2 + grid.spacing / 2,
grid.spacing,
),
east,
]
U = np.exp(x)[:, None]
U[0] = 0 # West BC
U[-1] = 2 * np.exp(1) # East BC
U = np.linalg.inv(L_BC.toarray()) @ U

plt.plot(x, U, "o", label="Approximated")
plt.plot(x, np.exp(x), label="Analytical")
plt.legend(loc="upper left")
plt.title("Poisson's equation with Robin BC")
plt.xlabel("x")
plt.ylabel("u(x)")
plt.show()
from pymole import Grid, Laplacian, RobinBoundaryCondition


WEST = 0.0
EAST = 1.0
ACCURACY_ORDER = 6
NUM_CELLS = 13


def exact_solution(x):
"""return the analytical solution u(x) = exp(x)."""
#comparison of the numerical solution with the exact one
return np.exp(x)


def solve_problem(
num_cells=NUM_CELLS,
accuracy_order=ACCURACY_ORDER,
):
"""solve the one-dimensional elliptic problem."""
#the grid needs at least 2k+1 cells for the selected accuracy order
minimum_cells = 2 * accuracy_order + 1

if num_cells < minimum_cells:
raise ValueError(
f"At least {minimum_cells} cells are required "
f"for accuracy order {accuracy_order}."
)

#creation ofthe computational grid between west and east
grid = Grid.generate(
WEST,
EAST,
shape=num_cells + 1,
)

#creation of the discrete Laplacian operator
laplacian = Laplacian(
grid,
accuracy_order=accuracy_order,
).matrix

#Application of Robin boundary conditions at both ends of the domain
boundary_condition = RobinBoundaryCondition(
grid,
accuracy_order=accuracy_order,
dirichlet_coefficient=1.0,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: for consistency, define the Robin coefficients next to the other constants at the top. Something like:

WEST = 0.0
EAST = 1.0
ACCURACY_ORDER = 6
NUM_CELLS = 13
DIRICHLET_COEFFICIENT = 1.0
NEUMANN_COEFFICIENT = 1.0

neumann_coefficient=1.0,
)

#this is the matrix of the linear system that will be solved
system_matrix = (
laplacian + boundary_condition.matrix
).toarray()

#calculations of the locations of the cell centers
cell_centers = WEST + (
np.arange(num_cells) + 0.5
) * grid.spacing

#the full coordinate vector includes the two boundary points
x = np.concatenate(
([WEST], cell_centers, [EAST])
)

#the exact solution is also used to build the right-hand side
right_hand_side = exact_solution(x)

# Robin boundary conditions:
# u(0) - u'(0) = 0
# u(1) + u'(1) = 2e
right_hand_side[0] = 0.0
right_hand_side[-1] = 2.0 * np.exp(1.0)

#solve the system without explicitly calculating the inverse matrix
numerical_solution = np.linalg.solve(
system_matrix,
right_hand_side,
)

analytical_solution = exact_solution(x)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is minor, but the exact solution is computed twice. Compute it once and copy it for the RHS (https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
Copying the numpy object (https://numpy.org/doc/stable/reference/generated/numpy.copy.html) is faster than recomputing the analytical solution.

analytical_solution = exact_solution(x)
right_hand_side = np.copy(analytical_solution) # need a copy since rhs is modified afterwards
# now you can use/modify right_hand_side


return x, numerical_solution, analytical_solution


def plot_solution(
x,
numerical_solution,
analytical_solution,
):
"""plot the numerical and analytical solutions."""
#the markers show the values calculated by MOLE
plt.plot(
x,
numerical_solution,
"o",
label="Numerical",
)

#preparing the exact analytical solution
plt.plot(
x,
analytical_solution,
label="Analytical",
)

plt.legend()
plt.title("Poisson's equation with Robin boundary conditions")
plt.xlabel("x")
plt.ylabel("u(x)")
plt.grid(True)
plt.show()


def main():
"""solve the problem and display the results."""
#equation solution
x, numerical_solution, analytical_solution = solve_problem()

#plot both solutions for comparison
plot_solution(
x,
numerical_solution,
analytical_solution,
)


if __name__ == "__main__":
main()
Loading