#!/bin/bash

# Run python demos

set -e

# Tests real build by default.
# Access the complex build by setting env variable USE_DOLFINX_COMPLEX

if [ "x${USE_DOLFINX_COMPLEX}" != "x" ]; then
    TESTDIR_SUFFIX="-complex"
    TEST_DESCRIPTION="for complex build "
    export PETSC_DIR=/usr/lib/petscdir/petsc-complex
    # process ufl forms for complex test: second argument 1 indicates complex
    UFL_TYPE=1
else
    TESTDIR_SUFFIX="-real"
    export PETSC_DIR=/usr/lib/petsc
fi
export SLEPC_DIR=`grep wPETSC_DIR ${PETSC_DIR}/lib/petsc/conf/petscvariables | awk '{print $3}' | sed "s/petsc/slepc/g"`

# MPI tests are set up to run on no more than 3 processes
NPROC=$( nproc )
if [[ $NPROC > 2 ]]; then
  N_MPI=3
else
  N_MPI=2
fi
# and only 2 processes for unit tests
N_MPI_UNITTEST=2

export OMPI_MCA_plm_rsh_agent=/bin/false
export OMPI_MCA_rmaps_base_oversubscribe=1
export OMPI_MCA_btl_base_warn_component_unused=0

echo "== running python demos ${TEST_DESCRIPTION}=="
cd python/demo

# help CI tests run a little faster
export DOLFINX_JIT_CFLAGS="-g0 -O2"

# static-condensation-elasticity.py (mixed-elasticity-sc) uses numba
if ! dpkg-query -s python3-numba >/dev/null 2>&1; then
   SKIP_NUMBA_DEMO="condensation"
fi

TESTS_SKIPPED="cahn"
OTHER_TESTS_SKIPPED="gmsh"

MULTIPLE_SLOW_DEMO="hood"

for test in $SKIP_NUMBA_DEMO $MULTIPLE_SLOW_DEMO $EXTRA_SLOW_DEMO $OTHER_TESTS_SKIPPED; do
  TESTS_SKIPPED="$TESTS_SKIPPED or $test"
done
TEST_KEYWORDS="not ( $TESTS_SKIPPED )"

DEB_HOST_ARCH_BITS=$(dpkg-architecture -qDEB_HOST_ARCH_BITS)
if [ "x${DEB_HOST_ARCH_BITS}" = "x32" ] ; then
  MPI_DEMOS_SKIPPED="helmholtz condensation poisson"
fi
MPI_TESTS_SKIPPED=$TESTS_SKIPPED
for test in $MPI_DEMOS_SKIPPED; do
  MPI_TESTS_SKIPPED="$MPI_TESTS_SKIPPED or $test"
done
MPI_TEST_KEYWORDS="not ( $MPI_TESTS_SKIPPED )"


echo "=== python demo test (serial) ${TEST_DESCRIPTION}==="
python3 -m pytest -v --durations=20 -k "${TEST_KEYWORDS}" test.py

echo "=== python demo test (MPI using ${N_MPI} processors out of $NPROC)) ${TEST_DESCRIPTION}==="

# "-m mpi" refers to a custom pytest marker (not python module)
# and interferes with the pytest-mpi plugin, if installed.
# So explicitly switch off pytest-mpi (-p no:mpi, distinct from -m mpi)
# see https://github.com/FEniCS/dolfinx/issues/2254

python3 -m pytest -v -p no:mpi -m mpi --durations=20 -k "${MPI_TEST_KEYWORDS}" test.py --mpiexec=mpiexec --num-proc=${N_MPI}
