Elmerをコンパイルするシェルスクリプト

# 狙い
私の調べた範囲ですと、MMGが動作するのはElmer Virtual Machine（もしくは小生がElmer Discussion Forumに投稿したVirtual Machineのスクリプトから作成したWSL2のディストロ）があります。
ファイルサイズが７～10GB程度あり非常に大きいのと、必要なライブラリが分からないので使いやすい状況ではありませんでした。
Mmgを利用しているプロジェクトで有名なのは、ElmerとGmsh（どちらもFreeCADにデフォルトで入っています）と思います。
[Mmgを使用しているプロジェクト](https://www.mmgtools.org/projects-using-mmg "Projects using Mmg")
elmerfemソースコードのTesting、elmer-elmag、elmer-linsysにサンプルがあるので、最初の勉強用としてelmerを用いる敷居を下げたいと思い、スクリプトを整理しました。
[ElmerCSC-Github](https://github.com/ElmerCSC "ElmerCSC")
### 設定済ですぐに使えるWSLディストリビューションを準備したので、すぐに試されたい方はご利用ください。
# ビルドスクリプトとコマンド操作
### インストール環境の準備 (WSL2のDebian 12を想定)
元のスクリプトは、Ubuntu 22.04LTS用のものです。
また、WSLよりも通常のLinux環境の方が設定の問題が少ないと思います。
```
sudo nano /etc/wsl.conf
# Default user
[user]
default=elmeruser

# Do not append Windows PATH
[interop]
appendWindowsPath = false

sudo nano /etc/apt/sources.list
# add the “contrib”, “non-free”, and “non-free-firmware” repositories.

# Create Required Directories
mkdir ~/bin
mkdir ~/lib
mkdir ~/Source
sudo mkdir /opt/elmer && sudo chown elmeruser:elmeruser -Rf /opt/elmer
mkdir -p /opt/elmer/elmerdependencies/bin
mkdir /opt/elmer/elmerdependencies/lib

# Update PATH Environment Variables
nano ~/.bashrc
# Add custom directories to PATH and LD_LIBRARY_PATH
export PATH=$PATH:$HOME/bin:/opt/elmer/elmerdependencies/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/lib:/opt/elmer/elmerdependencies/lib

source ~/.bashrc
```
### Debianのリポジトリからパッケージをインストール
```
sudo apt install git
sudo apt install cmake build-essential gfortran libopenmpi-dev libblas-dev liblapack-dev intel-mkl # alternative of intel-mkl: libopenblas-dev
sudo apt install libqwt-qt5-dev
sudo apt install libqt5opengl5-dev
sudo apt install qtscript5-dev
sudo apt install libqt5svg5-dev
sudo apt install qtscript5-dev libqwt-qt5-dev
sudo apt install libmpich-dev libnetcdff-dev libmetis-dev libparmetis-dev libmumps-dev netcdf-bin
sudo apt install lua5.3
sudo apt install libhypre-dev paraview
cd ~/Source
git clone https://github.com/ElmerCSC/elmerfem.git
```
## ３種類のビルド用シェルスクリプトの実行
### ICStoolbox_install_script.sh (MMGのコンパイルに必要）
```sh:ICStoolbox_install_script.sh
#!/bin/bash
# Full ICStoolbox installation script
# Proceed with care ! Executing will erase every modification you made.
# 
# copy from https://github.com/ISCDtoolbox/Commons?tab=readme-ov-file
#           
#           Full ISCDtoolbox install
#           https://raw.githubusercontent.com/ISCDtoolbox/Commons/master/install.sh
#

set -e

#Cleaning
rm -rf ~/lib/libCommons.so
rm -rf ~/lib/libNavierStokes.so
rm -rf ~/lib/libElas.so
rm -rf ~/lib/libVelex.so
rm -rf ~/lib/libAdvection.so
rm -rf ~/bin/nstokes
rm -rf ~/bin/elastic
rm -rf ~/bin/advect
rm -rf ~/bin/velext

#Cloning
mkdir -p ~/dev/ICStoolbox
cd ~/dev/ICStoolbox
rm -rf Commons NavierStokes LinearElasticity Advection VelocityExtension
git clone https://github.com/ICStoolbox/Commons.git
git clone https://github.com/ICStoolbox/LinearElasticity.git
git clone https://github.com/ICStoolbox/NavierStokes.git
git clone https://github.com/ICStoolbox/Advection.git
git clone https://github.com/ICStoolbox/VelocityExtension.git

#Compiling
mkdir -p Commons/build
cd Commons/build
cmake .. 
make
make install
cd -

mkdir -p LinearElasticity/build
cd LinearElasticity/build
cmake ..
make
make install
cd -

mkdir -p NavierStokes/build
cd NavierStokes/build
cmake ..
make
make install
cd -

mkdir -p Advection/build
cd Advection/build
cmake ..
make
make install
cd -

mkdir -p VelocityExtension/build
cd VelocityExtension/build
cmake ..
make
make install
cd -

#Testing
elastic LinearElasticity/demos/3d/8branch
nstokes NavierStokes/demos/2d/cavity
velext VelocityExtension/demos/disk.mesh -o VelocityExtension/demos/disk.new.sol
#advect Advection/demos/2d/test.mesh -dt 0.001 -s Advection/demos/2d/test.sol -c Advection/demos/2d/test.chi.sol -o Advection/demos/2d/test.chi.sol

#Output
echo ""
echo "#################################"
echo "ICStoolbox successfully installed"
echo "#################################"
echo ""
```
### elmerdeps.sh : from Elmer Virtual Machine
```sh:elmerdeps.sh
#!/bin/bash
export CFLAGS="-fPIC  -O2"
export CC=gcc
git clone https://github.com/sakov/csa-c
cd csa-c/csa
./configure --prefix="/opt/elmer/elmerdependencies"
make -j $(nproc) install
make clean
cd ../..
git clone https://github.com/sakov/nn-c
cd nn-c/nn/
./configure --prefix="/opt/elmer/elmerdependencies"
mv makefile makefile.tmp
awk '/^CFLAGS_TRIANGLE/{gsub(/=/,"= -fPIC ")};{print}' makefile.tmp > makefile
rm -f makefile.tmp
make -j $(nproc) install
make clean
cd ../..
git clone https://github.com/MmgTools/mmg.git
cd mmg
#git reset --hard 565d6849
git checkout develop
mkdir build
cd build
cmake -D CMAKE_INSTALL_PREFIX="/opt/elmer/elmerdependencies" -D CMAKE_BUILD_TYPE=RelWithDebInfo -D BUILD_SHARED_LIBS:BOOL=TRUE -D MMG_INSTALL_PRIVATE_HEADERS=ON -D CMAKE_C_FLAGS="-fPIC  -g" -D CMAKE_CXX_FLAGS="-fPIC -std=c++11 -g"  ..
make -j $(nproc) install
cd ../..
git clone https://github.com/MmgTools/parmmg
cd parmmg
git checkout develop
mkdir build
cd build
cmake -D CMAKE_INSTALL_PREFIX="/opt/elmer/elmerdependencies" -D CMAKE_BUILD_TYPE=RelWithDebInfo -D BUILD_SHARED_LIBS:BOOL=TRUE -D DOWNLOAD_MMG=OFF  -D MMG_DIR="/opt/elmer/elmerdependencies"  ..
make -j $(nproc) install
cd ../..
```
### buildelmer.sh : from Elmer Virtual Machine
```sh:buildelmer.sh
#!/bin/bash
BRANCH="devel"
BASE=$PWD
ELMERSRC="$BASE/elmerfem"
if [[ ! -e ${ELMERSRC} ]]; then
    echo "source directory not found, cloning from GitHub"
    git clone https://github.com/ElmerCSC/elmerfem.git
    cd elmerfem
    git submodule update --init
    cd ..
else
    echo "source directory exists, just updating"
    cd elmerfem
    git pull
    git submodule update --init
    make clean
    cd ..
fi   

CMAKE=cmake

# own compilations needed for Elmer (exra script to run)
ELMERDEP="/opt/elmer/elmerdependencies/"

### hard-coding these - change if 
MUMPS_ROOT="/usr/lib/x86_64-linux-gnu/"
MUMPS_INC="/usr/include"
HYPRE_ROOT="/usr/lib/x86_64-linux-gnu"
HYPRE_INC="/usr/include/hypre"
NETCDF_ROOT="/usr/lib/x86_64-linux-gnu"
NETCDF_INC="/usr/include"

ls 
cd ${ELMERSRC}
echo "Elmer Source-dir:" $(pwd)
git checkout $BRANCH #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#git pull
git status
TIMESTAMP=$(date +"%m-%d-%y")
VERSION=$(git log -1 --pretty=format:%h)
#exit
ELMER_REV="Elmer_${BRANCH}_${VERSION}"
BUILDDIR="${BASE}/builddir_${BRANCH}_${VERSION}"
IDIR="/opt/elmer/${BRANCH}"
#PRECACHE="$BASE/debug.cmake"
echo "-------------------------------------"
echo "Building Elmer from source " ${ELMERSRC}
echo "within build directory " ${BUILDDIR}
#echo "using following toolchain file " ${TOOLCHAIN}
echo "installation into " ${IDIR}
echo "Elmer version is:" ${VERSION}
#echo "using pre-cache file"  ${PRECACHE}
echo "-------------------------------------"
LOGFILE="${BASE}/Logs/installation_${BRANCH}_${TIMESTAMP}.log"
echo "-------------------------------------" > ${LOGFILE}
echo "Building Elmer from source " ${ELMERSRC} >> ${LOGFILE}
echo "within build directory " ${BUILDDIR} >> ${LOGFILE}
#echo "using following toolchain file " ${TOOLCHAIN} >> ${LOGFILE}
echo "installation into " ${IDIR} >> ${LOGFILE}
echo "Elmer version is:" ${VERSION} >> ${LOGFILE}
#echo "using pre-cache file"  ${PRECACHE} >> ${LOGFILE}
echo "-------------------------------------" >> ${LOGFILE}

# Remove from cmake
# -DWITH_GridDataReader:BOOL=TRUE \
# -DWITH_OCC:BOOL=TRUE \
# -DWITH_VTK:BOOL=TURE \
# -DWITH_MKL:BOOL=TRUE \

# create new build-dir
echo "creating"  $BUILDDIR ":"
echo "-------------------------------------"
if [[ ! -e $BUILDDIR ]]; then
    mkdir -p $BUILDDIR
    cd ${BUILDDIR}
    pwd

    ls -ltr

    echo $CMAKE $ELMERSRC #-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN
    $CMAKE  $ELMERSRC \
           -DCMAKE_INSTALL_PREFIX=$IDIR \
           -DWITH_MPI:BOOL=TRUE \
           -DWITH_LUA:BOOL=TRUE \
           -DWITH_OpenMP:BOOL=TRUE \
           -DWITH_Mumps:BOOL=TRUE \
           -DMumps_LIBRARIES="${MUMPS_ROOT}/libpord.so;${MUMPS_ROOT}/libmumps_common.so;${MUMPS_ROOT}/libdmumps.so"\
           -DMumps_INCLUDE_DIR="${MUMPS_INC}" \
           -DWITH_Hypre:BOOL=TRUE \
           -DHypre_LIBRARIES="${HYPRE_ROOT}/libHYPRE.so" \
           -DHypre_INCLUDE_DIR="${HYPRE_INC}" \
           -DWITH_Trilinos:BOOL=FALSE \
           -DWITH_ElmerIce:BOOL=TRUE \
           -DWITH_Zoltan:BOOL=TRUE \
           -DWITH_MMG:BOOL=TRUE \
           -DMMG_INCLUDE_DIR="$ELMERDEP/include" \
           -DMMG_LIBRARY="$ELMERDEP/lib/libmmg.so" \
	   -DWITH_PARMMG:BOOL=TRUE \
           -DPARMMGROOT="$ELMERDEP" \
           -DWITH_NETCDF:BOOL=TRUE \
           -DWITH_ScatteredDataInterpolator:BOOL=TRUE \
           -DCSA_LIBRARY="$ELMERDEP/lib/libcsa.a" \
           -DCSA_INCLUDE_DIR="$ELMERDEP/include" \
           -DNN_INCLUDE_DIR="$ELMERDEP/include" \
           -DNN_LIBRARY="$ELMERDEP/lib/libnn.a" \
	   -DWITH_ELMERGUI:BOOL=TRUE \
           -DWITH_QT5:BOOL=TRUE \
           -DQWT_INCLUDE_DIR="/usr/include/qwt" \
           -DQWT_LIBRARY="/usr/lib/libqwt-qt5.so" \
           -DWITH_PARAVIEW:BOOL=TRUE \
           -DWITH_QWT:BOOL=TRUE \
           -DWITH_MATC:BOOL=FALSE \
           -DWITH_PYTHONQT:BOOL=FALSE \
           -DMPI_TEST_MAXPROC=2 \
	   -Wno-dev \
    |& tee -a ${LOGFILE}
elif [[ ! -d $dir ]]; then
    echo $BUILDDIR "exists - just updateing" 1>&2
    cd ${BUILDDIR}
    pwd
fi

echo "compiling and installing"
unbuffer make -j $(nproc) |& tee -a ${LOGFILE} && make install
# use this instead, if unbuffer not available (package expect on RHEL)
#make -j 4 |& tee -a ${LOGFILE} && make install

if  make install; then
    echo "${IDIR} has been installed"
    echo "${IDIR} has been installed" >> ${LOGFILE}
    echo "Testing installation"
    ctest -j $(nproc) -L quick|& tee -a ${LOGFILE}.ctest
    echo "to make disk space, remove build as well as source directory"
    echo "rm -fr  $BUILDDIR $ELMERSRC"
    cd $BASE
else
    echo "Compilation failed. ${IDIR} has NOT been installed"
    echo "Compilation failed. ${IDIR} has NOT been installed" >> ${LOGFILE}
    cd $BASE
fi
```
# Elmer on WSL2 – Ready to Use

*(Debian 12, Compiled: 2025-03-19, MMG, ParMMG, MUMPS, HYPRE, Lua, Zoltan)*

This WSL image contains the Elmer development version 9.0 (Rev: 4f69f075e, Compiled: 2025-03-19). It features ElmerGUI and Elmer/Ice functionality, and it is linked with MUMPS, Hypre, (Par)MMG, and Zoltan.

## Provided Scripts

In the `$HOME/Source` directory, three shell scripts are provided:

1. **ICStoolbox_install_script.sh**
   - Builds the basic library for MMG and ParMMG.
   - If the MPI settings are changed, a recompilation is required.

2. **elmerdeps.sh**
   - Builds and updates (Par)MMG.
   - The following versions are included in `/opt/elmer/elmerdependencies/bin`:
     - **MMG:** Release 5.8.0 (Oct. 30, 2024)
     - **ParMMG:** Release 1.5.0 (Nov. 01, 2024)

3. **buildelmer.sh**
   - Builds and updates Elmer.

## Installation Instructions
1. Download the following WSL2 distribution file* from my OneDrive.
   [ElmerWSL_Deb12_202503.zip](https://1drv.ms/u/c/ca3fad7a4b4217c1/EWMBXK6DuPJEqKfmEvr3zt0BCFrDRkJ6PX3MSY12qo1suQ?e=fdv8v6) 
2. Unzip the file `ElmerWSL_Deb12_202503.zip` to extract:
   - `ElmerWSL_Deb12_202503_build_by_Scripts.tar.gz`
   - `ReadMe1st.txt`
   - `ReadMe1st.md`

3. Import the tar.gz file using the following command:

   ```
                <DistroName> <InstallLocation>    <InstallTarFile>
   wsl --import ElmerWSL-2025 C:\ElmerWSL C:\path\to\downloaded\file\ElmerWSL_Deb12_202503_build_by_Scripts.tar.gz
    ```
   参考情報
    https://learn.microsoft.com/ja-jp/windows/wsl/use-custom-distro?form=MG0AV3

   ユーザー情報
    - user: "elmeruser"
    - password: "elmerfem"
    設定済ですのですぐに使用できます。パスワードが脆弱ですので、passwdコマンドにより早めに変更されることを推奨します。
    

#### 4. コンパイル後のテスト結果：412項目全てOKでした。
```
100% tests passed, 0 tests failed out of 412

Label Time Summary:
amr               =  16.57 sec*proc (7 tests)
aster             =   2.35 sec*proc (1 test)
block             =  29.47 sec*proc (12 tests)
cmodes            =  20.65 sec*proc (8 tests)
complex_eigen     =   5.09 sec*proc (2 tests)
constraint        =   2.35 sec*proc (1 test)
contact           =   9.61 sec*proc (4 tests)
control           =  21.48 sec*proc (9 tests)
cutfem            =  12.25 sec*proc (5 tests)
eigen             =  12.22 sec*proc (5 tests)
elasticity        =   7.49 sec*proc (3 tests)
elasticsolve      =  24.29 sec*proc (10 tests)
eliminate         =   2.34 sec*proc (1 test)
em-wave           =   2.52 sec*proc (1 test)
extrude           =   9.40 sec*proc (4 tests)
failing           =  10.24 sec*proc (4 tests)
fsi               =   2.55 sec*proc (1 test)
harmonic          =   7.27 sec*proc (3 tests)
heateq            =  18.35 sec*proc (8 tests)
helmholtz         =   9.68 sec*proc (4 tests)
hypre             =   3.43 sec*proc (2 tests)
lua               =  21.26 sec*proc (8 tests)
lumping           =  18.58 sec*proc (7 tests)
matc              =  42.47 sec*proc (17 tests)
mortar            =  30.74 sec*proc (12 tests)
n-t               =  17.68 sec*proc (7 tests)
namespace         =  12.00 sec*proc (5 tests)
p-fem             =  20.38 sec*proc (8 tests)
parallel          =   2.89 sec*proc (5 tests)
particle          =   9.60 sec*proc (4 tests)
plate             =   9.74 sec*proc (4 tests)
quick             = 1025.36 sec*proc (412 tests)
radiator          =  10.19 sec*proc (3 tests)
restart           =   2.73 sec*proc (1 test)
serendipity       =  54.38 sec*proc (21 tests)
serial            = 1022.47 sec*proc (407 tests)
shell             =  15.35 sec*proc (6 tests)
transient         =  35.00 sec*proc (14 tests)
umat              =   7.49 sec*proc (3 tests)
useextrude        =  32.66 sec*proc (13 tests)
vector_element    =  32.00 sec*proc (12 tests)
vtu               =   7.10 sec*proc (3 tests)
whitney           =  21.37 sec*proc (9 tests)

Total Test time (real) =  65.27 sec
to make disk space, remove build as well as source directory
rm -fr  /home/elmeruser/Source/builddir_devel_4f69f075e /home/elmeruser/Source/elmerfem
```


### 本件のElmer Forum（本家の英語サイト）へのリンク
[How to Build Elmer with MMG: Part 1 - Command-Line Operations](https://www.elmerfem.org/forum/viewtopic.php?t=8590)
[How to Build Elmer with MMG: Part 2 - Using a Ready-to-Use Elmer Setup on WSL2](https://www.elmerfem.org/forum/viewtopic.php?t=8591)

### ElmerGUIでのテスト状況
サンプルを用いた線形弾性解析![ElmerGUI-test-WSL2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/4014034/442e4fa8-905f-4fb1-be1a-1001d04aaf78.png)