Wells-Group / TEAM30

A repository for the TEAM-30 benchmark using DOLFINx
MIT License
5 stars 2 forks source link

pytest fails #36

Closed pemd-sys closed 1 year ago

pemd-sys commented 1 year ago

Hi I cloned the git repo and ran the docker container and then ran the pytest command, but it exited with errors. Can you please let me know what i can do to run the examples. Many thanks.


matrix@matrix-VirtualBox:~/Downloads$ git clone https://github.com/Wells-Group/TEAM30.git

Cloning into 'TEAM30'...

remote: Enumerating objects: 568, done.

remote: Counting objects: 100% (146/146), done.

remote: Compressing objects: 100% (110/110), done.

remote: Total 568 (delta 36), reused 60 (delta 24), pack-reused 422

Receiving objects: 100% (568/568), 168.84 KiB | 588.00 KiB/s, done.

Resolving deltas: 100% (332/332), done.

matrix@matrix-VirtualBox:~/Downloads$ docker run -ti -v $(pwd):/root/shared -w /root/shared/ --shm-size=512m --name=team30 ghcr.io/jorgensd/dolfinx_team30:v0.5.0.post0

root@fcde5b9ac435:~/shared# ls

TEAM30 fenics-tutorial-notebook test

root@fcde5b9ac435:~/shared# cd TEAM30/

root@fcde5b9ac435:~/shared/TEAM30# python3 -m pytest -xvs

=========================================================================================== test session starts ===========================================================================================

platform linux -- Python 3.10.4, pytest-7.1.3, pluggy-1.0.0 -- /usr/bin/python3

cachedir: .pytest_cache

rootdir: /root/shared/TEAM30

plugins: forked-1.4.0, xdist-2.5.0

collected 2 items

test_team30.py::test_team30[1-True]

Parametric sweep: 0%| | 0/10 [00:00<?, ?it/s]FAILED

================================================================================================ FAILURES =================================================================================================

___ test_team30[1-True] ___

single_phase = True, degree = 1

@pytest.mark.parametrize("single_phase", [True, False])

@pytest.mark.parametrize("degree", [1])

def test_team30(single_phase, degree):

    steps = 720  # Number of steps per phase

    rtol = 0.05  # Tolerance for relative tolerance compared to ref data

    atol = 1e-3

    num_phases = 6

    res = 0.001

    ext = "single" if single_phase else "three"

    outdir = f"Test_results_{ext}"

    os.system(f"mkdir -p {outdir}")

    fname = f"{outdir}/{ext}_phase"

    # Generate mesh

    generate_team30_mesh(fname, single=single_phase, res=res, L=1)

    convert_mesh(fname, "triangle", prune_z=True)

    convert_mesh(fname, "line", prune_z=True, ext="facets")

    # Open output file on rank 0

    output = None

    outfile = f"{outdir}/results_{ext}_{degree}.txt"

    if MPI.COMM_WORLD.rank == 0:

        output = open(outfile, "w")

        print("Speed, Torque, Torque_Arkkio, Voltage, Rotor_loss, Steel_loss, num_phases, "

              + "steps_per_phase, freq, degree, num_elements, num_dofs, single_phase", file=output)

    # Solve problem

    df = pandas.read_csv(f"ref_{ext}_phase.txt", delimiter=", ")

    speed = df["Speed"]

    progress = tqdm.tqdm(desc="Parametric sweep", total=len(speed))

    petsc_options = {"ksp_type": "preonly", "pc_type": "lu"}

    for omega in speed:

        ext = "single" if single_phase else "three"

        os.system(f"mkdir -p {outdir}")
      solve_team30(single_phase, num_phases, omega, degree, petsc_options=petsc_options, outdir=outdir,
                     steps_per_phase=steps, outfile=output, progress=False, mesh_dir=outdir)

test_team30.py:50:


single_phase = True, num_phases = 6, omega_u = 0.0, degree = 1, petsc_options = {'ksp_type': 'preonly', 'pc_type': 'lu'}, form_compiler_options = {}, jit_parameters = {}, apply_torque = False

T_ext = <function at 0x7f29b53be050>, outdir = 'Test_results_single', steps_per_phase = 720

outfile = <_io.TextIOWrapper name='Test_results_single/results_single_1.txt' mode='w' encoding='UTF-8'>, plot = False, progress = False, mesh_dir = 'Test_results_single', save_output = False

def solve_team30(single_phase: bool, num_phases: int, omega_u: np.float64, degree: np.int32, petsc_options: dict = {},

                 form_compiler_options: dict = {}, jit_parameters: dict = {}, apply_torque: bool = False,

                 T_ext: Callable[[float], float] = lambda t: 0, outdir: str = "results", steps_per_phase: int = 100,

                 outfile: Optional[Union[TextIOWrapper, TextIO]] = sys.stdout, plot: bool = False,

                 progress: bool = False, mesh_dir: str = "meshes", save_output: bool = False):

    """

    Solve the TEAM 30 problem for a single or three phase engine.

    Parameters

    ==========

    single_phase

        If true run the single phase model, otherwise run the three phase model

    num_phases

        Number of phases to run the simulation for

    omega_u

        Angular speed of rotor (Used as initial speed if apply_torque is True)

    degree

        Degree of magnetic vector potential functions space

    petsc_options

        Parameters that is passed to the linear algebra backend

        PETSc. For available choices for the 'petsc_options' kwarg,

        see the `PETSc-documentation

        <https://petsc4py.readthedocs.io/en/stable/manual/ksp/>`

    form_compiler_options

        Parameters used in FFCx compilation of this form. Run `ffcx --help` at

        the commandline to see all available options. Takes priority over all

        other parameter values, except for `scalar_type` which is determined by

        DOLFINx.

    jit_parameters

        Parameters used in CFFI JIT compilation of C code generated by FFCx.

        See `python/dolfinx/jit.py` for all available parameters.

        Takes priority over all other parameter values.

    apply_torque

        Boolean if torque should affect rotation. If True `omega_u` is ignored and T_ext

        is used as external forcing

    T_ex

        Lambda function for describing the external forcing as a function of time

    outdir

        Directory to put results in

    steps_per_phase

        Number of time steps per phase of the induction engine

    outfile

        File to write results to. (Default is print to terminal)

    plot

        Plot torque and voltage over time

    progress

        Show progress bar for solving in time

    mesh_dir

        Directory containing mesh

    save_output

        Save output to bp-files

    """

    freq = model_parameters["freq"]

    T = num_phases * 1 / freq

    dt_ = 1 / steps_per_phase * 1 / freq

    mu_0 = model_parameters["mu_0"]

    omega_J = 2 * np.pi * freq

    ext = "single" if single_phase else "three"

    fname = f"{mesh_dir}/{ext}_phase"

    domains, currents = domain_parameters(single_phase)

    # Read mesh and cell markers

    with io.XDMFFile(MPI.COMM_WORLD, f"{fname}.xdmf", "r") as xdmf:

        mesh = xdmf.read_mesh(name="Grid")

        ct = xdmf.read_meshtags(mesh, name="Grid")

    # Read facet tag

    tdim = mesh.topology.dim

    mesh.topology.create_connectivity(tdim - 1, 0)

    with io.XDMFFile(MPI.COMM_WORLD, f"{fname}_facets.xdmf", "r") as xdmf:

        ft = xdmf.read_meshtags(mesh, name="Grid")

    # Create DG 0 function for mu_R and sigma

    DG0 = fem.FunctionSpace(mesh, ("DG", 0))

    mu_R = fem.Function(DG0)

    sigma = fem.Function(DG0)

    density = fem.Function(DG0)

    for (material, domain) in domains.items():

        for marker in domain:

            cells = ct.find(marker)

            mu_R.x.array[cells] = model_parameters["mu_r"][material]

            sigma.x.array[cells] = model_parameters["sigma"][material]

            density.x.array[cells] = model_parameters["densities"][material]

    # Define problem function space

    cell = mesh.ufl_cell()

    FE = ufl.FiniteElement("Lagrange", cell, degree)

    ME = ufl.MixedElement([FE, FE])

    VQ = fem.FunctionSpace(mesh, ME)

    # Define test, trial and functions for previous timestep

    Az, V = ufl.TrialFunctions(VQ)

    vz, q = ufl.TestFunctions(VQ)

    AnVn = fem.Function(VQ)

    An, _ = ufl.split(AnVn)  # Solution at previous time step

    J0z = fem.Function(DG0)  # Current density

    # Create integration sets

    Omega_n = domains["Cu"] + domains["Stator"] + domains["Air"] + domains["AirGap"]

    Omega_c = domains["Rotor"] + domains["Al"]

    # Create integration measures

    dx = ufl.Measure("dx", domain=mesh, subdomain_data=ct)

    ds = ufl.Measure("ds", domain=mesh, subdomain_data=ft, subdomain_id=surface_map["Exterior"])

    # Define temporal and spatial parameters

    n = ufl.FacetNormal(mesh)

    dt = fem.Constant(mesh, dt_)

    x = ufl.SpatialCoordinate(mesh)

    omega = fem.Constant(mesh, PETSc.ScalarType(omega_u))

    # Define variational form

    a = dt / mu_R * ufl.inner(ufl.grad(Az), ufl.grad(vz)) * dx(Omega_n + Omega_c)

    a += dt / mu_R * vz * (n[0] * Az.dx(0) - n[1] * Az.dx(1)) * ds

    a += mu_0 * sigma * Az * vz * dx(Omega_c)

    a += dt * mu_0 * sigma * (V.dx(0) * q.dx(0) + V.dx(1) * q.dx(1)) * dx(Omega_c)

    L = dt * mu_0 * J0z * vz * dx(Omega_n)

    L += mu_0 * sigma * An * vz * dx(Omega_c)

    # Motion voltage term

    u = omega * ufl.as_vector((-x[1], x[0]))

    a += dt * mu_0 * sigma * ufl.dot(u, ufl.grad(Az)) * vz * dx(Omega_c)

    # Find all dofs in Omega_n for Q-space

    cells_n = np.hstack([ct.find(domain) for domain in Omega_n])

    Q, _ = VQ.sub(1).collapse()

    deac_dofs = fem.locate_dofs_topological((VQ.sub(1), Q), tdim, cells_n)

    # Create zero condition for V in Omega_n

    zeroQ = fem.Function(Q)

    zeroQ.x.array[:] = 0

    bc_Q = fem.dirichletbc(zeroQ, deac_dofs, VQ.sub(1))

    # Create external boundary condition for V space

    V_, _ = VQ.sub(0).collapse()

    tdim = mesh.topology.dim

    def boundary(x):

        return np.full(x.shape[1], True)

    boundary_facets = dolfinx.mesh.locate_entities_boundary(mesh, tdim - 1, boundary)

    bndry_dofs = fem.locate_dofs_topological((VQ.sub(0), V_), tdim - 1, boundary_facets)

    zeroV = fem.Function(V_)

    zeroV.x.array[:] = 0

    bc_V = fem.dirichletbc(zeroV, bndry_dofs, VQ.sub(0))

    bcs = [bc_V, bc_Q]

    # Create sparsity pattern and matrix with additional non-zeros on diagonal
  cpp_a = fem.form(a, form_compiler_options=form_compiler_options,
                     jit_options=jit_parameters)

E TypeError: form() got an unexpected keyword argument 'form_compiler_options'

team30_A_phi.py:192: TypeError

============================================================================================ warnings summary =============================================================================================

test_team30.py::test_team30[1-True]

/root/shared/TEAM30/test_team30.py:43: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.

df = pandas.read_csv(f"ref_{ext}_phase.txt", delimiter=", ")

test_team30.py::test_team30[1-True]

/usr/local/lib/python3.10/dist-packages/cffi/ffiplatform.py:10: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives

from distutils.core import Extension

test_team30.py::test_team30[1-True]

/usr/lib/python3.10/distutils/command/build_ext.py:13: DeprecationWarning: The distutils.sysconfig module is deprecated, use sysconfig instead

from distutils.sysconfig import customize_compiler, get_python_version

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

========================================================================================= short test summary info =========================================================================================

FAILED test_team30.py::test_team30[1-True] - TypeError: form() got an unexpected keyword argument 'form_compiler_options'

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

====================================================================================== 1 failed, 3 warnings in 7.57s ======================================================================================

Parametric sweep: 0%| | 0/10 [00:01<?, ?it/s]

jorgensd commented 1 year ago

This is probably because you are running against DOLFINx main. The current code is built against v0.5.2, which does not include https://github.com/FEniCS/dolfinx/pull/2310

This will be fixed at the next release (0.6.0 of DOLFINx).

For now, you can resolve this by changing form_compiler_params to form_compiler_options and jit_params to jit_options

pemd-sys commented 1 year ago

I ran the fenics docker with nightly build and ran the team30 code on it. it worked fine.

pemd-sys commented 1 year ago

Closed