Basic model tutorial#

In this tutorial you will learn the basics of the model interface for a simple inline Python model. The API for the model interface is documented in the romtools workflow model reference.

# First, import the relevant modules.
import numpy as np
from matplotlib import pyplot as plt
'''
Here, we will interface around a basic model for solving the 1D
advection-diffusion equation

    c u_x - nu u_xx = 1.
'''

class AdvectionDiffusionProblem:
    def __init__(self, nx):
        self.x = np.linspace(0, 1, nx)
        dx = 1.0 / (nx - 1)

        # Assemble diffusion and advection operators.
        self.Ad = np.zeros((nx, nx))
        self.Ad[0, 0] = -2.0 / dx**2
        self.Ad[0, 1] = 1.0 / dx**2
        self.Ad[-1, -1] = -2.0 / dx**2
        self.Ad[-1, -2] = 1.0 / dx**2
        for i in range(1, nx - 1):
            self.Ad[i, i] = -2.0 / dx**2
            self.Ad[i, i - 1] = 1.0 / dx**2
            self.Ad[i, i + 1] = 1.0 / dx**2

        self.Ac = np.zeros((nx, nx))
        self.Ac[0, 0] = 1.0 / dx
        for i in range(1, nx - 1):
            self.Ac[i, i] = 1.0 / dx
            self.Ac[i, i - 1] = -1.0 / dx

        self.f = np.ones(nx)

    def solve(self, c, nu):
        A = c * self.Ac - nu * self.Ad
        return np.linalg.solve(A, self.f)


problem = AdvectionDiffusionProblem(nx=33)
u = problem.solve(c=1.0, nu=1.0e-2)
plt.plot(problem.x, u)
plt.xlabel(r'$x$')
plt.ylabel(r'$u$');

A romtools model provides methods for populating a run directory and running the model for a parameter sample. For an inline Python model, the run-directory setup can be empty.

class AdrRomToolsModel:
    def __init__(self, problem: AdvectionDiffusionProblem):
        self.problem = problem

    def populate_run_directory(self, run_directory: str, parameter_sample: dict):
        # This inline model needs no offline data.
        pass

    def run_model(self, run_directory: str, parameter_sample: dict):
        c = parameter_sample['c']
        nu = parameter_sample['nu']
        self.problem.solve(c, nu)
        return 0


model = AdrRomToolsModel(problem)
assert model.run_model('.', {'c': 1.0, 'nu': 1.0e-2}) == 0