diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml index bdcfe1c9864..427cf21600b 100644 --- a/.azure-pipelines.yml +++ b/.azure-pipelines.yml @@ -13,6 +13,7 @@ pr: paths: exclude: - Docs + - '**/*.rst' jobs: - job: @@ -38,7 +39,6 @@ jobs: # Cartesian 3D cartesian_3d: WARPX_CMAKE_FLAGS: -DWarpX_DIMS=3 -DWarpX_FFT=ON -DWarpX_PYTHON=ON - WARPX_HEFFTE: 'TRUE' # Cylindrical RZ cylindrical_rz: WARPX_CMAKE_FLAGS: -DWarpX_DIMS=RZ -DWarpX_FFT=ON -DWarpX_PYTHON=ON @@ -66,18 +66,8 @@ jobs: cacheHitVar: CCACHE_CACHE_RESTORED displayName: Cache Ccache Objects - - task: Cache@2 - continueOnError: true - inputs: - key: 'Python3 | "$(System.JobName)" | .azure-pipelines.yml' - restoreKeys: | - Python3 | "$(System.JobName)" | .azure-pipelines.yml - path: /home/vsts/.local/lib/python3.8 - cacheHitVar: PYTHON38_CACHE_RESTORED - displayName: Cache Python Libraries - - bash: | - set -eu -o pipefail + set -o nounset errexit pipefail cat /proc/cpuinfo | grep "model name" | sort -u df -h echo 'Acquire::Retries "3";' | sudo tee /etc/apt/apt.conf.d/80-retries @@ -121,17 +111,6 @@ jobs: -DCMAKE_CXX_STANDARD=17 \ -Duse_cmake_find_lapack=ON -Dbuild_tests=OFF -DCMAKE_VERBOSE_MAKEFILE=ON fi - if [ "${WARPX_HEFFTE:-FALSE}" == "TRUE" ]; then - cmake-easyinstall --prefix=/usr/local git+https://github.com/icl-utk-edu/heffte.git@v2.4.0 \ - -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ - -DCMAKE_CXX_STANDARD=17 -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_ENABLE_FFTW=ON -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_CUDA=OFF -DHeffte_ENABLE_ROCM=OFF \ - -DHeffte_ENABLE_ONEAPI=OFF -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_PYTHON=OFF -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_MAGMA=OFF \ - -DCMAKE_VERBOSE_MAKEFILE=ON - fi # Python modules required for test analysis python3 -m pip install --upgrade -r Regression/requirements.txt python3 -m pip cache purge @@ -146,25 +125,50 @@ jobs: displayName: 'Install dependencies' - bash: | - set -eu -o pipefail + # set options + set -o nounset errexit pipefail + # display disk space usage df -h - # configure export AMReX_CMAKE_FLAGS="-DAMReX_ASSERTIONS=ON -DAMReX_TESTING=ON" - cmake -S . -B build \ - ${AMReX_CMAKE_FLAGS} \ - ${WARPX_CMAKE_FLAGS} \ - -DWarpX_TEST_CLEANUP=ON \ - -DWarpX_TEST_FPETRAP=ON - + export WARPX_TEST_FLAGS="-DWarpX_TEST_CLEANUP=ON -DWarpX_TEST_FPETRAP=ON -DWarpX_BACKTRACE_INFO=ON" + cmake -S . -B build \ + ${AMReX_CMAKE_FLAGS} \ + ${WARPX_CMAKE_FLAGS} \ + ${WARPX_TEST_FLAGS} # build cmake --build build -j 2 + # display disk space usage df -h displayName: 'Build' - bash: | - set -eu -o pipefail - - # run tests (exclude pytest.AMReX when running Python tests) - ctest --test-dir build --output-on-failure -E AMReX + # set options + set -o nounset errexit pipefail + # determine if the build was triggered by a push to the development branch + if [[ "$(Build.SourceBranch)" == "refs/heads/development" ]]; then + # run tests (exclude pytest.AMReX when running Python tests) + # and submit results to CDash as Experimental + ctest --test-dir build --output-on-failure -E AMReX \ + -D ExperimentalTest -D ExperimentalSubmit + else + # run tests (exclude pytest.AMReX when running Python tests) + ctest --test-dir build --output-on-failure -E AMReX + fi displayName: 'Test' + + - bash: | + # set options + set -o nounset errexit pipefail + # find and print backtrace + find build/bin/ -type f -name "Backtrace*" \ + -exec echo -e "\nBacktrace\n---------\n{}\n---------" \; \ + -exec cat {} \; + displayName: 'Logs' + condition: always() + + - bash: | + # clean out so the Post-job Cache "tar" command has more disk space available + rm -rf build + displayName: 'Clean Build Directory' + condition: always() diff --git a/.clang-tidy b/.clang-tidy index 04d1419c5c7..8111fc2fc25 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -19,6 +19,7 @@ Checks: ' -cppcoreguidelines-avoid-non-const-global-variables, -cppcoreguidelines-init-variables, -cppcoreguidelines-macro-usage, + -cppcoreguidelines-missing-std-forward, -cppcoreguidelines-narrowing-conversions, -cppcoreguidelines-non-private-member-variables-in-classes, -cppcoreguidelines-owning-memory, @@ -29,6 +30,7 @@ Checks: ' misc-*, -misc-no-recursion, -misc-non-private-member-variables-in-classes, + -misc-include-cleaner, modernize-*, -modernize-avoid-c-arrays, -modernize-return-braced-init-list, @@ -55,6 +57,9 @@ CheckOptions: value: "H," - key: modernize-pass-by-value.ValuesOnly value: "true" - +- key: misc-use-anonymous-namespace.HeaderFileExtensions + value: "H," +- key: performance-move-const-arg.CheckTriviallyCopyableMove + value: "false" HeaderFilterRegex: 'Source[a-z_A-Z0-9\/]+\.H$' diff --git a/.github/ISSUE_TEMPLATE/blank_issue.md b/.github/ISSUE_TEMPLATE/blank_issue.md new file mode 100644 index 00000000000..2d5216c8fc8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/blank_issue.md @@ -0,0 +1,14 @@ +--- +name: Blank issue +about: Ask us a question +labels: [question] +--- + +Are you here because you have something to report that is neither a bug, a new feature, nor an installation problem? + +Before opening this issue, consider opening a [discussion](https://github.com/ECP-WarpX/WarpX/discussions) instead! + +Issues are used to report bugs, installation problems or to request new features. +Discussions are used to ask more open-ended questions, brainstorm, ask our feedback, etc. + +You can find more details on how to use issues and discussions [here](https://github.com/ECP-WarpX/WarpX/blob/development/CONTRIBUTING.rst). diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000000..a5a64487646 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,58 @@ +--- +name: Bug report +about: Report a bug or unexpected behavior. +labels: [bug] +--- + +_Please remove any sensitive information (e.g., passwords, API keys) from your submission. +Please check the relevant boxes and fill in the specific versions or details for the relevant items. +Thank you for taking the time to report this issue. We will respond as soon as possible._ + +## Description +A clear and concise description of the bug. + +## Expected behavior +What did you expect to happen when you encountered the issue? + +## How to reproduce +Please provide (if available): +- WarpX inputs files +- PICMI Python files +- Python post-processing scripts + +If you are unable to provide certain files or scripts, please describe the steps you took to encounter the issue. + +Please minimize your inputs/scripts to be concise and focused on the issue. +For instance, make the simulation scripts as small and fast to run as possible. + +## System information +Please check all relevant boxes and provide details. + +- Operating system (name and version): + - [ ] Linux: e.g., Ubuntu 22.04 LTS + - [ ] macOS: e.g., macOS Monterey 12.4 + - [ ] Windows: e.g., Windows 11 Pro +- Version of WarpX: e.g., latest, 24.10, etc. +- Installation method: + - [ ] Conda + - [ ] Spack + - [ ] PyPI + - [ ] Brew + - [ ] From source with CMake + - [ ] Module system on an HPC cluster +- Other dependencies: yes/no, describe +- Computational resources: + - [ ] MPI: e.g., 2 MPI processes + - [ ] OpenMP: e.g., 2 OpenMP threads + - [ ] CPU: e.g., 2 CPUs + - [ ] GPU: e.g., 2 GPUs (NVIDIA, AMD, etc.) + +If you encountered the issue on an HPC cluster, please check our [HPC documentation](https://warpx.readthedocs.io/en/latest/install/hpc.html) to see if your HPC cluster is already supported. + +## Steps taken so far +What troubleshooting steps have you taken so far, and what were the results? + +Have you tried debugging the code, following the instructions in our [debugging documentation](https://warpx.readthedocs.io/en/latest/usage/workflows/debugging.html)? + +## Additional information +If applicable, please add any additional information that may help explain the issue, such as log files (e.g., build logs, error logs, etc.), error messages (e.g., compiler errors, runtime errors, etc.), screenshots, or other relevant details. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000000..3ba13e0cec6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000000..8e4630cc098 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,27 @@ +--- +name: Feature request +about: Suggest a new feature or enhancement. +labels: [enhancement] +--- + +_Please remove any sensitive information (e.g., passwords, API keys) from your submission. +Please check the relevant boxes and fill in the specific versions or details for the relevant items. +Thank you for taking the time to report this issue. We will respond as soon as possible._ + +## Context and motivation +Please provide a clear and concise description of the context that is prompting you to request a new feature. What problem are you trying to solve, and how will this feature help you achieve your goals? + +## Proposed feature +Describe the feature you would like to add to WarpX in detail. Please include: +- A clear and concise description of the feature +- Any relevant technical requirements or specifications +- How you envision the feature being used + +## Alternative solutions +Have you considered any alternative solutions or features that could achieve the same goal? If so, please describe them and explain why you believe the proposed feature is the best solution. + +## Additional information +If applicable, please provide any additional information that may be relevant to the feature request, such as: +- Links to existing codes or implementations +- References to relevant publications or research +- Any specific use cases or scenarios where the feature would be particularly useful diff --git a/.github/ISSUE_TEMPLATE/installation-issue.md b/.github/ISSUE_TEMPLATE/installation-issue.md new file mode 100644 index 00000000000..7cc937d91c0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/installation-issue.md @@ -0,0 +1,49 @@ +--- +name: Installation issue +about: Report an issue with installing or setting up WarpX. +labels: [install] +--- + +_Please remove any sensitive information (e.g., passwords, API keys) from your submission. +Please check the relevant boxes and fill in the specific versions or details for the relevant items. +Thank you for taking the time to report this issue. We will respond as soon as possible._ + +## Description +A clear and concise description of the issue. + +## System information +- Operating system (name and version): + - [ ] Linux: e.g., Ubuntu 22.04 LTS + - [ ] macOS: e.g., macOS Monterey 12.4 + - [ ] Windows: e.g., Windows 11 Pro +- Version of WarpX: e.g., latest, 24.10, etc. +- Installation method: + - [ ] Conda + - [ ] Spack + - [ ] PyPI + - [ ] Brew + - [ ] From source with CMake + - [ ] Module system on an HPC cluster +- Other dependencies: yes/no, describe +- Computational resources: + - [ ] CPU + - [ ] GPU: e.g., NVIDIA, AMD, etc. + +If you encountered the issue on an HPC cluster, please check our [HPC documentation](https://warpx.readthedocs.io/en/latest/install/hpc.html) to see if your HPC cluster is already supported. + +If you encountered the issue installing from source with CMake, please provide the output of the following steps: +1. buildsystem generation: output of `cmake --fresh -S . -B build` (include your specific build options, e.g., `-DWarpX_DIMS=3`) +2. project build: output of `cmake --build build` (include your specific build options, e.g., `-j 4`) + +If applicable, please add any additional information about your software environment: +- [ ] CMake: e.g., 3.24.0 +- [ ] C++ compiler: e.g., GNU 11.3 with NVCC 12.0.76 +- [ ] Python: e.g., CPython 3.12 +- [ ] MPI: e.g., OpenMPI 4.1.1 +- [ ] FFTW: e.g., 3.3.10 +- [ ] HDF5: e.g., 1.14.0 +- [ ] ADIOS2: e.g., 2.10.0 +- Other dependencies: yes/no, describe + +## Additional information +If applicable, please add any additional information that may help explain the issue, such as log files (e.g., build logs, error logs, etc.), error messages (e.g., compiler errors, runtime errors, etc.), screenshots, or other relevant details. diff --git a/.github/workflows/clang_sanitizers.yml b/.github/workflows/clang_sanitizers.yml index e89cb676a03..e0947916d3f 100644 --- a/.github/workflows/clang_sanitizers.yml +++ b/.github/workflows/clang_sanitizers.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-clangsanitizers @@ -15,8 +16,7 @@ concurrency: jobs: build_UB_sanitizer: name: Clang UB sanitizer - runs-on: ubuntu-22.04 - container: ubuntu:23.10 + runs-on: ubuntu-24.04 if: github.event.pull_request.draft == false env: CC: clang @@ -27,7 +27,7 @@ jobs: - uses: actions/checkout@v4 - name: install dependencies run: | - .github/workflows/dependencies/clang17.sh + .github/workflows/dependencies/clang.sh 17 - name: CCache Cache uses: actions/cache@v4 with: @@ -65,10 +65,6 @@ jobs: - name: run with UB sanitizer run: | - # We need these two lines because these tests run inside a docker container - export OMPI_ALLOW_RUN_AS_ROOT=1 - export OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 - export OMP_NUM_THREADS=2 #MPI implementations often leak memory @@ -81,9 +77,9 @@ jobs: build_thread_sanitizer: name: Clang thread sanitizer - runs-on: ubuntu-22.04 - container: ubuntu:23.10 - if: github.event.pull_request.draft == false + runs-on: ubuntu-24.04 + # TODO Fix data race conditions and re-enable job + if: 0 #github.event.pull_request.draft == false env: CC: clang CXX: clang++ @@ -93,7 +89,7 @@ jobs: - uses: actions/checkout@v4 - name: install dependencies run: | - .github/workflows/dependencies/clang17.sh + .github/workflows/dependencies/clang.sh 17 - name: CCache Cache uses: actions/cache@v4 with: @@ -149,10 +145,6 @@ jobs: export TSAN_OPTIONS='ignore_noninstrumented_modules=1' export ARCHER_OPTIONS="verbose=1" - # We need these two lines because these tests run inside a docker container - export OMPI_ALLOW_RUN_AS_ROOT=1 - export OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 - export OMP_NUM_THREADS=2 mpirun -n 2 ./build/bin/warpx.rz Examples/Physics_applications/laser_acceleration/inputs_base_rz warpx.serialize_initial_conditions = 0 diff --git a/.github/workflows/clang_tidy.yml b/.github/workflows/clang_tidy.yml index edb3e8b1988..49f2a5b6e25 100644 --- a/.github/workflows/clang_tidy.yml +++ b/.github/workflows/clang_tidy.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-clangtidy @@ -19,13 +20,13 @@ jobs: dim: [1, 2, RZ, 3] name: clang-tidy-${{ matrix.dim }}D runs-on: ubuntu-22.04 - timeout-minutes: 180 + timeout-minutes: 250 if: github.event.pull_request.draft == false steps: - uses: actions/checkout@v4 - name: install dependencies run: | - .github/workflows/dependencies/clang15.sh + .github/workflows/dependencies/clang.sh 17 - name: set up cache uses: actions/cache@v4 with: @@ -42,8 +43,8 @@ jobs: export CCACHE_LOGFILE=${{ github.workspace }}/ccache.log.txt ccache -z - export CXX=$(which clang++-15) - export CC=$(which clang-15) + export CXX=$(which clang++-17) + export CC=$(which clang-17) cmake -S . -B build_clang_tidy \ -DCMAKE_VERBOSE_MAKEFILE=ON \ @@ -61,7 +62,7 @@ jobs: ${{github.workspace}}/.github/workflows/source/makeMakefileForClangTidy.py --input ${{github.workspace}}/ccache.log.txt make -j4 --keep-going -f clang-tidy-ccache-misses.mak \ - CLANG_TIDY=clang-tidy-15 \ + CLANG_TIDY=clang-tidy-17 \ CLANG_TIDY_ARGS="--config-file=${{github.workspace}}/.clang-tidy --warnings-as-errors=*" ccache -s diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 1a89f6668d5..30e4adf1b51 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-cuda @@ -55,23 +56,13 @@ jobs: which nvcc || echo "nvcc not in PATH!" cmake-easyinstall --prefix=/usr/local \ - git+https://github.com/openPMD/openPMD-api.git@0.15.1 \ + git+https://github.com/openPMD/openPMD-api.git@0.16.1 \ -DopenPMD_USE_PYTHON=OFF \ -DBUILD_TESTING=OFF \ -DBUILD_EXAMPLES=OFF \ -DBUILD_CLI_TOOLS=OFF \ -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ -DCMAKE_VERBOSE_MAKEFILE=ON - cmake-easyinstall --prefix=/usr/local \ - git+https://github.com/icl-utk-edu/heffte.git@v2.4.0 \ - -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ - -DCMAKE_CXX_STANDARD=17 -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_ENABLE_FFTW=OFF -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_CUDA=ON -DHeffte_ENABLE_ROCM=OFF \ - -DHeffte_ENABLE_ONEAPI=OFF -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_PYTHON=OFF -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_MAGMA=OFF \ - -DCMAKE_VERBOSE_MAKEFILE=ON - name: build WarpX run: | export CCACHE_COMPRESS=1 @@ -92,7 +83,6 @@ jobs: -DWarpX_openpmd_internal=OFF \ -DWarpX_PRECISION=SINGLE \ -DWarpX_FFT=ON \ - -DWarpX_HEFFTE=ON \ -DAMReX_CUDA_ERROR_CROSS_EXECUTION_SPACE_CALL=ON \ -DAMReX_CUDA_ERROR_CAPTURE_THIS=ON cmake --build build_sp -j 4 @@ -137,7 +127,7 @@ jobs: which nvcc || echo "nvcc not in PATH!" git clone https://github.com/AMReX-Codes/amrex.git ../amrex - cd ../amrex && git checkout --detach 92679babfc2cc66ca06ee591a80001db57c89878 && cd - + cd ../amrex && git checkout --detach 044d52f7d309e340939d7cae449fd83209da317f && cd - make COMP=gcc QED=FALSE USE_MPI=TRUE USE_GPU=TRUE USE_OMP=FALSE USE_FFT=TRUE USE_CCACHE=TRUE -j 4 ccache -s diff --git a/.github/workflows/dependencies/clang17.sh b/.github/workflows/dependencies/clang.sh similarity index 58% rename from .github/workflows/dependencies/clang17.sh rename to .github/workflows/dependencies/clang.sh index d208a9f3f3b..3ffe6dbc675 100755 --- a/.github/workflows/dependencies/clang17.sh +++ b/.github/workflows/dependencies/clang.sh @@ -1,50 +1,50 @@ #!/usr/bin/env bash # -# Copyright 2024 The WarpX Community +# Copyright 2025 The WarpX Community # # License: BSD-3-Clause-LBNL -# Authors: Luca Fedeli set -eu -o pipefail -# This dependency file is currently used within a docker container, -# which does not come with sudo. -apt-get -qqq update -apt-get -y install sudo - -# `man apt.conf`: -# Number of retries to perform. If this is non-zero APT will retry -# failed files the given number of times. +# `man apt.conf`: number of retries to perform (if non-zero, +# APT will retry failed files the given number of times). echo 'Acquire::Retries "3";' | sudo tee /etc/apt/apt.conf.d/80-retries -# This dependency file is currently used within a docker container, -# which does not come (among others) with wget, xz-utils, curl, git, -# ccache, and pkg-config pre-installed. -sudo apt-get -qqq update +sudo apt-get update sudo apt-get install -y \ cmake \ - clang-17 \ - clang-tidy-17 \ libblas-dev \ - libc++-17-dev \ libboost-math-dev \ libfftw3-dev \ libfftw3-mpi-dev \ libhdf5-openmpi-dev \ liblapack-dev \ libopenmpi-dev \ - libomp-17-dev \ - ninja-build \ - wget \ - xz-utils \ - curl \ - git \ - ccache \ - pkg-config + ninja-build + +# parse clang version number from command line +version_number=${1} + +# add LLVM repository and install clang tools +wget https://apt.llvm.org/llvm.sh +chmod +x llvm.sh +sudo ./llvm.sh ${version_number} + +# install clang, clang-tidy, and +# LLVM implementations of C++ standard library and OpenMP +sudo apt-get update +sudo apt-get install -y \ + clang-${version_number} \ + clang-tidy-${version_number} \ + libc++-${version_number}-dev \ + libomp-${version_number}-dev + +# export compiler flags +export CXX=$(which clang++-${version_number}) +export CC=$(which clang-${version_number}) -# Use clang 17 -export CXX=$(which clang++-17) -export CC=$(which clang-17) +# ccache +$(dirname "$0")/ccache.sh # cmake-easyinstall # diff --git a/.github/workflows/dependencies/clang15.sh b/.github/workflows/dependencies/clang15.sh deleted file mode 100755 index 63d5d70956f..00000000000 --- a/.github/workflows/dependencies/clang15.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# -# Copyright 2023 The WarpX Community -# -# License: BSD-3-Clause-LBNL -# Authors: Luca Fedeli - -set -eu -o pipefail - -# `man apt.conf`: -# Number of retries to perform. If this is non-zero APT will retry -# failed files the given number of times. -echo 'Acquire::Retries "3";' | sudo tee /etc/apt/apt.conf.d/80-retries - -sudo apt-get -qqq update -sudo apt-get install -y \ - cmake \ - clang-15 \ - clang-tidy-15 \ - libblas-dev \ - libc++-15-dev \ - libboost-math-dev \ - libfftw3-dev \ - libfftw3-mpi-dev \ - libhdf5-openmpi-dev \ - liblapack-dev \ - libopenmpi-dev \ - libomp-15-dev \ - ninja-build - -# ccache -$(dirname "$0")/ccache.sh - -# cmake-easyinstall -# -sudo curl -L -o /usr/local/bin/cmake-easyinstall https://raw.githubusercontent.com/ax3l/cmake-easyinstall/main/cmake-easyinstall -sudo chmod a+x /usr/local/bin/cmake-easyinstall -export CEI_SUDO="sudo" -export CEI_TMP="/tmp/cei" - -# BLAS++ & LAPACK++ -cmake-easyinstall \ - --prefix=/usr/local \ - git+https://github.com/icl-utk-edu/blaspp.git \ - -Duse_openmp=OFF \ - -Dbuild_tests=OFF \ - -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ - -DCMAKE_VERBOSE_MAKEFILE=ON - -cmake-easyinstall \ - --prefix=/usr/local \ - git+https://github.com/icl-utk-edu/lapackpp.git \ - -Duse_cmake_find_lapack=ON \ - -Dbuild_tests=OFF \ - -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ - -DCMAKE_VERBOSE_MAKEFILE=ON diff --git a/.github/workflows/dependencies/hip.sh b/.github/workflows/dependencies/hip.sh index 2a1b4d090bc..e07349ce63f 100755 --- a/.github/workflows/dependencies/hip.sh +++ b/.github/workflows/dependencies/hip.sh @@ -28,7 +28,9 @@ sudo apt-key add rocm.gpg.key source /etc/os-release # set UBUNTU_CODENAME: focal or jammy or ... -echo "deb [arch=amd64] https://repo.radeon.com/rocm/apt/${1-latest} ${UBUNTU_CODENAME} main" \ +VERSION=${1-6.3.2} + +echo "deb [arch=amd64] https://repo.radeon.com/rocm/apt/${VERSION} ${UBUNTU_CODENAME} main" \ | sudo tee /etc/apt/sources.list.d/rocm.list echo 'export PATH=/opt/rocm/llvm/bin:/opt/rocm/bin:/opt/rocm/profiler/bin:/opt/rocm/opencl/bin:$PATH' \ | sudo tee -a /etc/profile.d/rocm.sh @@ -50,11 +52,16 @@ sudo apt-get install -y --no-install-recommends \ libzstd-dev \ ninja-build \ openmpi-bin \ - rocm-dev \ - rocfft-dev \ - rocprim-dev \ - rocrand-dev \ - hiprand-dev + rocm-dev${VERSION} \ + roctracer-dev${VERSION} \ + rocprofiler-dev${VERSION} \ + rocrand-dev${VERSION} \ + rocfft-dev${VERSION} \ + rocprim-dev${VERSION} \ + rocsparse-dev${VERSION} + +# hiprand-dev is a new package that does not exist in old versions +sudo apt-get install -y --no-install-recommends hiprand-dev${VERSION} || true # ccache $(dirname "$0")/ccache.sh @@ -68,27 +75,9 @@ which clang++ export CXX=$(which clang++) export CC=$(which clang) -# "mpic++ --showme" forgets open-pal in Ubuntu 20.04 + OpenMPI 4.0.3 -# https://bugs.launchpad.net/ubuntu/+source/openmpi/+bug/1941786 -# https://github.com/open-mpi/ompi/issues/9317 -export LDFLAGS="-lopen-pal" - # cmake-easyinstall # sudo curl -L -o /usr/local/bin/cmake-easyinstall https://raw.githubusercontent.com/ax3l/cmake-easyinstall/main/cmake-easyinstall sudo chmod a+x /usr/local/bin/cmake-easyinstall export CEI_SUDO="sudo" export CEI_TMP="/tmp/cei" - -# heFFTe -# -cmake-easyinstall --prefix=/usr/local \ - git+https://github.com/icl-utk-edu/heffte.git@v2.4.0 \ - -DCMAKE_CXX_COMPILER_LAUNCHER=$(which ccache) \ - -DCMAKE_CXX_STANDARD=17 -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_ENABLE_FFTW=OFF -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_CUDA=OFF -DHeffte_ENABLE_ROCM=ON \ - -DHeffte_ENABLE_ONEAPI=OFF -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_PYTHON=OFF -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_MAGMA=OFF \ - -DCMAKE_VERBOSE_MAKEFILE=ON diff --git a/.github/workflows/dependencies/icc.sh b/.github/workflows/dependencies/icc.sh index fae6e22d45a..63763421d31 100755 --- a/.github/workflows/dependencies/icc.sh +++ b/.github/workflows/dependencies/icc.sh @@ -58,7 +58,7 @@ export CEI_TMP="/tmp/cei" CXX=$(which icpc) CC=$(which icc) \ cmake-easyinstall \ --prefix=/usr/local \ - git+https://github.com/openPMD/openPMD-api.git@0.15.2 \ + git+https://github.com/openPMD/openPMD-api.git@0.16.1 \ -DopenPMD_USE_PYTHON=OFF \ -DBUILD_TESTING=OFF \ -DBUILD_EXAMPLES=OFF \ diff --git a/.github/workflows/dependencies/nvcc11-3.sh b/.github/workflows/dependencies/nvcc11-3.sh index 92e2717e425..050b58b5947 100755 --- a/.github/workflows/dependencies/nvcc11-3.sh +++ b/.github/workflows/dependencies/nvcc11-3.sh @@ -41,7 +41,8 @@ sudo apt-get install -y \ cuda-nvml-dev-11-3 \ cuda-nvtx-11-3 \ libcufft-dev-11-3 \ - libcurand-dev-11-3 + libcurand-dev-11-3 \ + libcusparse-dev-11-3 sudo ln -s cuda-11.3 /usr/local/cuda # if we run out of temporary storage in CI: diff --git a/.github/workflows/dependencies/nvcc11-8.sh b/.github/workflows/dependencies/nvcc11-8.sh index 6089360392b..608f6c7a817 100755 --- a/.github/workflows/dependencies/nvcc11-8.sh +++ b/.github/workflows/dependencies/nvcc11-8.sh @@ -41,7 +41,8 @@ sudo apt-get install -y \ cuda-nvml-dev-11-8 \ cuda-nvtx-11-8 \ libcufft-dev-11-8 \ - libcurand-dev-11-8 + libcurand-dev-11-8 \ + libcusparse-dev-11-8 sudo ln -s cuda-11.8 /usr/local/cuda # if we run out of temporary storage in CI: diff --git a/.github/workflows/hip.yml b/.github/workflows/hip.yml index 8ba39de7742..cf679f67ca7 100644 --- a/.github/workflows/hip.yml +++ b/.github/workflows/hip.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-hip @@ -15,7 +16,7 @@ concurrency: jobs: build_hip_3d_sp: name: HIP 3D SP - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 env: CXXFLAGS: "-Werror -Wno-deprecated-declarations -Wno-error=pass-failed" CMAKE_GENERATOR: Ninja @@ -24,7 +25,7 @@ jobs: - uses: actions/checkout@v4 - name: install dependencies shell: bash - run: .github/workflows/dependencies/hip.sh + run: .github/workflows/dependencies/hip.sh 6.3.2 - name: CCache Cache uses: actions/cache@v4 with: @@ -47,11 +48,6 @@ jobs: export CXX=$(which clang++) export CC=$(which clang) - # "mpic++ --showme" forgets open-pal in Ubuntu 20.04 + OpenMPI 4.0.3 - # https://bugs.launchpad.net/ubuntu/+source/openmpi/+bug/1941786 - # https://github.com/open-mpi/ompi/issues/9317 - export LDFLAGS="-lopen-pal" - cmake -S . -B build_sp \ -DCMAKE_VERBOSE_MAKEFILE=ON \ -DAMReX_AMD_ARCH=gfx900 \ @@ -61,8 +57,7 @@ jobs: -DWarpX_MPI=ON \ -DWarpX_OPENPMD=ON \ -DWarpX_PRECISION=SINGLE \ - -DWarpX_FFT=ON \ - -DWarpX_HEFFTE=ON + -DWarpX_FFT=ON cmake --build build_sp -j 4 export WARPX_MPI=OFF @@ -75,7 +70,7 @@ jobs: build_hip_2d_dp: name: HIP 2D DP - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 env: CXXFLAGS: "-Werror -Wno-deprecated-declarations -Wno-error=pass-failed" CMAKE_GENERATOR: Ninja @@ -84,7 +79,7 @@ jobs: - uses: actions/checkout@v4 - name: install dependencies shell: bash - run: .github/workflows/dependencies/hip.sh + run: .github/workflows/dependencies/hip.sh 6.3.2 - name: CCache Cache uses: actions/cache@v4 with: @@ -107,11 +102,6 @@ jobs: export CXX=$(which clang++) export CC=$(which clang) - # "mpic++ --showme" forgets open-pal in Ubuntu 20.04 + OpenMPI 4.0.3 - # https://bugs.launchpad.net/ubuntu/+source/openmpi/+bug/1941786 - # https://github.com/open-mpi/ompi/issues/9317 - export LDFLAGS="-lopen-pal" - cmake -S . -B build_2d \ -DCMAKE_VERBOSE_MAKEFILE=ON \ -DAMReX_AMD_ARCH=gfx900 \ @@ -122,8 +112,7 @@ jobs: -DWarpX_MPI=ON \ -DWarpX_OPENPMD=ON \ -DWarpX_PRECISION=DOUBLE \ - -DWarpX_FFT=ON \ - -DWarpX_HEFFTE=ON + -DWarpX_FFT=ON cmake --build build_2d -j 4 export WARPX_MPI=OFF diff --git a/.github/workflows/insitu.yml b/.github/workflows/insitu.yml index 50b482d28d3..3d3942174a7 100644 --- a/.github/workflows/insitu.yml +++ b/.github/workflows/insitu.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-insituvis diff --git a/.github/workflows/intel.yml b/.github/workflows/intel.yml index 9b98c6e5990..25819e188e3 100644 --- a/.github/workflows/intel.yml +++ b/.github/workflows/intel.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-intel diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 0ddfcf38b41..87482cc6166 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-macos diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index bbe20679781..d657daf5793 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-ubuntu diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ae4843e0536..7f964239a02 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -7,6 +7,7 @@ on: pull_request: paths-ignore: - "Docs/**" + - "**.rst" concurrency: group: ${{ github.ref }}-${{ github.head_ref }}-windows diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 27065ac5ca3..f3ccdcbc635 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -69,7 +69,7 @@ repos: # Python: Ruff linter & formatter # https://docs.astral.sh/ruff/ - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.1 + rev: v0.9.9 hooks: # Run the linter - id: ruff diff --git a/CMakeLists.txt b/CMakeLists.txt index c08c72489cb..bb3ee66f786 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ # Preamble #################################################################### # cmake_minimum_required(VERSION 3.24.0) -project(WarpX VERSION 24.10) +project(WarpX VERSION 25.02) include(${WarpX_SOURCE_DIR}/cmake/WarpXFunctions.cmake) @@ -73,7 +73,6 @@ option(WarpX_LIB "Build WarpX as a library" OFF) option(WarpX_MPI "Multi-node support (message-passing)" ON) option(WarpX_OPENPMD "openPMD I/O (HDF5, ADIOS)" ON) option(WarpX_FFT "FFT-based solvers" OFF) -option(WarpX_HEFFTE "Multi-node FFT-based solvers" OFF) option(WarpX_PYTHON "Python bindings" OFF) option(WarpX_SENSEI "SENSEI in situ diagnostics" OFF) option(WarpX_QED "QED support (requires PICSAR)" ON) @@ -82,14 +81,22 @@ option(WarpX_QED_TABLE_GEN "QED table generation (requires PICSAR and Boost)" option(WarpX_QED_TOOLS "Build external tool to generate QED lookup tables (requires PICSAR and Boost)" OFF) -# Advanced option to automatically clean up CI test directories -option(WarpX_TEST_CLEANUP "Clean up CI test directories" OFF) +# Advanced option to run tests +option(WarpX_TEST_CLEANUP "Clean up automated test directories" OFF) +option(WarpX_TEST_DEBUGGER "Run automated tests without AMReX signal handling (to attach debuggers)" OFF) +option(WarpX_TEST_FPETRAP "Run automated tests with FPE-trapping runtime parameters" OFF) mark_as_advanced(WarpX_TEST_CLEANUP) - -# Advanced option to run CI tests with FPE-trapping runtime parameters -option(WarpX_TEST_FPETRAP "Run CI tests with FPE-trapping runtime parameters" OFF) +mark_as_advanced(WarpX_TEST_DEBUGGER) mark_as_advanced(WarpX_TEST_FPETRAP) +# Advanced option to compile with the -g1 option for minimal debug symbols +# (useful to see, e.g., line numbers in backtraces) +option(WarpX_BACKTRACE_INFO "Compile with -g1 for minimal debug symbols (currently used in CI tests)" OFF) +mark_as_advanced(WarpX_BACKTRACE_INFO) +if(WarpX_BACKTRACE_INFO) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g1") +endif() + set(WarpX_DIMS_VALUES 1 2 3 RZ) set(WarpX_DIMS 3 CACHE STRING "Simulation dimensionality <1;2;3;RZ>") list(REMOVE_DUPLICATES WarpX_DIMS) @@ -139,10 +146,6 @@ mark_as_advanced(WarpX_MPI_THREAD_MULTIPLE) option(WarpX_amrex_internal "Download & build AMReX" ON) -if(WarpX_HEFFTE AND NOT WarpX_MPI) - message(FATAL_ERROR "WarpX_HEFFTE (${WarpX_HEFFTE}) can only be used if WarpX_MPI is ON.") -endif() - # change the default build type to Release (or RelWithDebInfo) instead of Debug set_default_build_type("Release") @@ -190,12 +193,9 @@ option(ABLASTR_FFT "compile AnyFFT wrappers" ${WarpX_FFT}) if(WarpX_FFT) set(ABLASTR_FFT ON CACHE STRING "FFT-based solvers" FORCE) endif() -option(ABLASTR_HEFFTE "compile AnyFFT wrappers" ${WarpX_HEFFTE}) -if(WarpX_HEFFTE) - set(ABLASTR_HEFFTE ON CACHE STRING "Multi-Node FFT-based solvers" FORCE) -endif() -# this defined the variable BUILD_TESTING which is ON by default +# Define the variable BUILD_TESTING (ON by default), +# include CDash dashboard testing module include(CTest) @@ -235,23 +235,6 @@ if(WarpX_FFT) endif() endif() -# multi-node FFT -if(WarpX_HEFFTE) - if(WarpX_COMPUTE STREQUAL CUDA) - set(_heFFTe_COMPS CUDA) - elseif(WarpX_COMPUTE STREQUAL HIP) - set(_heFFTe_COMPS ROCM) - elseif(WarpX_COMPUTE STREQUAL SYCL) - set(_heFFTe_COMPS ONEAPI) - else() # NOACC, OMP - set(_heFFTe_COMPS FFTW) # or MKL - endif() - # note: we could also enforce GPUAWARE for CUDA and HIP, which can still be - # disabled at runtime - - find_package(Heffte REQUIRED COMPONENTS ${_heFFTe_COMPS}) -endif() - # Python if(WarpX_PYTHON) find_package(Python 3.8 COMPONENTS Interpreter Development.Module REQUIRED) @@ -492,10 +475,6 @@ foreach(D IN LISTS WarpX_DIMS) endif() endif() - if(ABLASTR_HEFFTE) - target_link_libraries(ablastr_${SD} PUBLIC Heffte::Heffte) - endif() - if(WarpX_PYTHON) target_link_libraries(pyWarpX_${SD} PRIVATE pybind11::module pybind11::windows_extras) if(WarpX_PYTHON_IPO) @@ -503,7 +482,7 @@ foreach(D IN LISTS WarpX_DIMS) warpx_enable_IPO(pyWarpX_${SD}) else() # conditionally defined target in pybind11 - # https://github.com/pybind/pybind11/blob/v2.12.0/tools/pybind11Common.cmake#L397-L403 + # https://github.com/pybind/pybind11/blob/v2.13.0/tools/pybind11Common.cmake#L407-L413 target_link_libraries(pyWarpX_${SD} PRIVATE pybind11::lto) endif() endif() @@ -586,13 +565,6 @@ foreach(D IN LISTS WarpX_DIMS) target_compile_definitions(ablastr_${SD} PUBLIC ABLASTR_USE_FFT) endif() - if(WarpX_HEFFTE) - target_compile_definitions(ablastr_${SD} PUBLIC WARPX_USE_HEFFTE) - endif() - if(ABLASTR_HEFFTE) - target_compile_definitions(ablastr_${SD} PUBLIC ABLASTR_USE_HEFFTE) - endif() - if(WarpX_PYTHON AND pyWarpX_VERSION_INFO) # for module __version__ target_compile_definitions(pyWarpX_${SD} PRIVATE diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 77b8200b0d5..3affc9f4aaa 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -12,6 +12,36 @@ Git workflow The WarpX project uses `git `_ for version control. If you are new to git, you can follow `this tutorial `__. + +What to do when +^^^^^^^^^^^^^^^ + +Issues +"""""" + +`Issues `__ are used to track tasks that the contributors and/or maintainers can work on. +Use issues for reporting bugs or installation problems and for requesting new features. + +If you've found a bug and wish to report it, first search the open issues and `pull requests `__ to see if someone else has already reported the same thing. +If it's something new, open an issue using a template. +We'll use the issue to address the problem you've encountered. + +Discussions +""""""""""" + +`Discussions `__ are for open-ended conversations, general questions, brainstorming ideas. +Please, use discussions if you want to ask us something that is not technically a bug or a feature. +Feel free to ping us there! + +Pull Requests (PRs) +""""""""""""""""""" + +Open a `pull request `__ if you want to add a new feature yourself. +Follow the guide below for more details. + + +Thank you for contributing! 🥰 + Configure your GitHub Account & Development Machine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/CTestConfig.cmake b/CTestConfig.cmake new file mode 100644 index 00000000000..8af4cb36ac1 --- /dev/null +++ b/CTestConfig.cmake @@ -0,0 +1,20 @@ +## This file should be placed in the root directory of your project. +## Then modify the CMakeLists.txt file in the root directory of your +## project to incorporate the testing dashboard. +## +## # The following are required to submit to the CDash dashboard: +## ENABLE_TESTING() +## INCLUDE(CTest) + +set(CTEST_PROJECT_NAME WarpX) +set(CTEST_NIGHTLY_START_TIME 08:00:00 UTC) + +set(CTEST_SUBMIT_URL https://my.cdash.org/submit.php?project=WarpX) + +set(CTEST_DROP_SITE_CDASH TRUE) + +# Set site and build names +# - CTest script variables: CTEST_SITE, CTEST_BUILD_NAME +# - CTest module variables: SITE, BUILDNAME +set(SITE "Azure-Pipelines") +set(BUILDNAME "CI-Development") diff --git a/Docs/requirements.txt b/Docs/requirements.txt index 7581638551e..14d07e29f6e 100644 --- a/Docs/requirements.txt +++ b/Docs/requirements.txt @@ -13,7 +13,7 @@ openpmd-viewer # for checksumAPI # PICMI API docs # note: keep in sync with version in ../requirements.txt -picmistandard==0.31.0 +picmistandard==0.33.0 # for development against an unreleased PICMI version, use: # picmistandard @ git+https://github.com/picmi-standard/picmi.git#subdirectory=PICMI_Python @@ -27,5 +27,6 @@ sphinx-copybutton sphinx-design sphinx_rtd_theme>=1.1.1 sphinxcontrib-bibtex +sphinxcontrib-googleanalytics sphinxcontrib-napoleon yt # for checksumAPI diff --git a/Docs/source/acknowledge_us.rst b/Docs/source/acknowledge_us.rst index 8c9b8dcf15c..f648e9c1bbd 100644 --- a/Docs/source/acknowledge_us.rst +++ b/Docs/source/acknowledge_us.rst @@ -23,7 +23,7 @@ Please add the following sentence to your publications, it helps contributors ke **Plain text:** - This research used the open-source particle-in-cell code WarpX https://github.com/ECP-WarpX/WarpX. Primary WarpX contributors are with LBNL, LLNL, CEA-LIDYL, SLAC, DESY, CERN, and TAE Technologies. We acknowledge all WarpX contributors. + This research used the open-source particle-in-cell code WarpX https://github.com/ECP-WarpX/WarpX. Primary WarpX contributors are with LBNL, LLNL, CEA-LIDYL, SLAC, DESY, CERN, Helion Energy, and TAE Technologies. We acknowledge all WarpX contributors. **LaTeX:** @@ -31,7 +31,7 @@ Please add the following sentence to your publications, it helps contributors ke \usepackage{hyperref} This research used the open-source particle-in-cell code WarpX \url{https://github.com/ECP-WarpX/WarpX}. - Primary WarpX contributors are with LBNL, LLNL, CEA-LIDYL, SLAC, DESY, CERN, and TAE Technologies. + Primary WarpX contributors are with LBNL, LLNL, CEA-LIDYL, SLAC, DESY, CERN, Helion Energy, and TAE Technologies. We acknowledge all WarpX contributors. .. _acknowledge_warpx_ref: diff --git a/Docs/source/conf.py b/Docs/source/conf.py index c1ad43197c5..a5fed3a4614 100644 --- a/Docs/source/conf.py +++ b/Docs/source/conf.py @@ -56,8 +56,13 @@ "sphinx_design", "breathe", "sphinxcontrib.bibtex", + "sphinxcontrib.googleanalytics", ] +# Google Analytics +googleanalytics_id = "G-QZGY5060MZ" +googleanalytics_enabled = True + # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] @@ -107,9 +112,9 @@ def __init__(self, *args, **kwargs): # built documents. # # The short X.Y version. -version = "24.10" +version = "25.02" # The full version, including alpha/beta/rc tags. -release = "24.10" +release = "25.02" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/Docs/source/dataanalysis/workflows.rst b/Docs/source/dataanalysis/workflows.rst index dc611b00e53..ab4ca88ddab 100644 --- a/Docs/source/dataanalysis/workflows.rst +++ b/Docs/source/dataanalysis/workflows.rst @@ -1,7 +1,8 @@ +.. _dataanalysis-how-to: .. _dataanalysis-workflows: -Workflows -========= +How-To Guides +============= This section collects typical user workflows and best practices for data analysis with WarpX. diff --git a/Docs/source/developers/checksum.rst b/Docs/source/developers/checksum.rst index ccbea3408ef..1e71ee3ddae 100644 --- a/Docs/source/developers/checksum.rst +++ b/Docs/source/developers/checksum.rst @@ -22,11 +22,6 @@ This relies on the function ``evaluate_checksum``: .. autofunction:: checksumAPI.evaluate_checksum -Here's an example: - -.. literalinclude:: ../../../Examples/Tests/embedded_circle/analysis.py - :language: python - This can also be included as part of an existing analysis script. How to evaluate checksums from the command line diff --git a/Docs/source/developers/fields.rst b/Docs/source/developers/fields.rst index 9d980119814..ee782570bad 100644 --- a/Docs/source/developers/fields.rst +++ b/Docs/source/developers/fields.rst @@ -119,9 +119,9 @@ Bilinear filter The multi-pass bilinear filter (applied on the current density) is implemented in ``Source/Filter/``, and class ``WarpX`` holds an instance of this class in member variable ``WarpX::bilinear_filter``. For performance reasons (to avoid creating too many guard cells), this filter is directly applied in communication routines, see ``WarpX::AddCurrentFromFineLevelandSumBoundary`` above and -.. doxygenfunction:: WarpX::ApplyFilterJ(const amrex::Vector, 3>> ¤t, int lev, int idim) +.. doxygenfunction:: WarpX::ApplyFilterMF(const ablastr::fields::MultiLevelVectorField &mfvec, int lev, int idim) -.. doxygenfunction:: WarpX::SumBoundaryJ(const amrex::Vector, 3>> ¤t, int lev, int idim, const amrex::Periodicity &period) +.. doxygenfunction:: WarpX::SumBoundaryJ(const ablastr::fields::MultiLevelVectorField ¤t, int lev, int idim, const amrex::Periodicity &period) Godfrey's anti-NCI filter for FDTD simulations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/Docs/source/developers/gnumake/openpmd.rst b/Docs/source/developers/gnumake/openpmd.rst index 3215c9461a1..0497ecf044b 100644 --- a/Docs/source/developers/gnumake/openpmd.rst +++ b/Docs/source/developers/gnumake/openpmd.rst @@ -9,7 +9,7 @@ therefore we recommend to use `spack `__ in order to facilitate the installation. More specifically, we recommend that you try installing the -`openPMD-api library 0.15.1 or newer `__ +`openPMD-api library 0.16.1 or newer `__ using spack (first section below). If this fails, a back-up solution is to install parallel HDF5 with spack, and then install the openPMD-api library from source. diff --git a/Docs/source/developers/gnumake/python.rst b/Docs/source/developers/gnumake/python.rst index 543b80d5ddd..06dbd5ac737 100644 --- a/Docs/source/developers/gnumake/python.rst +++ b/Docs/source/developers/gnumake/python.rst @@ -3,7 +3,7 @@ Installing WarpX as a Python package ==================================== -A full Python installation of WarpX can be done, which includes a build of all of the C++ code, or a pure Python version can be made which only installs the Python scripts. WarpX requires Python version 3.8 or newer. +A full Python installation of WarpX can be done, which includes a build of all of the C++ code, or a pure Python version can be made which only installs the Python scripts. WarpX requires Python version 3.9 or newer. For a full Python installation of WarpX --------------------------------------- diff --git a/Docs/source/developers/local_compile.rst b/Docs/source/developers/how_to_compile_locally.rst similarity index 99% rename from Docs/source/developers/local_compile.rst rename to Docs/source/developers/how_to_compile_locally.rst index 8bfa033a92d..9fc1b397b78 100644 --- a/Docs/source/developers/local_compile.rst +++ b/Docs/source/developers/how_to_compile_locally.rst @@ -1,7 +1,7 @@ .. _developers-local-compile: -Fast, Local Compilation -======================= +How to compile locally and fast +=============================== For simplicity, WarpX :ref:`compilation with CMake ` by default downloads, configures and compiles compatible versions of :ref:`central dependencies ` such as: diff --git a/Docs/source/developers/how_to_guides.rst b/Docs/source/developers/how_to_guides.rst new file mode 100644 index 00000000000..25ed4f2d30d --- /dev/null +++ b/Docs/source/developers/how_to_guides.rst @@ -0,0 +1,13 @@ +.. _development-howtoguides: + +How-To Guides +============= + +.. toctree:: + :maxdepth: 1 + + how_to_profile + how_to_test + how_to_run_clang_tidy + how_to_compile_locally + how_to_write_the_docs diff --git a/Docs/source/developers/profiling.rst b/Docs/source/developers/how_to_profile.rst similarity index 99% rename from Docs/source/developers/profiling.rst rename to Docs/source/developers/how_to_profile.rst index 5acea786920..e756d8362c2 100644 --- a/Docs/source/developers/profiling.rst +++ b/Docs/source/developers/how_to_profile.rst @@ -1,7 +1,7 @@ .. _developers-profiling: -Profiling the Code -================== +How to profile the code +======================= Profiling allows us to find the bottle-necks of the code as it is currently implemented. Bottle-necks are the parts of the code that may delay the simulation, making it more computationally expensive. diff --git a/Docs/source/developers/how_to_run_clang_tidy.rst b/Docs/source/developers/how_to_run_clang_tidy.rst new file mode 100644 index 00000000000..bbcd7b80130 --- /dev/null +++ b/Docs/source/developers/how_to_run_clang_tidy.rst @@ -0,0 +1,51 @@ +.. _developers-run_clang_tidy_locally: + +How to run the clang-tidy linter +================================ + +WarpX's CI tests include several checks performed with the `clang-tidy `__ linter. +The complete list of checks performed is defined in the ``.clang-tidy`` configuration file. + +.. dropdown:: clang-tidy configuration file + :color: light + :icon: info + :animate: fade-in-slide-down + + .. literalinclude:: ../../../.clang-tidy + :language: yaml + +Under `Tools/Linter `__, the script ``runClangTidy.sh`` can be used to run the clang-tidy linter locally. + +.. dropdown:: clang-tidy local run script + :color: light + :icon: info + :animate: fade-in-slide-down + + .. literalinclude:: ../../../Tools/Linter/runClangTidy.sh + :language: bash + +It is a prerequisite that WarpX is compiled following the instructions that you find in our :ref:`Users ` or :ref:`Developers ` sections. + +The script generates a wrapper to ensure that clang-tidy is only applied to WarpX source files and compiles WarpX in 1D, 2D, 3D, and RZ geometry, using such wrapper. + +By default WarpX is compiled in single precision with PSATD solver, QED module, QED table generator and embedded boundary in order to ensure broader coverage with the clang-tidy tool. + +Few optional environment variables can be set to tune the behavior of the script: + +* ``WARPX_TOOLS_LINTER_PARALLEL``: set the number of cores used for compilation; + +* ``CLANG``, ``CLANGXX``, and ``CLANGTIDY``: set the version of the compiler and the linter. + +For continuous integration we currently use clang version 15.0.0 and it is recommended to use this version locally as well. +A newer version may find issues not currently covered by CI tests (checks are opt-in), while older versions may not find all the issues. + +Here's an example of how to run the script after setting the appropriate environment variables: + +.. code-block:: bash + + export WARPX_TOOLS_LINTER_PARALLEL=12 + export CLANG=clang-15 + export CLANGXX=clang++-15 + export CLANGTIDY=clang-tidy-15 + + ./Tools/Linter/runClangTidy.sh diff --git a/Docs/source/developers/how_to_test.rst b/Docs/source/developers/how_to_test.rst new file mode 100644 index 00000000000..12dc653ac61 --- /dev/null +++ b/Docs/source/developers/how_to_test.rst @@ -0,0 +1,254 @@ +.. _developers-testing: + +How to test the code +==================== + +When you propose code changes, you want to make sure that + +* the code changes do not break the behavior of the rest of the code; +* the code changes give correct results (numerics, physics, etc.). + +Following the continuous integration (CI) software development practice, WarpX runs automated builds and tests after a commit is pushed to an open PR as well as after a PR is merged into the main branch. + +How to run pre-commit tests locally +----------------------------------- + +First, WarpX uses `pre-commit `__ to perform automated style and correctness checks. + +Here is how to install ``pre-commit`` locally: + +#. Install ``pre-commit``: + + .. code-block:: sh + + python -m pip install -U pre-commit + +#. Install the git hook scripts: + + .. code-block:: sh + + pre-commit install + +If you install ``pre-commit`` locally, the style and correctness checks will run automatically on your computer, after you commit the code changes and before you push them to the remote repository. + +If you do not install ``pre-commit`` locally, these checks will run automatically as part of our CI workflows and a commit containing style and correctness changes might be added automatically to your branch after you have pushed your own commit. +In that case, you will need to pull that automated commit before pushing further commits. + +The configuration options for ``pre-commit`` are set in the `pre-commit-config.yaml `__ file. + +How to configure the automated tests +------------------------------------ + +Our regression tests are run with `CTest `__, an executable that comes with CMake. + +The test suite is ready to run once you have configured and built WarpX with CMake, following the instructions that you find in our :ref:`Users ` or :ref:`Developers ` sections. + +A test that requires a build option that was not configured and built will be skipped automatically. For example, if you configure and build WarpX in 1D only, any test of dimensionality other than 1D, which would require WarpX to be configured and built in the corresponding dimensionality, will be skipped automatically. + +How to run automated tests locally +---------------------------------- + +Once your code changes are ready, there are ways to check that they do not break the rest of the code. +WarpX has automated tests running every time a commit is pushed to an open pull request. +The input files and scripts used by the automated tests can be found in the `Examples `__ directory, either under `Physics_applications `__ or `Tests `__. + +For easier debugging, it can be convenient to run the tests on your local computer by executing CTest as illustrated in the examples below (where we assume that WarpX was configured and built in the directory ``build``): + +* List tests available for the current build options: + + .. code-block:: sh + + ctest --test-dir build -N + +* Run tests available for the current build options: + + .. code-block:: sh + + ctest --test-dir build + +* Run tests available for the current build options in parallel (while preserving existing dependencies between tests): + + .. code-block:: sh + + ctest --test-dir build -j 2 + +* Run tests available for the current build options and output anything outputted by the test program if the test should fail: + + .. code-block:: sh + + ctest --test-dir build --output-on-failure + +* Run tests available for the current build options with verbose output: + + .. code-block:: sh + + ctest --test-dir build --verbose + +* Run tests matching the regular expression ``laser_acceleration``: + + .. code-block:: sh + + ctest --test-dir build -R laser_acceleration + +* Run tests except those matching the regular expression ``laser_acceleration``: + + .. code-block:: sh + + ctest --test-dir build -E laser_acceleration + +* Sometimes two or more tests share a large number of input parameters and differ by a small set of options. + Such tests typically also share a base string in their names. + For example, you can find three different tests named ``test_3d_langmuir_multi``, ``test_3d_langmuir_multi_nodal`` and ``test_3d_langmuir_multi_picmi``. + In such a case, if you wish to run the test ``test_3d_langmuir_multi`` only, this can be done again with the ``-R`` regular `expression filter `__ via + + .. code-block:: sh + + ctest --test-dir build -R "test_3d_langmuir_multi\..*" + + Note that filtering with ``-R "test_3d_langmuir_multi"`` would include the additional tests that have the same substring in their name and would not be sufficient to isolate a single test. + Note also that the escaping ``\.`` in the regular expression is necessary in order to take into account the fact that each test is automatically appended with the strings ``.run``, ``.analysis``, ``.checksum`` and possibly ``.cleanup``. + +* Run only tests not labeled with the ``slow`` label: + + .. code-block:: sh + + ctest --test-dir build -LE slow + +Once the execution of CTest is completed, you can find all files associated with each test in its corresponding directory under ``build/bin/``. +For example, if you run the single test ``test_3d_laser_acceleration``, you can find all files associated with this test in the directory ``build/bin/test_3d_laser_acceleration/``. + +If you modify the code base locally and want to assess the effects of your code changes on the automated tests, you need to first rebuild WarpX including your code changes and then rerun CTest. + +How to add automated tests +-------------------------- + +An automated test typically consists of the following components: + +* input file or PICMI input script; + +* analysis script; + +* checksum file. + +As mentioned above, the input files and scripts used by the automated tests can be found in the `Examples `__ directory, under either `Physics_applications `__ or `Tests `__. + +Each test directory must contain a file named ``CMakeLists.txt`` where all tests associated with the input files and scripts in that directory must be listed. + +A checksum file is a file that contains reference values obtained by computing a chosen checksum for a set of fields. +More precisely, we compute the sums of the absolute values of the arrays corresponding to each field from the results produced by the automated test and compare these checksums with the reference ones stored in the checksum file of that test, with respect to specific tolerances. +This is expected to be sensitive enough to make the automated test fail if the code changes cause significant differences in the final results, thus catching possible bugs. + +A new test can be added by calling the function ``add_warpx_test`` in ``CMakeLists.txt``. The function has the following signature: + +.. code-block:: cmake + + function(add_warpx_test + name # unique test name: + # test_1d_example, test_2d_example_picmi, etc. + dims # dimensionality: 1, 2, 3, RZ + nprocs # number of processes: 1, 2 + inputs # inputs file or PICMI script: + # inputs_test_1d_example, inputs_test_2d_example_picmi.py, "inputs_test_2d_example_picmi.py arg1 arg2", etc. + analysis # custom test analysis command: + # OFF, "analysis.py", "analysis.py arg1 arg2", etc. + checksum # default regression analysis command: + # OFF, "analysis_default_regression.py --path diags/diag1", etc. + dependency # name of base test that must run first (must match name exactly): + # OFF, test_1d_example_prepare, etc. + ) + +Here's how to add an automated test: + +#. Choose the test directory, either an existing one or a new one. + +#. Add an input file or PICMI input script. + The name must follow the naming conventions described in the section :ref:`developers-testing-naming` below. + +#. Add a Python analysis script to analyze the results of the test. + +#. Add the test to the ``CMakeLists.txt`` file (add such file if you are adding the test in a new test directory) using the function ``add_warpx_test`` mentioned above. + +#. If the test directory is new, add the directory with the command ``add_subdirectory`` in `Physics_applications/CMakeLists.txt `__ or `Tests/CMakeLists.txt `__, depending on where the test directory is located. + +#. If the test directory is new, make a symbolic link to the default regression analysis script ``analysis_default_regression.py`` from `Examples/analysis_default_regression.py `__, by running ``ln -s ../../analysis_default_regression.py analysis_default_regression.py`` from the test directory. + +#. Run the test locally with ``ctest``, after setting the environment variable ``CHECKSUM_RESET=ON``, in order to generate automatically the checksum file. + +Once you have added the test, run the test locally again, after resetting ``CHECKSUM_RESET=OFF``, to check that everything works as expected. + +The ``analysis`` and ``checksum`` commands passed as arguments to ``add_warpx_test`` can be set to ``OFF`` if the intention is to skip the respective analysis for a given test. + +If you need a new Python package dependency for testing, please add it in `Regression/requirements.txt `__. + +Sometimes two or more tests share a large number of input parameters. +The shared input parameters can be collected in a "base" input file that can be passed as a runtime parameter in the actual test input files through the parameter ``FILE``. + +Here is the help message of the default regression analysis script, including usage and list of available options and arguments: + + .. code-block:: bash + + usage: analysis_default_regression.py [-h] [--path PATH] [--rtol RTOL] [--skip-fields] [--skip-particles] + options: + -h, --help show this help message and exit + --path PATH path to output file(s) + --rtol RTOL relative tolerance to compare checksums + --skip-fields skip fields when comparing checksums + --skip-particles skip particles when comparing checksums + +How to reset checksums locally +------------------------------ + +It is possible to reset a checksum file locally by running the corresponding test with ``ctest`` with the environment variable ``CHECKSUM_RESET=ON``. For example: + + .. code-block:: bash + + CHECKSUM_RESET=ON ctest --test-dir build -R laser_acceleration + +Alternatively, it is also possible to reset multiple checksum files using the output of our Azure pipelines, which can be useful for code changes that result in resetting a large numbers of checksum files. +Here's how to do so: + +#. On the GitHub page of the pull request, find (one of) the pipeline(s) failing due to checksum regressions and click on "Details" (highlighted in blue). + + .. figure:: https://gist.github.com/user-attachments/assets/09db91b9-5711-4250-8b36-c52a6049e38e + +#. In the new page that opens up, click on "View more details on Azure pipelines" (highlighted in blue). + + .. figure:: https://gist.github.com/user-attachments/assets/ab0c9a24-5518-4da7-890f-d79fa1c8de4c + +#. In the new page that opens up, select the group of tests for which you want to reset the checksum files (e.g., ``cartesian_3d``) and click on "View raw log". + + .. figure:: https://gist.github.com/user-attachments/assets/06c1fe27-2c13-4bd3-b6b8-8b8941b37889 + +#. Save the raw log as a text file on your computer. + +#. Go to the directory `Tools/DevUtils `__ and run the Python script `update_benchmarks_from_azure_output.py `__ passing the path of the raw log text file as a command line argument: + + .. code:: bash + + python update_benchmarks_from_azure_output.py path/to/raw_log.txt + + This will update the checksum files for all the tests in the raw log that did not pass the checksum analysis. + +.. _developers-testing-naming: + +Naming conventions for automated tests +-------------------------------------- + +Note that we currently obey the following snake\_case naming conventions for test names and test input files (which make automation tasks easier, e.g., parsing visually, parsing through code, sorting alphabetically, filtering tests in CTest via ``-R``, etc.): + +#. **Regular test names** start with the string ``test_1d_``, ``test_2d_``, ``test_3d_`` or ``test_rz_``, followed by a string that is descriptive of the test. For example, ``test_3d_laser_acceleration``. + +#. **PICMI test names** start with the string ``test_1d_``, ``test_2d_``, ``test_3d_`` or ``test_rz_``, followed by a string that is descriptive of the test, and end with the string ``_picmi``. For example, ``test_3d_laser_acceleration_picmi``. + +#. **Restart test names** end with the string ``_restart``. For example, ``test_3d_laser_acceleration_restart``. + +#. **Test input files** start with the string ``inputs_`` followed by the test name. For example, ``inputs_test_3d_laser_acceleration`` or ``inputs_test_3d_laser_acceleration_picmi.py`` or ``inputs_test_3d_laser_acceleration_restart``. + +#. **Base input files** (that is, files collecting input parameters shared between two or more tests) are typically named ``inputs_base_1d``, ``inputs_base_2d``, ``inputs_base_3d`` or ``inputs_base_rz``, possibly followed by additional strings if need be. + +Other resources +--------------- + +With regard to testing the code more generally, not necessarily in the context of continuous integration, AMReX provides a number of useful post-processing tools for plotfiles. +The complete list of tools can be found `here `__. +One tool that traditionally stood out as especially useful for core developers and maintainers is `fcompare `__. diff --git a/Docs/source/developers/documentation.rst b/Docs/source/developers/how_to_write_the_docs.rst similarity index 98% rename from Docs/source/developers/documentation.rst rename to Docs/source/developers/how_to_write_the_docs.rst index 5d604bcf9b3..827b5950d80 100644 --- a/Docs/source/developers/documentation.rst +++ b/Docs/source/developers/how_to_write_the_docs.rst @@ -1,7 +1,7 @@ .. _developers-docs: -Documentation -============= +How to write documentation +========================== Doxygen documentation --------------------- diff --git a/Docs/source/developers/particles.rst b/Docs/source/developers/particles.rst index 1f1e2eab606..9f199bdbb91 100644 --- a/Docs/source/developers/particles.rst +++ b/Docs/source/developers/particles.rst @@ -83,7 +83,7 @@ Main functions .. doxygenfunction:: PhysicalParticleContainer::PushPX -.. doxygenfunction:: WarpXParticleContainer::DepositCurrent(amrex::Vector, 3>> &J, amrex::Real dt, amrex::Real relative_time) +.. doxygenfunction:: WarpXParticleContainer::DepositCurrent(ablastr::fields::MultiLevelVectorField const &J, amrex::Real dt, amrex::Real relative_time) .. note:: The current deposition is used both by ``PhysicalParticleContainer`` and ``LaserParticleContainer``, so it is in the parent class ``WarpXParticleContainer``. @@ -141,7 +141,7 @@ Attribute name ``int``/``real`` Description Wher Wheeler process physics is used. ==================== ================ ================================== ===== ==== ====================== -WarpX allows extra runtime attributes to be added to particle containers (through ``NewRealComp("attrname")`` or ``NewIntComp("attrname")``). +WarpX allows extra runtime attributes to be added to particle containers (through ``AddRealComp("attrname")`` or ``AddIntComp("attrname")``). The attribute name can then be used to access the values of that attribute. For example, using a particle iterator, ``pti``, to loop over the particles the command ``pti.GetAttribs(particle_comps["attrname"]).dataPtr();`` will return the values of the ``"attrname"`` attribute. diff --git a/Docs/source/developers/run_clang_tidy_locally.rst b/Docs/source/developers/run_clang_tidy_locally.rst deleted file mode 100644 index 3f600019fe7..00000000000 --- a/Docs/source/developers/run_clang_tidy_locally.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. _developers-run_clang_tidy_locally: - -The clang-tidy linter -===================== - -Clang-tidy CI test ------------------- - -WarpX's CI tests include several checks performed with the -`clang-tidy `__ linter -(currently the version 15 of this tool). The complete list of checks -enforced in CI tests can be found in the ``.clang-tidy`` configuration file. - -.. dropdown:: clang-tidy configuration file - :color: light - :icon: info - :animate: fade-in-slide-down - - .. literalinclude:: ../../../.clang-tidy - :language: yaml - -Run clang-tidy linter locally ------------------------------ - -We provide a script to run clang-tidy locally. The script can be run as follows, -provided that all the requirements to compile WarpX are met (see `building from source `). -The script generates a simple wrapper to ensure that `clang-tidy` is only applied to WarpX source files -and compiles WarpX in 1D,2D,3D, and RZ using such wrapper. By default WarpX is compiled in single precision -with PSATD solver, QED module, QED table generator and Embedded boundary in order to find more -potential issues with the `clang-tidy` tool. - -Few optional environment variables can be set to tune the behavior of the script: - -* ``WARPX_TOOLS_LINTER_PARALLEL``: sets the number of cores to be used for the compilation -* ``CLANG``, ``CLANGXX``, and ``CLANGTIDY`` : set the version of the compiler and of the linter - -Note: clang v15 is currently used in CI tests. It is therefore recommended to use this version. -Otherwise, a newer version may find issues not currently covered by CI tests (checks are opt-in) -while older versions may not find all the issues. - -.. code-block:: bash - - export WARPX_TOOLS_LINTER_PARALLEL=12 - export CLANG=clang-15 - export CLANGXX=clang++-15 - export CLANGTIDY=clang-tidy-15 - ./Tools/Linter/runClangTidy.sh - -.. dropdown:: Script Details - :color: light - :icon: info - :animate: fade-in-slide-down - - .. literalinclude:: ../../../Tools/Linter/runClangTidy.sh - :language: bash diff --git a/Docs/source/developers/testing.rst b/Docs/source/developers/testing.rst deleted file mode 100644 index 111e3e7d7cb..00000000000 --- a/Docs/source/developers/testing.rst +++ /dev/null @@ -1,250 +0,0 @@ -.. _developers-testing: - -Testing the Code -================ - -When proposing a code change, you want to make sure that - -* the code change does not break the existing code; -* the code change gives correct results (numerics, physics, etc.). - -WarpX follows the continuous integration (CI) software development practice, where automated builds and tests are run after merging code changes into the main branch. - -While the code is tested regularly remotely (on the cloud when commits are pushed to an open PR, and every night on local clusters), it can also be useful to run tests on your custom input file. - -How to run pre-commit tests locally ------------------------------------ - -First, when proposing a code change, we perform a couple of automated style and correctness checks. - -If you install the ``pre-commit`` tool on your local machine via - -.. code-block:: sh - - python -m pip install -U pre-commit - pre-commit install - -the style and correctness checks will run automatically on your local machine, after you commit the change and before you push. - -If you do not install the ``pre-commit`` tool on your local machine, these checks will run automatically as part of our CI workflows and a commit containing style and correctness changes might be added automatically to your branch. -In that case, you will need to pull that automated commit before pushing further changes. - -See `pre-commit.com `__ and our ``.pre-commit-config.yaml`` file in the repository for more details. - -How to configure the automated tests ------------------------------------- - -Our regression tests are run with `CTest `__, an executable that comes with CMake. - -The test suite is ready to run once you have configured and built WarpX with CMake, following the instructions that you find in our :ref:`Users ` or :ref:`Developers ` sections. - -A test that requires a build option that was not configured and built will be skipped automatically. For example, if you configure and build WarpX in 1D only, any test of dimensionality other than 1D, which would require WarpX to be configured and built in the corresponding dimensionality, will be skipped automatically. - -How to run automated tests locally ----------------------------------- - -Once your new feature is ready, there are ways to check that you did not break anything. -WarpX has automated tests running every time a commit is pushed to an open pull request. -The input files and scripts used by the automated tests can be found in the `Examples `__ directory, either under `Physics_applications `__ or `Tests `__. - -For easier debugging, it can be convenient to run the tests on your local machine by executing CTest as illustrated in the examples below (where we assume that WarpX was configured and built in the directory ``build``): - -* List tests available for the current build options: - - .. code-block:: sh - - ctest --test-dir build -N - -* Run tests available for the current build options: - - .. code-block:: sh - - ctest --test-dir build - -* Run tests available for the current build options in parallel (while preserving existing dependencies between tests): - - .. code-block:: sh - - ctest --test-dir build -j 2 - -* Run tests available for the current build options and output anything outputted by the test program if the test should fail: - - .. code-block:: sh - - ctest --test-dir build --output-on-failure - -* Run tests available for the current build options with verbose output: - - .. code-block:: sh - - ctest --test-dir build --verbose - -* Run tests matching the regular expression ``laser_acceleration``: - - .. code-block:: sh - - ctest --test-dir build -R laser_acceleration - -* Run tests except those matching the regular expression ``laser_acceleration``: - - .. code-block:: sh - - ctest --test-dir build -E laser_acceleration - -* Sometimes two or more tests share a large number of input parameters and differ by a small set of options. - Such tests typically also share a base string in their names. - For example, you can find three different tests named ``test_3d_langmuir_multi``, ``test_3d_langmuir_multi_nodal`` and ``test_3d_langmuir_multi_picmi``. - In such a case, if you wish to run the test ``test_3d_langmuir_multi`` only, this can be done again with the ``-R`` regular `expression filter `__ via - - .. code-block:: sh - - ctest --test-dir build -R "test_3d_langmuir_multi\..*" - - Note that filtering with ``-R "test_3d_langmuir_multi"`` would include the additional tests that have the same substring in their name and would not be sufficient to isolate a single test. - Note also that the escaping ``\.`` in the regular expression is necessary in order to take into account the fact that each test is automatically appended with the strings ``.run``, ``.analysis`` and possibly ``.cleanup``. - -* Run only tests not labeled with the ``slow`` label: - - .. code-block:: sh - - ctest --test-dir build -LE slow - -Once the execution of CTest is completed, you can find all files associated with each test in its corresponding directory under ``build/bin/``. -For example, if you run the single test ``test_3d_laser_acceleration``, you can find all files associated with this test in the directory ``build/bin/test_3d_laser_acceleration/``. - -If you modify the code base locally and want to assess the effects of your code changes on the automated tests, you need to first rebuild WarpX including your code changes and then rerun CTest. - -How to add automated tests --------------------------- - -An automated test typically consists of the following components: - -* input file or PICMI input script; -* analysis script; -* checksum file. - -To learn more about how to use checksums in automated tests, please see the corresponding section :ref:`Checksums on Tests `. - -As mentioned above, the input files and scripts used by the automated tests can be found in the `Examples `__ directory, under either `Physics_applications `__ or `Tests `__. - -Each test directory must contain a file named ``CMakeLists.txt`` where all tests associated with the input files and scripts in that directory must be listed. - -A new test can be added by adding a corresponding entry in ``CMakeLists.txt`` as illustrated in the examples below: - -* Add the **regular test** ``test_1d_laser_acceleration``: - - .. code-block:: cmake - - add_warpx_test( - test_1d_laser_acceleration # name - 1 # dims - 2 # nprocs - inputs_test_1d_laser_acceleration # inputs - analysis.py # analysis - diags/diag1000100 # output (plotfile) - OFF # dependency - ) - -* Add the **PICMI test** ``test_2d_laser_acceleration_picmi``: - - .. code-block:: cmake - - add_warpx_test( - test_2d_laser_acceleration_picmi # name - 2 # dims - 2 # nprocs - inputs_test_2d_laser_acceleration_picmi.py # inputs - analysis.py # analysis - diags/diag1000100 # output (plotfile) - OFF # dependency - ) - -* Add the **restart test** ``test_3d_laser_acceleration_restart``: - - .. code-block:: cmake - - add_warpx_test( - test_3d_laser_acceleration_restart # name - 3 # dims - 2 # nprocs - inputs_test_3d_laser_acceleration_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000100 # output (plotfile) - test_3d_laser_acceleration # dependency - ) - - Note that the restart has an explicit dependency, namely it can run only provided that the original test, from which the restart checkpoint files will be read, runs first. - -* A more complex example. Add the **PICMI test** ``test_rz_laser_acceleration_picmi``, with custom command-line arguments ``--test`` and ``dir``, and openPMD time series output: - - .. code-block:: cmake - - add_warpx_test( - test_rz_laser_acceleration_picmi # name - RZ # dims - 2 # nprocs - "inputs_test_rz_laser_acceleration_picmi.py --test --dir 1" # inputs - analysis.py # analysis - diags/diag1/ # output (openPMD time series) - OFF # dependency - ) - -If you need a new Python package dependency for testing, please add it in `Regression/requirements.txt `__. - -Sometimes two or more tests share a large number of input parameters. -The shared input parameters can be collected in a "base" input file that can be passed as a runtime parameter in the actual test input files through the parameter ``FILE``. - -If the new test is added in a new directory that did not exist before, please add the name of that directory with the command ``add_subdirectory`` in `Physics_applications/CMakeLists.txt `__ or `Tests/CMakeLists.txt `__, depending on where the new test directory is located. - -Naming conventions for automated tests --------------------------------------- - -Note that we currently obey the following snake\_case naming conventions for test names and test input files (which make automation tasks easier, e.g., parsing visually, parsing through code, sorting alphabetically, filtering tests in CTest via ``-R``, etc.): - -#. **Regular test names** start with the string ``test_1d_``, ``test_2d_``, ``test_3d_`` or ``test_rz_``, followed by a string that is descriptive of the test. For example, ``test_3d_laser_acceleration``. - -#. **PICMI test names** start with the string ``test_1d_``, ``test_2d_``, ``test_3d_`` or ``test_rz_``, followed by a string that is descriptive of the test, and end with the string ``_picmi``. For example, ``test_3d_laser_acceleration_picmi``. - -#. **Restart test names** end with the string ``_restart``. For example, ``test_3d_laser_acceleration_restart``. - -#. **Test input files** start with the string ``inputs_`` followed by the test name. For example, ``inputs_test_3d_laser_acceleration`` or ``inputs_test_3d_laser_acceleration_picmi.py`` or ``inputs_test_3d_laser_acceleration_restart``. - -#. **Base input files** (that is, files collecting input parameters shared between two or more tests) are typically named ``inputs_base_1d``, ``inputs_base_2d``, ``inputs_base_3d`` or ``inputs_base_rz``, possibly followed by additional strings if need be. - -Useful tool for plotfile comparison: ``fcompare`` -------------------------------------------------- - -AMReX provides ``fcompare``, an executable that takes two ``plotfiles`` as input and returns the absolute and relative difference for each field between these two plotfiles. For some changes in the code, it is very convenient to run the same input file with an old and your current version, and ``fcompare`` the plotfiles at the same iteration. To use it: - -.. code-block:: sh - - # Compile the executable - cd /Tools/Plotfile/ # This may change - make -j 8 - # Run the executable to compare old and new versions - /Tools/Plotfile/fcompare.gnu.ex old/plt00200 new/plt00200 - -which should return something like - -.. code-block:: sh - - variable name absolute error relative error - (||A - B||) (||A - B||/||A||) - ---------------------------------------------------------------------------- - level = 0 - jx 1.044455105e+11 1.021651316 - jy 4.08631977e+16 7.734299273 - jz 1.877301764e+14 1.073458933 - Ex 4.196315448e+10 1.253551615 - Ey 3.330698083e+12 6.436470137 - Ez 2.598167798e+10 0.6804387128 - Bx 273.8687473 2.340209782 - By 152.3911863 1.10952567 - Bz 37.43212767 2.1977289 - part_per_cell 15 0.9375 - Ex_fp 4.196315448e+10 1.253551615 - Ey_fp 3.330698083e+12 6.436470137 - Ez_fp 2.598167798e+10 0.6804387128 - Bx_fp 273.8687473 2.340209782 - By_fp 152.3911863 1.10952567 - Bz_fp 37.43212767 2.1977289 diff --git a/Docs/source/developers/workflows.rst b/Docs/source/developers/workflows.rst deleted file mode 100644 index f7c81ae70d8..00000000000 --- a/Docs/source/developers/workflows.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. _development-workflows: - -Workflows -========= - -.. toctree:: - :maxdepth: 1 - - profiling - testing - checksum - run_clang_tidy_locally - local_compile - documentation diff --git a/Docs/source/highlights.rst b/Docs/source/highlights.rst index 09156072cad..81cc53c3eab 100644 --- a/Docs/source/highlights.rst +++ b/Docs/source/highlights.rst @@ -14,7 +14,12 @@ Plasma-Based Acceleration Scientific works in laser-plasma and beam-plasma acceleration. -#. Shrock JE, Rockafellow E, Miao B, Le M, Hollinger RC, Wang S, Gonsalves AJ, Picksley A, Rocca JJ, and Milchberg HM +#. Ma M, Zeng M, Wang J, Lu G, Yan W, Chen L, and Li D. + **Particle-in-cell simulation of laser wakefield accelerators with oblique lasers in quasicylindrical geometry**. + Phys. Rev. Accel. Beams **28**, 021301, 2025 + `DOI:10.1103/PhysRevAccelBeams.28.021301 `__ + +#. Shrock JE, Rockafellow E, Miao B, Le M, Hollinger RC, Wang S, Gonsalves AJ, Picksley A, Rocca JJ, and Milchberg HM. **Guided Mode Evolution and Ionization Injection in Meter-Scale Multi-GeV Laser Wakefield Accelerators**. Phys. Rev. Lett. **133**, 045002, 2024 `DOI:10.1103/PhysRevLett.133.045002 `__ @@ -154,6 +159,21 @@ High Energy Astrophysical Plasma Physics Scientific works in astrophysical plasma modeling. +#. Sam A, Kumar P, Fletcher AC, Crabtree C, Lee N, Elschot S. + **Nonlinear evolution, propagation, electron-trapping, and damping effects of ion-acoustic solitons using fully kinetic PIC simulations**. + Phys. Plasmas **32** 022103, 2025 + `DOI:10.1063/5.0249525 `__ + +#. Jambunathan R, Jones H, Corrales L, Klion H, Roward ME, Myers A, Zhang W, Vay J-L. + **Application of mesh refinement to relativistic magnetic reconnection**. + Physics of Plasmas ***32*** 1, 2025 + `DOI:10.1063/5.0233583 `__ + +#. Ghosh S, Bhat P. + **Magnetic Reconnection: An Alternative Explanation of Radio Emission in Galaxy Clusters**. + The Astrophysical Journal Letters **979** 1, 2025. + `DOI:10.3847/2041-8213/ad9f2d `__ + #. Klion H, Jambunathan R, Rowan ME, Yang E, Willcox D, Vay J-L, Lehe R, Myers A, Huebl A, Zhang W. **Particle-in-Cell simulations of relativistic magnetic reconnection with advanced Maxwell solver algorithms**. The Astrophysical Journal **952** 8, 2023. @@ -188,9 +208,27 @@ Scientific works in High-Performance Computing, applied mathematics and numerics Please see :ref:`this section `. +Related works using WarpX: + +#. Yan Y., Du F., Tang J., Yu D and Zhao Y., + **Numerical study on wave attenuation via 1D fully kinetic electromagnetic particle-in-cell simulations**. + Plasma Sources Sci. Technol. **33** 115013, 2024 + `DOI:10.1088/1361-6595/ad8c7c `__ + + Nuclear Fusion and Plasma Confinement ************************************* +#. Tyushev M., Papahn Zadeh M., Chopra N. S., Raitses Y., Romadanov I., Likhanskii A., Fubiani G., Garrigues L., Groenewald R. and Smolyakov A. + **Mode transitions and spoke structures in E×B Penning discharge**. + Physics of Plasmas **32**, 013511, 2025. + `DOI:10.1063/5.0238577 `__ + +#. Scheffel J. and Jäderberg J. and Bendtz K. and Holmberg R. and Lindvall K., + **Axial Confinement in the Novatron Mirror Machine**. + arXiv 2410.20134 + `DOI:10.48550/arXiv.2410.20134 `__ + #. Affolter M., Thompson R., Hepner S., Hayes E. C., Podolsky V., Borghei M., Carlsson J., Gargone A., Merthe D., McKee E., Langtry R., **The Orbitron: A crossed-field device for co-confinement of high energy ions and electrons**. AIP Advances **14**, 085025, 2024. diff --git a/Docs/source/index.rst b/Docs/source/index.rst index 9668620976a..dfdeb3b9530 100644 --- a/Docs/source/index.rst +++ b/Docs/source/index.rst @@ -126,7 +126,7 @@ Development developers/developers developers/doxygen developers/gnumake - developers/workflows + developers/how_to_guides developers/faq .. good to have in the future: .. developers/repostructure diff --git a/Docs/source/install/cmake.rst b/Docs/source/install/cmake.rst index 41e4c40bc85..fbdc6809853 100644 --- a/Docs/source/install/cmake.rst +++ b/Docs/source/install/cmake.rst @@ -97,7 +97,6 @@ CMake Option Default & Values Descr ``WarpX_PRECISION`` SINGLE/**DOUBLE** Floating point precision (single/double) ``WarpX_PARTICLE_PRECISION`` SINGLE/**DOUBLE** Particle floating point precision (single/double), defaults to WarpX_PRECISION value if not set ``WarpX_FFT`` ON/**OFF** FFT-based solvers -``WarpX_HEFFTE`` ON/**OFF** Multi-Node FFT-based solvers ``WarpX_PYTHON`` ON/**OFF** Python bindings ``WarpX_QED`` **ON**/OFF QED support (requires PICSAR) ``WarpX_QED_TABLE_GEN`` ON/**OFF** QED table generation support (requires PICSAR and Boost) @@ -129,7 +128,7 @@ CMake Option Default & Values Des ``WarpX_amrex_internal`` **ON**/OFF Needs a pre-installed AMReX library if set to ``OFF`` ``WarpX_openpmd_src`` *None* Path to openPMD-api source directory (preferred if set) ``WarpX_openpmd_repo`` ``https://github.com/openPMD/openPMD-api.git`` Repository URI to pull and build openPMD-api from -``WarpX_openpmd_branch`` ``0.15.2`` Repository branch for ``WarpX_openpmd_repo`` +``WarpX_openpmd_branch`` ``0.16.1`` Repository branch for ``WarpX_openpmd_repo`` ``WarpX_openpmd_internal`` **ON**/OFF Needs a pre-installed openPMD-api library if set to ``OFF`` ``WarpX_picsar_src`` *None* Path to PICSAR source directory (preferred if set) ``WarpX_picsar_repo`` ``https://github.com/ECP-WarpX/picsar.git`` Repository URI to pull and build PICSAR from @@ -144,6 +143,10 @@ CMake Option Default & Values Des ``WarpX_pybind11_repo`` ``https://github.com/pybind/pybind11.git`` Repository URI to pull and build pybind11 from ``WarpX_pybind11_branch`` *we set and maintain a compatible commit* Repository branch for ``WarpX_pybind11_repo`` ``WarpX_pybind11_internal`` **ON**/OFF Needs a pre-installed pybind11 library if set to ``OFF`` +``WarpX_TEST_CLEANUP`` ON/**OFF** Clean up automated test directories +``WarpX_TEST_DEBUGGER`` ON/**OFF** Run automated tests without AMReX signal handling (to attach debuggers) +``WarpX_TEST_FPETRAP`` ON/**OFF** Run automated tests with FPE-trapping runtime parameters +``WarpX_BACKTRACE_INFO`` ON/**OFF** Compile with -g1 for minimal debug symbols (currently used in CI tests) ============================= ============================================== =========================================================== For example, one can also build against a local AMReX copy. @@ -275,7 +278,6 @@ Environment Variable Default & Values Descr ``WARPX_PRECISION`` SINGLE/**DOUBLE** Floating point precision (single/double) ``WARPX_PARTICLE_PRECISION`` SINGLE/**DOUBLE** Particle floating point precision (single/double), defaults to WarpX_PRECISION value if not set ``WARPX_FFT`` ON/**OFF** FFT-based solvers -``WARPX_HEFFTE`` ON/**OFF** Multi-Node FFT-based solvers ``WARPX_QED`` **ON**/OFF PICSAR QED (requires PICSAR) ``WARPX_QED_TABLE_GEN`` ON/**OFF** QED table generation (requires PICSAR and Boost) ``BUILD_PARALLEL`` ``2`` Number of threads to use for parallel builds diff --git a/Docs/source/install/dependencies.rst b/Docs/source/install/dependencies.rst index 71a607eae6a..a06ea10a86d 100644 --- a/Docs/source/install/dependencies.rst +++ b/Docs/source/install/dependencies.rst @@ -6,7 +6,7 @@ Dependencies WarpX depends on the following popular third party software. Please see installation instructions below. -- a mature `C++17 `__ compiler, e.g., GCC 8.4+, Clang 7, NVCC 11.0, MSVC 19.15 or newer +- a mature `C++17 `__ compiler, e.g., GCC 9.1+, Clang 7, NVCC 11.0, MSVC 19.15 or newer - `CMake 3.24.0+ `__ - `Git 2.18+ `__ - `AMReX `__: we automatically download and compile a copy of AMReX @@ -28,17 +28,16 @@ Optional dependencies include: - `FFTW3 `__: for spectral solver (PSATD or IGF) support when running on CPU or SYCL - also needs the ``pkg-config`` tool on Unix -- `heFFTe 2.4.0+ `__: for multi-node spectral solver (IGF) support - `BLAS++ `__ and `LAPACK++ `__: for spectral solver (PSATD) support in RZ geometry - `Boost 1.66.0+ `__: for QED lookup tables generation support -- `openPMD-api 0.15.1+ `__: we automatically download and compile a copy of openPMD-api for openPMD I/O support +- `openPMD-api 0.16.1+ `__: we automatically download and compile a copy of openPMD-api for openPMD I/O support - see `optional I/O backends `__, i.e., ADIOS2 and/or HDF5 - `Ascent 0.8.0+ `__: for in situ 3D visualization - `SENSEI 4.0.0+ `__: for in situ analysis and visualization - `CCache `__: to speed up rebuilds (For CUDA support, needs version 3.7.9+ and 4.2+ is recommended) - `Ninja `__: for faster parallel compiles -- `Python 3.8+ `__ +- `Python 3.9+ `__ - `mpi4py `__ - `numpy `__ @@ -53,27 +52,26 @@ For all other systems, we recommend to use a **package dependency manager**: Pick *one* of the installation methods below to install all dependencies for WarpX development in a consistent manner. -Conda (Linux/macOS/Windows) ---------------------------- +Conda-Forge (Linux/macOS/Windows) +--------------------------------- -`Conda `__/`Mamba `__ are cross-compatible, user-level package managers. +`Conda-Forge `__ is a repository for cross-compatible, user-level packages. .. tip:: - We recommend to configure your conda to use the faster ``libmamba`` `dependency solver `__. + We recommend to deactivate that conda self-activates its ``base`` environment. + This `avoids interference with the system and other package managers `__. .. code-block:: bash - conda update -y -n base conda - conda install -y -n base conda-libmamba-solver - conda config --set solver libmamba + conda config --set auto_activate_base false - We recommend to deactivate that conda self-activates its ``base`` environment. - This `avoids interference with the system and other package managers `__. + In order to make sure that the conda configuration uses ``conda-forge`` as the only channel, which will help avoid issues with blocked ``defaults`` or ``anaconda`` repositories, please set the following configurations: .. code-block:: bash - conda config --set auto_activate_base false + conda config --add channels conda-forge + conda config --set channel_priority strict .. tab-set:: @@ -81,7 +79,7 @@ Conda (Linux/macOS/Windows) .. code-block:: bash - conda create -n warpx-cpu-mpich-dev -c conda-forge blaspp boost ccache cmake compilers git "heffte=*=mpi_mpich*" lapackpp "openpmd-api=*=mpi_mpich*" openpmd-viewer python make numpy pandas scipy yt "fftw=*=mpi_mpich*" pkg-config matplotlib mamba mpich mpi4py ninja pip virtualenv + conda create -n warpx-cpu-mpich-dev -c conda-forge blaspp boost ccache cmake compilers git lapackpp "openpmd-api=*=mpi_mpich*" openpmd-viewer packaging pytest python python-build make numpy pandas scipy setuptools yt "fftw=*=mpi_mpich*" pkg-config matplotlib mamba mpich mpi4py ninja pip virtualenv wheel conda activate warpx-cpu-mpich-dev # compile WarpX with -DWarpX_MPI=ON @@ -91,7 +89,7 @@ Conda (Linux/macOS/Windows) .. code-block:: bash - conda create -n warpx-cpu-dev -c conda-forge blaspp boost ccache cmake compilers git lapackpp openpmd-api openpmd-viewer python make numpy pandas scipy yt fftw pkg-config matplotlib mamba ninja pip virtualenv + conda create -n warpx-cpu-dev -c conda-forge blaspp boost ccache cmake compilers git lapackpp openpmd-api openpmd-viewer packaging pytest python python-build make numpy pandas scipy setuptools yt fftw pkg-config matplotlib mamba ninja pip virtualenv wheel conda activate warpx-cpu-dev # compile WarpX with -DWarpX_MPI=OFF @@ -105,19 +103,19 @@ For OpenMP support, you will further need: .. code-block:: bash - conda install -c conda-forge libgomp + mamba install -c conda-forge libgomp .. tab-item:: macOS or Windows .. code-block:: bash - conda install -c conda-forge llvm-openmp + mamba install -c conda-forge llvm-openmp For Nvidia CUDA GPU support, you will need to have `a recent CUDA driver installed `__ or you can lower the CUDA version of `the Nvidia cuda package `__ and `conda-forge to match your drivers `__ and then add these packages: .. code-block:: bash - conda install -c nvidia -c conda-forge cuda cuda-nvtx-dev cupy + mamba install -c nvidia -c conda-forge cuda cuda-nvtx-dev cupy More info for `CUDA-enabled ML packages `__. diff --git a/Docs/source/install/hpc.rst b/Docs/source/install/hpc.rst index 35884050a59..61e60359e59 100644 --- a/Docs/source/install/hpc.rst +++ b/Docs/source/install/hpc.rst @@ -50,7 +50,7 @@ This section documents quick-start guides for a selection of supercomputers that hpc/perlmutter hpc/pitzer hpc/polaris - hpc/quartz + hpc/dane hpc/summit hpc/taurus hpc/tioga diff --git a/Docs/source/install/hpc/dane.rst b/Docs/source/install/hpc/dane.rst new file mode 100644 index 00000000000..9c3c9077df5 --- /dev/null +++ b/Docs/source/install/hpc/dane.rst @@ -0,0 +1,167 @@ +.. _building-dane: + +Dane (LLNL) +============= + +The `Dane Intel CPU cluster `__ is located at LLNL. + + +Introduction +------------ + +If you are new to this system, **please see the following resources**: + +* `LLNL user account `__ (login required) +* `Jupyter service `__ (`documentation `__, login required) +* `Production directories `__: + + * ``/p/lustre1/$(whoami)`` and ``/p/lustre2/$(whoami)``: personal directory on the parallel filesystem + * Note that the ``$HOME`` directory and the ``/usr/workspace/$(whoami)`` space are NFS mounted and *not* suitable for production quality data generation. + + +.. _building-dane-preparation: + +Preparation +----------- + +Use the following commands to download the WarpX source code. +Note that these commands and the shell scripts all assume the bash shell. + +.. code-block:: bash + + git clone https://github.com/ECP-WarpX/WarpX.git /usr/workspace/${USER}/dane/src/warpx + +We use system software modules, add environment hints and further dependencies via the file ``$HOME/dane_warpx.profile``. +Create it now: + +.. code-block:: bash + + cp /usr/workspace/${USER}/dane/src/warpx/Tools/machines/dane-llnl/dane_warpx.profile.example $HOME/dane_warpx.profile + +.. dropdown:: Script Details + :color: light + :icon: info + :animate: fade-in-slide-down + + .. literalinclude:: ../../../../Tools/machines/dane-llnl/dane_warpx.profile.example + :language: bash + +Edit the 2nd line of this script, which sets the ``export proj=""`` variable. +For example, if you are member of the project ``tps``, then run ``vi $HOME/dane_warpx.profile``. +Enter the edit mode by typing ``i`` and edit line 2 to read: + +.. code-block:: bash + + export proj="tps" + +Exit the ``vi`` editor with ``Esc`` and then type ``:wq`` (write & quit). + +.. important:: + + Now, and as the first step on future logins to Dane, activate these environment settings: + + .. code-block:: bash + + source $HOME/dane_warpx.profile + +Finally, since Dane does not yet provide software modules for some of our dependencies, install them once: + +.. code-block:: bash + + bash /usr/workspace/${USER}/dane/src/warpx/Tools/machines/dane-llnl/install_dependencies.sh + source /usr/workspace/${USER}/dane/venvs/warpx-dane/bin/activate + +.. dropdown:: Script Details + :color: light + :icon: info + :animate: fade-in-slide-down + + .. literalinclude:: ../../../../Tools/machines/dane-llnl/install_dependencies.sh + :language: bash + + +.. _building-dane-compilation: + +Compilation +----------- + +Use the following :ref:`cmake commands ` to compile the application executable: + +.. code-block:: bash + + cd /usr/workspace/${USER}/dane/src/warpx + rm -rf build_dane + + cmake -S . -B build_dane -DWarpX_FFT=ON -DWarpX_QED_TABLE_GEN=ON -DWarpX_DIMS="1;2;RZ;3" + cmake --build build_dane -j 6 + +The WarpX application executables are now in ``/usr/workspace/${USER}/dane/src/warpx/build_dane/bin/``. +Additionally, the following commands will install WarpX as a Python module: + +.. code-block:: bash + + rm -rf build_dane_py + + cmake -S . -B build_dane_py -DWarpX_FFT=ON -DWarpX_QED_TABLE_GEN=ON -DWarpX_APP=OFF -DWarpX_PYTHON=ON -DWarpX_DIMS="1;2;RZ;3" + cmake --build build_dane_py -j 6 --target pip_install + +Now, you can :ref:`submit Dane compute jobs ` for WarpX :ref:`Python (PICMI) scripts ` (:ref:`example scripts `). +Or, you can use the WarpX executables to submit Dane jobs (:ref:`example inputs `). +For executables, you can reference their location in your :ref:`job script ` or copy them to a location in ``$PROJWORK/$proj/``. + + +.. _building-dane-update: + +Update WarpX & Dependencies +--------------------------- + +If you already installed WarpX in the past and want to update it, start by getting the latest source code: + +.. code-block:: bash + + cd /usr/workspace/${USER}/dane/src/warpx + + # read the output of this command - does it look ok? + git status + + # get the latest WarpX source code + git fetch + git pull + + # read the output of these commands - do they look ok? + git status + git log # press q to exit + +And, if needed, + +- :ref:`update the dane_warpx.profile file `, +- log out and into the system, activate the now updated environment profile as usual, +- :ref:`execute the dependency install scripts `. + +As a last step, clean the build directory ``rm -rf /usr/workspace/${USER}/dane/src/warpx/build_dane`` and rebuild WarpX. + + +.. _running-cpp-dane: + +Running +------- + +.. _running-cpp-dane-CPUs: + +Intel Sapphire Rapids CPUs +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The batch script below can be used to run a WarpX simulation on 2 nodes on the supercomputer Dane at LLNL. +Replace descriptions between chevrons ``<>`` by relevant values, for instance ```` could be ``plasma_mirror_inputs``. + +.. literalinclude:: ../../../../Tools/machines/dane-llnl/dane.sbatch + :language: bash + :caption: You can copy this file from ``Tools/machines/dane-llnl/dane.sbatch``. + +To run a simulation, copy the lines above to a file ``dane.sbatch`` and run + +.. code-block:: bash + + sbatch dane.sbatch + +to submit the job. diff --git a/Docs/source/install/hpc/lawrencium.rst b/Docs/source/install/hpc/lawrencium.rst index 2217c5a31ce..f163531a29a 100644 --- a/Docs/source/install/hpc/lawrencium.rst +++ b/Docs/source/install/hpc/lawrencium.rst @@ -69,7 +69,7 @@ And since Lawrencium does not yet provide a module for them, install ADIOS2, BLA cmake -S src/lapackpp -B src/lapackpp-v100-build -DCMAKE_CXX_STANDARD=17 -Dgpu_backend=cuda -Dbuild_tests=OFF -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DCMAKE_INSTALL_PREFIX=$HOME/sw/v100/lapackpp-master -Duse_cmake_find_lapack=ON -DBLAS_LIBRARIES=${LAPACK_DIR}/lib/libblas.a -DLAPACK_LIBRARIES=${LAPACK_DIR}/lib/liblapack.a cmake --build src/lapackpp-v100-build --target install --parallel 12 -Optionally, download and install Python packages for :ref:`PICMI ` or dynamic ensemble optimizations (:ref:`libEnsemble `): +Optionally, download and install Python packages for :ref:`PICMI ` or dynamic ensemble optimizations (`libEnsemble `__): .. code-block:: bash diff --git a/Docs/source/install/hpc/perlmutter.rst b/Docs/source/install/hpc/perlmutter.rst index 9612b64476d..7e2ae31630e 100644 --- a/Docs/source/install/hpc/perlmutter.rst +++ b/Docs/source/install/hpc/perlmutter.rst @@ -76,7 +76,7 @@ On Perlmutter, you can run either on GPU nodes with fast A100 GPUs (recommended) .. code-block:: bash bash $HOME/src/warpx/Tools/machines/perlmutter-nersc/install_gpu_dependencies.sh - source ${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/venvs/warpx-gpu/bin/activate + source ${PSCRATCH}/storage/sw/warpx/perlmutter/gpu/venvs/warpx-gpu/bin/activate .. dropdown:: Script Details :color: light @@ -126,7 +126,7 @@ On Perlmutter, you can run either on GPU nodes with fast A100 GPUs (recommended) .. code-block:: bash bash $HOME/src/warpx/Tools/machines/perlmutter-nersc/install_cpu_dependencies.sh - source ${CFS}/${proj}/${USER}/sw/perlmutter/cpu/venvs/warpx-cpu/bin/activate + source ${PSCRATCH}/storage/sw/warpx/perlmutter/cpu/venvs/warpx-cpu/bin/activate .. dropdown:: Script Details :color: light diff --git a/Docs/source/install/hpc/quartz.rst b/Docs/source/install/hpc/quartz.rst deleted file mode 100644 index a49327e8613..00000000000 --- a/Docs/source/install/hpc/quartz.rst +++ /dev/null @@ -1,168 +0,0 @@ -.. _building-quartz: - -Quartz (LLNL) -============= - -The `Quartz Intel CPU cluster `_ is located at LLNL. - - -Introduction ------------- - -If you are new to this system, **please see the following resources**: - -* `LLNL user account `__ (login required) -* `Quartz user guide `_ -* Batch system: `Slurm `_ -* `Jupyter service `__ (`documentation `__, login required) -* `Production directories `_: - - * ``/p/lustre1/$(whoami)`` and ``/p/lustre2/$(whoami)``: personal directory on the parallel filesystem - * Note that the ``$HOME`` directory and the ``/usr/workspace/$(whoami)`` space are NFS mounted and *not* suitable for production quality data generation. - - -.. _building-quartz-preparation: - -Preparation ------------ - -Use the following commands to download the WarpX source code: - -.. code-block:: bash - - git clone https://github.com/ECP-WarpX/WarpX.git $HOME/src/warpx - -We use system software modules, add environment hints and further dependencies via the file ``$HOME/quartz_warpx.profile``. -Create it now: - -.. code-block:: bash - - cp $HOME/src/warpx/Tools/machines/quartz-llnl/quartz_warpx.profile.example $HOME/quartz_warpx.profile - -.. dropdown:: Script Details - :color: light - :icon: info - :animate: fade-in-slide-down - - .. literalinclude:: ../../../../Tools/machines/quartz-llnl/quartz_warpx.profile.example - :language: bash - -Edit the 2nd line of this script, which sets the ``export proj=""`` variable. -For example, if you are member of the project ``tps``, then run ``vi $HOME/quartz_warpx.profile``. -Enter the edit mode by typing ``i`` and edit line 2 to read: - -.. code-block:: bash - - export proj="tps" - -Exit the ``vi`` editor with ``Esc`` and then type ``:wq`` (write & quit). - -.. important:: - - Now, and as the first step on future logins to Quartz, activate these environment settings: - - .. code-block:: bash - - source $HOME/quartz_warpx.profile - -Finally, since Quartz does not yet provide software modules for some of our dependencies, install them once: - -.. code-block:: bash - - bash $HOME/src/warpx/Tools/machines/quartz-llnl/install_dependencies.sh - source /usr/workspace/${USER}/quartz/venvs/warpx-quartz/bin/activate - -.. dropdown:: Script Details - :color: light - :icon: info - :animate: fade-in-slide-down - - .. literalinclude:: ../../../../Tools/machines/quartz-llnl/install_dependencies.sh - :language: bash - - -.. _building-quartz-compilation: - -Compilation ------------ - -Use the following :ref:`cmake commands ` to compile the application executable: - -.. code-block:: bash - - cd $HOME/src/warpx - rm -rf build_quartz - - cmake -S . -B build_quartz -DWarpX_FFT=ON -DWarpX_QED_TABLE_GEN=ON -DWarpX_DIMS="1;2;RZ;3" - cmake --build build_quartz -j 6 - -The WarpX application executables are now in ``$HOME/src/warpx/build_quartz/bin/``. -Additionally, the following commands will install WarpX as a Python module: - -.. code-block:: bash - - rm -rf build_quartz_py - - cmake -S . -B build_quartz_py -DWarpX_FFT=ON -DWarpX_QED_TABLE_GEN=ON -DWarpX_APP=OFF -DWarpX_PYTHON=ON -DWarpX_DIMS="1;2;RZ;3" - cmake --build build_quartz_py -j 6 --target pip_install - -Now, you can :ref:`submit Quartz compute jobs ` for WarpX :ref:`Python (PICMI) scripts ` (:ref:`example scripts `). -Or, you can use the WarpX executables to submit Quartz jobs (:ref:`example inputs `). -For executables, you can reference their location in your :ref:`job script ` or copy them to a location in ``$PROJWORK/$proj/``. - - -.. _building-quartz-update: - -Update WarpX & Dependencies ---------------------------- - -If you already installed WarpX in the past and want to update it, start by getting the latest source code: - -.. code-block:: bash - - cd $HOME/src/warpx - - # read the output of this command - does it look ok? - git status - - # get the latest WarpX source code - git fetch - git pull - - # read the output of these commands - do they look ok? - git status - git log # press q to exit - -And, if needed, - -- :ref:`update the quartz_warpx.profile file `, -- log out and into the system, activate the now updated environment profile as usual, -- :ref:`execute the dependency install scripts `. - -As a last step, clean the build directory ``rm -rf $HOME/src/warpx/build_quartz`` and rebuild WarpX. - - -.. _running-cpp-quartz: - -Running -------- - -.. _running-cpp-quartz-CPUs: - -Intel Xeon E5-2695 v4 CPUs -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The batch script below can be used to run a WarpX simulation on 2 nodes on the supercomputer Quartz at LLNL. -Replace descriptions between chevrons ``<>`` by relevant values, for instance ```` could be ``plasma_mirror_inputs``. - -.. literalinclude:: ../../../../Tools/machines/quartz-llnl/quartz.sbatch - :language: bash - :caption: You can copy this file from ``Tools/machines/quartz-llnl/quartz.sbatch``. - -To run a simulation, copy the lines above to a file ``quartz.sbatch`` and run - -.. code-block:: bash - - sbatch quartz.sbatch - -to submit the job. diff --git a/Docs/source/install/users.rst b/Docs/source/install/users.rst index e56d2d8ac43..650cbacd4d0 100644 --- a/Docs/source/install/users.rst +++ b/Docs/source/install/users.rst @@ -38,36 +38,35 @@ If want to use WarpX on a specific high-performance computing (HPC) systems, jum .. image:: conda.svg -Using the Conda Package ------------------------ +Using the Conda-Forge Package +----------------------------- -A package for WarpX is available via the `Conda `_ package manager. +A package for WarpX is available via `Conda-Forge `__. .. tip:: - We recommend to configure your conda to use the faster ``libmamba`` `dependency solver `__. + We recommend to deactivate that conda self-activates its ``base`` environment. + This `avoids interference with the system and other package managers `__. .. code-block:: bash - conda update -y -n base conda - conda install -y -n base conda-libmamba-solver - conda config --set solver libmamba + conda config --set auto_activate_base false - We recommend to deactivate that conda self-activates its ``base`` environment. - This `avoids interference with the system and other package managers `__. + In order to make sure that the conda configuration uses ``conda-forge`` as the only channel, which will help avoid issues with blocked ``defaults`` or ``anaconda`` repositories, please set the following configurations: .. code-block:: bash - conda config --set auto_activate_base false + conda config --add channels conda-forge + conda config --set channel_priority strict .. code-block:: bash - conda create -n warpx -c conda-forge warpx - conda activate warpx + mamba create -n warpx -c conda-forge warpx + mamba activate warpx .. note:: - The ``warpx`` `conda package `__ does not yet provide GPU support. + The ``warpx`` package on conda-forge does not yet provide `GPU support `__. .. _install-spack: @@ -80,7 +79,7 @@ Using the Spack Package ----------------------- Packages for WarpX are available via the `Spack `__ package manager. -The package ``warpx`` installs executables and the package ``py-warpx`` includes Python bindings, i.e. `PICMI `_. +The package ``warpx`` installs executables and the variant ``warpx +python`` also includes Python bindings, i.e. `PICMI `__. .. code-block:: bash @@ -89,11 +88,11 @@ The package ``warpx`` installs executables and the package ``py-warpx`` includes spack buildcache keys --install --trust # see `spack info py-warpx` for build options. - # optional arguments: -mpi ^warpx dims=2 compute=cuda - spack install py-warpx - spack load py-warpx + # optional arguments: -mpi compute=cuda + spack install warpx +python + spack load warpx +python -See ``spack info warpx`` or ``spack info py-warpx`` and `the official Spack tutorial `__ for more information. +See ``spack info warpx`` and `the official Spack tutorial `__ for more information. .. _install-pypi: diff --git a/Docs/source/maintenance/release.rst b/Docs/source/maintenance/release.rst index f25b8c313e4..9c6dbcc3f82 100644 --- a/Docs/source/maintenance/release.rst +++ b/Docs/source/maintenance/release.rst @@ -28,7 +28,7 @@ In order to create a GitHub release, you need to: 1. Create a new branch from ``development`` and update the version number in all source files. We usually wait for the AMReX release to be tagged first, then we also point to its tag. - There is a script for updating core dependencies of WarpX and the WarpX version: + There are scripts for updating core dependencies of WarpX and the WarpX version: .. code-block:: sh @@ -42,6 +42,9 @@ In order to create a GitHub release, you need to: Then open a PR, wait for tests to pass and then merge. + The maintainer script ``Tools/Release/releasePR.py`` automates the steps above. + Please read through the instructions in the script before running. + 2. **Local Commit** (Optional): at the moment, ``@ax3l`` is managing releases and signs tags (naming: ``YY.MM``) locally with his GPG key before uploading them to GitHub. **Publish**: On the `GitHub Release page `__, create a new release via ``Draft a new release``. diff --git a/Docs/source/refs.bib b/Docs/source/refs.bib index 5bbaf633179..49f4658af4c 100644 --- a/Docs/source/refs.bib +++ b/Docs/source/refs.bib @@ -35,6 +35,17 @@ @ARTICLE{Birdsall1991 year = {1991} } +@misc{Janssen2016 +author = {Janssen, J. F. J. and Pitchford L. C. and Hagelaar G. J. M. and van Dijk J.}, +doi = {10.1088/0963-0252/25/5/055026}, +journal = {Plasma Sources Science and Technology}, +number = {5}, +pages = {055026}, +title = {{Evaluation of angular scattering models for electron-neutral collisions in Monte Carlo simulations}}, +volume = {25}, +year = {2016} +} + @misc{Lim2007, author = {Lim, Chul-Hyun}, issn = {0419-4217}, @@ -458,6 +469,7 @@ @misc{Fallahi2020 @article{VayFELA2009, title = {FULL ELECTROMAGNETIC SIMULATION OF FREE-ELECTRON LASER AMPLIFIER PHYSICS VIA THE LORENTZ-BOOSTED FRAME APPROACH}, author = {Fawley, William M and Vay, Jean-Luc}, + journal = {}, abstractNote = {Numerical simulation of some systems containing charged particles with highly relativistic directed motion can by speeded up by orders of magnitude by choice of the proper Lorentz-boosted frame[1]. A particularly good example is that of short wavelength free-electron lasers (FELs) in which a high energy electron beam interacts with a static magnetic undulator. In the optimal boost frame with Lorentz factor gamma_F , the red-shifted FEL radiation and blue shifted undulator have identical wavelengths and the number of required time-steps (presuming the Courant condition applies) decreases by a factor of 2(gamma_F)**2 for fully electromagnetic simulation. We have adapted the WARP code [2]to apply this method to several FEL problems involving coherent spontaneous emission (CSE) from pre-bunched ebeams, including that in a biharmonic undulator.}, url = {https://www.osti.gov/biblio/964405}, place = {United States}, @@ -479,3 +491,40 @@ @article{VayFELB2009 doi = {10.1063/1.3080930}, url = {https://doi.org/10.1063/1.3080930}, } + +@article{Barnes2021, + title = {Improved C1 shape functions for simplex meshes}, + author = {D.C. Barnes}, + journal = {Journal of Computational Physics}, + volume = {424}, + pages = {109852}, + year = {2021}, + issn = {0021-9991}, + doi = {https://doi.org/10.1016/j.jcp.2020.109852}, + url = {https://www.sciencedirect.com/science/article/pii/S0021999120306264}, +} + +@article{Rhee1987, + author = {Rhee, M. J. and Schneider, R. F. and Weidman, D. J.}, + title = "{Simple time‐resolving Thomson spectrometer}", + journal = {Review of Scientific Instruments}, + volume = {58}, + number = {2}, + pages = {240-244}, + year = {1987}, + month = {02}, + issn = {0034-6748}, + doi = {10.1063/1.1139314}, + url = {https://doi.org/10.1063/1.1139314}, + eprint = {https://pubs.aip.org/aip/rsi/article-pdf/58/2/240/19154912/240\_1\_online.pdf}, +} + +@misc{holmstrom2013handlingvacuumregionshybrid, + title={Handling vacuum regions in a hybrid plasma solver}, + author={M. Holmstrom}, + year={2013}, + eprint={1301.0272}, + archivePrefix={arXiv}, + primaryClass={physics.space-ph}, + url={https://arxiv.org/abs/1301.0272}, +} diff --git a/Docs/source/theory/boundary_conditions.rst b/Docs/source/theory/boundary_conditions.rst index 395b072ccbe..d8b3de40c11 100644 --- a/Docs/source/theory/boundary_conditions.rst +++ b/Docs/source/theory/boundary_conditions.rst @@ -301,3 +301,23 @@ the right boundary is reflecting. .. bibliography:: :keyprefix: bc- + +.. _theory-bc-pmc: + +Perfect Magnetic Conductor +---------------------------- + +This boundary can be used to model a symmetric surface, where charges and current are +symmetric across the boundary. +This is equivalent to the Neumann (zero-derivative) boundary condition. +For the electromagnetic solve, at PMC, the tangential magnetic field and the normal electric +field are odd across the boundary and set to 0 on the boundary. +In the guard-cell region, those fields are set equal and +opposite to the respective field component in the mirror location across the PMC boundary. +The other components, the normal magnetic field and tangential electric field, are even +and set equal to the field component in the mirror location in the domain across the PMC boundary. + +The PMC boundary condition also impacts the deposition of charge and current density. +The charge and current densities deposited into the guard cells are reflected back into +the domain, adding them to the mirror cells in the domain. +This represents the charge and current from the virtual symmetric particles in the guard cells. diff --git a/Docs/source/theory/multiphysics/collisions.rst b/Docs/source/theory/multiphysics/collisions.rst index 08485345a13..1c7593a0e4e 100644 --- a/Docs/source/theory/multiphysics/collisions.rst +++ b/Docs/source/theory/multiphysics/collisions.rst @@ -121,17 +121,27 @@ The particle velocity in the COM frame is then isotropically scattered using the Back scattering ^^^^^^^^^^^^^^^ -The process is the same as for elastic scattering above expect the scattering angle is fixed at :math:`\pi`, meaning the particle velocity in the COM frame is updated to :math:`-\vec{u}_c`. +The process is the same as for elastic scattering above except the scattering angle is fixed at :math:`\pi`, meaning the particle velocity in the COM frame is updated to :math:`-\vec{u}_c`. Excitation ^^^^^^^^^^ The process is also the same as for elastic scattering except the excitation energy cost is subtracted from the particle energy. This is done by reducing the velocity before a scattering angle is chosen. +Forward scattering +^^^^^^^^^^^^^^^^^^ + +This process operates in two ways: + +1. If an excitation energy cost is provided, the energy cost is subtracted from the particle energy and no scattering is performed. +2. If an excitation energy cost is not provided, the particle is not scattered and the velocity is unchanged (corresponding to a scattering angle of :math:`0` in the elastic scattering process above). + +See :cite:t:`b-Janssen2016` for a recommended use of this process. + Benchmarks ---------- -See the :ref:`MCC example ` for a benchmark of the MCC +See the :ref:`MCC example ` for a benchmark of the MCC implementation against literature results. Particle cooling due to elastic collisions diff --git a/Docs/source/usage/examples.rst b/Docs/source/usage/examples.rst index 237c10ab5fb..4ac80a8bab0 100644 --- a/Docs/source/usage/examples.rst +++ b/Docs/source/usage/examples.rst @@ -45,6 +45,7 @@ Particle Accelerator & Beam Physics examples/gaussian_beam/README.rst examples/beam_beam_collision/README.rst examples/free_electron_laser/README.rst + examples/thomson_parabola_spectrometer/README.rst High Energy Astrophysical Plasma Physics ---------------------------------------- @@ -64,14 +65,6 @@ Microelectronics * `ARTEMIS manual `__ -Nuclear Fusion --------------- - -.. note:: - - TODO - - Fundamental Plasma Physics -------------------------- diff --git a/Docs/source/usage/examples/thomson_parabola_spectrometer b/Docs/source/usage/examples/thomson_parabola_spectrometer new file mode 120000 index 00000000000..8e72fba4100 --- /dev/null +++ b/Docs/source/usage/examples/thomson_parabola_spectrometer @@ -0,0 +1 @@ +../../../../Examples/Physics_applications/thomson_parabola_spectrometer \ No newline at end of file diff --git a/Docs/source/usage/parameters.rst b/Docs/source/usage/parameters.rst index af559aa1fba..3d24afdfa4d 100644 --- a/Docs/source/usage/parameters.rst +++ b/Docs/source/usage/parameters.rst @@ -93,6 +93,14 @@ Overall simulation parameters The PS-JFNK method is described in `Angus et al., An implicit particle code with exact energy and charge conservation for electromagnetic studies of dense plasmas `__ . (The version implemented in WarpX is an updated version that includes the relativistic gamma factor for the particles.) Also see `Chen et al., An energy- and charge-conserving, implicit, electrostatic particle-in-cell algorithm. `__ . Exact energy conservation requires that the interpolation stencil used for the field gather match that used for the current deposition. ``algo.current_deposition = direct`` must be used with ``interpolation.galerkin_scheme = 0``, and ``algo.current_deposition = Esirkepov`` must be used with ``interpolation.galerkin_scheme = 1``. If using ``algo.current_deposition = villasenor``, the corresponding field gather routine will automatically be selected and the ``interpolation.galerkin_scheme`` flag does not need to be specified. The Esirkepov and villasenor deposition schemes are charge-conserving. + * ``strang_implicit_spectral_em``: Use a fully implicit electromagnetic solver. All of the comments for ``theta_implicit_em`` + above apply here as well (except that theta is fixed to 0.5 and that charge will not be conserved). + In this version, the advance is Strang split, with a half advance of the source free Maxwell's equation (with a spectral solver), a full advance of the particles plus longitudinal E field, and a second half advance of the source free Maxwell's equations. + The advantage of this method is that with the Spectral advance of the fields, it is dispersionless. + Note that exact energy convergence is achieved only with one grid block and ``psatd.periodic_single_box_fft == 1``. Otherwise, + the energy convservation is spoiled because of the inconsistency of the periodic assumption of the spectral solver and the + non-periodic behavior of the individual blocks. + * ``semi_implicit_em``: Use an approximately energy conserving semi-implicit electromagnetic solver. Choices for the nonlinear solver include a Picard iteration scheme and particle-suppressed JFNK. Note that this method has the CFL limitation :math:`\Delta t < c/\sqrt( \sum_i 1/\Delta x_i^2 )`. The Picard solver for this method can only be expected to work well when :math:`\omega_{pe} \Delta t` is less than one. The method is described in `Chen et al., A semi-implicit, energy- and charge-conserving particle-in-cell algorithm for the relativistic Vlasov-Maxwell equations `__. @@ -105,16 +113,16 @@ Overall simulation parameters exactly energy conserving, but the solver may perform better. * ``implicit_evolve.nonlinear_solver`` (`string`, default: None) - When `algo.evolve_scheme` is either `theta_implicit_em` or `semi_implicit_em`, this sets the nonlinear solver used + When `algo.evolve_scheme` is either `theta_implicit_em`, `strang_implicit_spectral_em`, or `semi_implicit_em`, this sets the nonlinear solver used to advance the field-particle system in time. Options are `picard` or `newton`. * ``implicit_evolve.max_particle_iterations`` (`integer`, default: 21) - When `algo.evolve_scheme` is either `theta_implicit_em` or `semi_implicit_em` and `implicit_evolve.nonlinear_solver = newton` + When `algo.evolve_scheme` is either `theta_implicit_em`, `strang_implicit_spectral_em`, or `semi_implicit_em` and `implicit_evolve.nonlinear_solver = newton` , this sets the maximum number of iterations for the method used to obtain a self-consistent update of the particles at each iteration in the JFNK process. * ``implicit_evolve.particle_tolerance`` (`float`, default: 1.e-10) - When `algo.evolve_scheme` is either `theta_implicit_em` or `semi_implicit_em` and `implicit_evolve.nonlinear_solver = newton` + When `algo.evolve_scheme` is either `theta_implicit_em`, `strang_implicit_spectral_em`, or `semi_implicit_em` and `implicit_evolve.nonlinear_solver = newton` , this sets the relative tolerance for the iterative method used to obtain a self-consistent update of the particles at each iteration in the JFNK process. @@ -228,6 +236,23 @@ Overall simulation parameters \boldsymbol{\nabla}^2 \phi = - \rho/\epsilon_0 \qquad \boldsymbol{E} = - \boldsymbol{\nabla}\phi \\ \boldsymbol{\nabla}^2 \boldsymbol{A} = - \mu_0 \boldsymbol{j} \qquad \boldsymbol{B} = \boldsymbol{\nabla}\times\boldsymbol{A} + * ``labframe-effective-potential``: Poisson's equation is solved with a modified dielectric function + (resulting in an "effective potential") to create a semi-implicit scheme which is robust to the + numerical instability seen in explicit electrostatic PIC when :math:`\Delta t \omega_{pe} > 2`. + If this option is used the additional parameter ``warpx.effective_potential_factor`` can also be + specified to set the value of :math:`C_{EP}` (default 4). The method is stable for :math:`C_{EP} \geq 1` + regardless of :math:`\Delta t`, however, the larger :math:`C_{EP}` is set, the lower the numerical plasma + frequency will be and therefore care must be taken to not set it so high that the plasma mode + hybridizes with other modes of interest. + Details of the method can be found in Appendix A of :cite:t:`param-Barnes2021` (note that in that paper + the method is referred to as "semi-implicit electrostatic" but here it has been renamed to "effective potential" + to avoid confusion with the semi-implicit method of Chen et al.). + In short, the code solves: + + .. math:: + + \boldsymbol{\nabla}\cdot\left(1+\frac{C_{EP}}{4}\sum_{s \in \text{species}}(\omega_{ps}\Delta t)^2 \right)\boldsymbol{\nabla} \phi = - \rho/\epsilon_0 \qquad \boldsymbol{E} = - \boldsymbol{\nabla}\phi + * ``relativistic``: Poisson's equation is solved **for each species** in their respective rest frame. The corresponding field is mapped back to the simulation frame and will produce both E and B @@ -265,6 +290,21 @@ Overall simulation parameters In electromagnetic mode, this solver can be used to initialize the species' self fields (``.initialize_self_fields=1``) provided that the field BCs are PML (``boundary.field_lo,hi = PML``). + * ``warpx.use_2d_slices_fft_solver`` (`bool`) optional (default: 0): Select the type of Integrated Green Function solver. + If 0, solve Poisson equation in full 3D geometry. + If 1, solve Poisson equation in a quasi 3D geometry, neglecting the :math:`z` derivatives in the Laplacian of the Poisson equation. + In practice, in this case, the code performes many 2D Poisson solves on all :math:`(x,y)` slices, each slice at a given :math:`z`. + This is often a good approximation for ultra-relativistic beams propagating along the :math:`z` direction, with the relativistic solver. + As a consequence, this solver does not need to do an FFT along the :math:`z` direction, + and instead uses only transverse FFTs (along :math:`x` and :math:`y`) at each :math:`z` position (or :math:`z` "slice"). + + * ``ablastr.nprocs_igf_fft`` (`int`) optional (default: number of MPI ranks): Number of MPI ranks used to parallalelize the FFT solver. + This can be less or equal than then number of MPI ranks that are used to run the overall simulation. + It can be useful if the auxiliary simulation boxes fit within a single process, so to avoid extra communications. + The auxiliary boxes are extended boxes in real and spectral space that are used to perform the necessary FFTs. + The extended simulation box size in real space is :math:`2n_x-1, 2n_y-1, 2n_z-1` with the 3D solver, :math:`2n_x-1, 2n_y -1, n_z` with the 2D solver. + The extended simulation box size in spectral space is :math:`n_x, 2n_y-1, 2n_z-1` with the 3D solver, :math:`n_x, 2n_y-1, n_z` with the 2D solver. + * ``warpx.self_fields_required_precision`` (`float`, default: 1.e-11) The relative precision with which the electrostatic space-charge fields should be calculated. More specifically, the space-charge fields are @@ -493,6 +533,39 @@ Domain Boundary Conditions * ``pec``: This option can be used to set a Perfect Electric Conductor at the simulation boundary. Please see the :ref:`PEC theory section ` for more details. Note that PEC boundary is invalid at `r=0` for the RZ solver. Please use ``none`` option. This boundary condition does not work with the spectral solver. + * ``pmc``: This option can be used to set a Perfect Magnetic Conductor at the simulation boundary. Please see the :ref:`PEC theory section ` for more details. This is equivalent to ``Neumann``. This boundary condition does not work with the spectral solver. + + * ``pec_insulator``: This option specifies a mixed perfect electric conductor and insulator boundary, where some part of the + boundary is PEC and some is insulator. In the insulator portion, the normal fields are extrapolated and the tangential fields + are either set to the specified value or extrapolated. The region that is insulator is specified using a spatially dependent expression with the insulator being in the area where the value of the expression is greater than zero. + The expressions are given for the low and high boundary on each axis, as listed below. The tangential fields are specified as + expressions that can depend on the location and time. The tangential fields are in two pairs, the electric fields and the + magnetic fields. In each pair, if one is specified, the other will be set to zero if not also specified. + + * ``insulator.area_x_lo(y,z)``: For the lower x (or r) boundary, expression specifying the insulator location + + * ``insulator.area_x_hi(y,z)``: For the upper x (or r) boundary, expression specifying the insulator location + + * ``insulator.area_y_lo(x,z)``: For the lower y boundary, expression specifying the insulator location + + * ``insulator.area_y_hi(x,z)``: For the upper y boundary, expression specifying the insulator location + + * ``insulator.area_z_lo(x,y)``: For the lower z boundary, expression specifying the insulator location + + * ``insulator.area_z_hi(x,y)``: For the upper z boundary, expression specifying the insulator location + + * ``insulator.Ey_x_lo(y,z,t)``, ``insulator.Ez_x_lo(y,z,t)``, ``insulator.By_x_lo(y,z,t)``, ``insulator.Bz_x_lo(y,z,t)``: expressions of the tangential field values for the lower x (or r) boundary + + * ``insulator.Ey_x_hi(y,z,t)``, ``insulator.Ez_x_hi(y,z,t)``, ``insulator.By_x_hi(y,z,t)``, ``insulator.Bz_x_hi(y,z,t)``: expressions of the tangential field values for the upper x (or r) boundary + + * ``insulator.Ex_y_lo(x,z,t)``, ``insulator.Ez_y_lo(x,z,t)``, ``insulator.Bx_y_lo(x,z,t)``, ``insulator.Bz_y_lo(x,z,t)``: expressions of the tangential field values for the lower y boundary + + * ``insulator.Ex_y_hi(x,z,t)``, ``insulator.Ez_y_hi(x,z,t)``, ``insulator.Bx_y_hi(x,z,t)``, ``insulator.Bz_y_hi(x,z,t)``: expressions of the tangential field values for the upper y boundary + + * ``insulator.Ex_z_lo(x,y,t)``, ``insulator.Ey_z_lo(x,y,t)``, ``insulator.Bx_z_lo(x,y,t)``, ``insulator.By_z_lo(x,y,t)``: expressions of the tangential field values for the lower z boundary + + * ``insulator.Ex_z_hi(x,y,t)``, ``insulator.Ey_z_hi(x,y,t)``, ``insulator.Bx_z_hi(x,y,t)``, ``insulator.By_z_hi(x,y,t)``: expressions of the tangential field values for the upper z boundary + * ``none``: No boundary condition is applied to the fields with the electromagnetic solver. This option must be used for the RZ-solver at `r=0`. * ``neumann``: For the electrostatic multigrid solver, a Neumann boundary condition (with gradient of the potential equal to 0) will be applied on the specified boundary. @@ -2096,8 +2169,8 @@ Details about the collision models can be found in the :ref:`theory section .scattering_processes`` (`strings` separated by spaces) Only for ``dsmc`` and ``background_mcc``. The scattering processes that should be - included. Available options are ``elastic``, ``back`` & ``charge_exchange`` - for ions and ``elastic``, ``excitationX`` & ``ionization`` for electrons. + included. Available options are ``elastic``, ``excitationX``, ``forward``, ``back``, and ``charge_exchange`` + for ions and ``elastic``, ``excitationX``, ``ionization`` & ``forward`` for electrons. Multiple excitation events can be included for electrons corresponding to excitation to different levels, the ``X`` above can be changed to a unique identifier for each excitation process. For each scattering process specified @@ -2155,10 +2228,13 @@ Time step Filtering ^^^^^^^^^ -* ``warpx.use_filter`` (`0` or `1`; default: `1`, except for RZ FDTD) - Whether to smooth the charge and currents on the mesh, after depositing them from the macro-particles. +* ``warpx.use_filter`` (`0` or `1`) + Whether to use filtering in the simulation. + With the explicit evolve scheme, the filtering is turned on by default, except for RZ FDTD. + With the implicit evolve schemes, the filtering is turned off by default. + The filtering smoothes the charge and currents on the mesh, after depositing them from the macro-particles. + With implicit schemes, the electric field is also filtered (to maintain consistency for energy conservation). This uses a bilinear filter (see the :ref:`filtering section `). - The default is `1` in all cases, except for simulations in RZ geometry using the FDTD solver. With the RZ PSATD solver, the filtering is done in :math:`k`-space. .. warning:: @@ -2461,6 +2537,27 @@ Maxwell solver: kinetic-fluid hybrid * ``hybrid_pic_model.substeps`` (`int`) optional (default ``10``) If ``algo.maxwell_solver`` is set to ``hybrid``, this sets the number of sub-steps to take during the B-field update. +* ``hybrid_pic_model.holmstrom_vacuum_region`` (`bool`) optional (default ``false``) + If ``algo.maxwell_solver`` is set to ``hybrid``, this sets the vacuum region handling of the generalized Ohm's Law to suppress vacuum fluctuations. :cite:t:`param-holmstrom2013handlingvacuumregionshybrid`. + +* ``hybid_pic_model.add_external_fields`` (`bool`) optional (default ``false``) + If ``algo.maxwell_solver`` is set to ``hybrid``, this sets the hybrid solver to use split external fields defined in external_vector_potential inputs. + +* ``external_vector_potential.fields`` (list of `str`) optional (default ``empty``) + If ``hybid_pic_model.add_external_fields`` is set to ``true``, this adds a list names for external time varying vector potentials to be added to hybrid solver. + +* ``external_vector_potential..read_from_file`` (`bool`) optional (default ``false``) + If ``hybid_pic_model.add_external_fields`` is set to ``true``, this flag determines whether to load an external field or use an implcit function to evaluate the time varying field. + +* ``external_vector_potential..path`` (`str`) optional (default ``""``) + If ``external_vector_potential..read_from_file`` is set to ``true``, sets the path to an OpenPMD file that can be loaded externally in :math:`weber/m`. + +* ``external_vector_potential..A[x,y,z]_external_grid_function(x,y,z)`` (`str`) optional (default ``"0"``) + If ``external_vector_potential..read_from_file`` is set to ``false``, Sets the external vector potential to be populated by an implicit function (on the grid) in :math:`weber/m`. + +* ``external_vector_potential..A_time_external_grid_function(t)`` (`str`) optional (default ``"1"``) + This sets the relative strength of the external vector potential by a dimensionless implicit time function, which can compute the external B fields and E fields based on the value and first time derivative of the function. + .. note:: Based on results from :cite:t:`param-Stanier2020` it is recommended to use @@ -2638,7 +2735,7 @@ WarpX has five types of diagnostics: ``TimeAveraged`` diagnostics only allow field data, which they output after averaging over a period of time, ``BackTransformed`` diagnostics are used when running a simulation in a boosted frame, to reconstruct output data to the lab frame, ``BoundaryScraping`` diagnostics are used to collect the particles that are absorbed at the boundary, throughout the simulation, and -``ReducedDiags`` allow the user to compute some reduced quantity (particle temperature, max of a field) and write a small amount of data to text files. +``ReducedDiags`` enable users to compute specific reduced quantities, such as particle temperature, energy histograms, or maximum field values, and efficiently save this in-situ analyzed data to files. Similar to what is done for physical species, WarpX has a class Diagnostics that allows users to initialize different diagnostics, each of them with different fields, resolution and period. This currently applies to standard diagnostics, but should be extended to back-transformed diagnostics and reduced diagnostics (and others) in a near future. @@ -2699,48 +2796,55 @@ In-situ capabilities can be used by turning on Sensei or Ascent (provided they a Only read if ``.format = sensei``. When 1 lower left corner of the mesh is pinned to 0.,0.,0. -* ``.openpmd_backend`` (``bp``, ``h5`` or ``json``) optional, only used if ``.format = openpmd`` +* ``.openpmd_backend`` (``bp5``, ``bp4``, ``h5`` or ``json``) optional, only used if ``.format = openpmd`` `I/O backend `_ for `openPMD `_ data dumps. ``bp`` is the `ADIOS I/O library `_, ``h5`` is the `HDF5 format `_, and ``json`` is a `simple text format `_. ``json`` only works with serial/single-rank jobs. When WarpX is compiled with openPMD support, the first available backend in the order given above is taken. * ``.openpmd_encoding`` (optional, ``v`` (variable based), ``f`` (file based) or ``g`` (group based) ) only read if ``.format = openpmd``. - openPMD `file output encoding `__. + openPMD `file output encoding `__. File based: one file per timestep (slower), group/variable based: one file for all steps (faster)). - ``variable based`` is an `experimental feature with ADIOS2 `__ and not supported for back-transformed diagnostics. + ``variable based`` is an `experimental feature with ADIOS2 `__ and not supported for back-transformed diagnostics. Default: ``f`` (full diagnostics) * ``.adios2_operator.type`` (``zfp``, ``blosc``) optional, - `ADIOS2 I/O operator type `__ for `openPMD `_ data dumps. + `ADIOS2 I/O operator type `__ for `openPMD `_ data dumps. * ``.adios2_operator.parameters.*`` optional, - `ADIOS2 I/O operator parameters `__ for `openPMD `_ data dumps. + `ADIOS2 I/O operator parameters `__ for `openPMD `_ data dumps. - A typical example for `ADIOS2 output using lossless compression `__ with ``blosc`` using the ``zstd`` compressor and 6 CPU treads per MPI Rank (e.g. for a `GPU run with spare CPU resources `__): + A typical example for `ADIOS2 output using lossless compression `__ with ``blosc`` using the ``zstd`` compressor and 6 CPU treads per MPI Rank (e.g. for a `GPU run with spare CPU resources `__): .. code-block:: text - .adios2_operator.type = blosc - .adios2_operator.parameters.compressor = zstd - .adios2_operator.parameters.clevel = 1 - .adios2_operator.parameters.doshuffle = BLOSC_BITSHUFFLE - .adios2_operator.parameters.threshold = 2048 - .adios2_operator.parameters.nthreads = 6 # per MPI rank (and thus per GPU) + .adios2_operator.type = blosc + .adios2_operator.parameters.compressor = zstd + .adios2_operator.parameters.clevel = 1 + .adios2_operator.parameters.doshuffle = BLOSC_BITSHUFFLE + .adios2_operator.parameters.threshold = 2048 + .adios2_operator.parameters.nthreads = 6 # per MPI rank (and thus per GPU) or for the lossy ZFP compressor using very strong compression per scalar: .. code-block:: text - .adios2_operator.type = zfp - .adios2_operator.parameters.precision = 3 + .adios2_operator.type = zfp + .adios2_operator.parameters.precision = 3 + + For back-transformed diagnostics with ADIOS BP5, we are experimenting with a new option for variable-based encoding that "flattens" the output steps, aiming to increase write and read performance: + + .. code-block:: text + + .openpmd_backend = bp5 + .adios2_engine.parameters.FlattenSteps = on * ``.adios2_engine.type`` (``bp4``, ``sst``, ``ssc``, ``dataman``) optional, - `ADIOS2 Engine type `__ for `openPMD `_ data dumps. + `ADIOS2 Engine type `__ for `openPMD `_ data dumps. See full list of engines at `ADIOS2 readthedocs `__ * ``.adios2_engine.parameters.*`` optional, - `ADIOS2 Engine parameters `__ for `openPMD `_ data dumps. + `ADIOS2 Engine parameters `__ for `openPMD `_ data dumps. An example for parameters for the BP engine are setting the number of writers (``NumAggregators``), transparently redirecting data to burst buffers etc. A detailed list of engine-specific parameters are available at the official `ADIOS2 documentation `__ @@ -3022,15 +3126,14 @@ In addition to their usual attributes, the saved particles have Reduced Diagnostics ^^^^^^^^^^^^^^^^^^^ -``ReducedDiags`` allow the user to compute some reduced quantity (particle temperature, max of a field) and write a small amount of data to text files. +``ReducedDiags`` enable users to compute specific reduced quantities, such as particle temperature, energy histograms, or maximum field values, and efficiently save this in-situ analyzed data to files. +This shifts analysis from post-processing to runtime calculation of reduction operations (average, maximum, ...) and can greatly save disk space when "raw" particle and field outputs from `FullDiagnostics` can be avoided in favor of single values, 1D or 2D data at possibly even higher time resolution. * ``warpx.reduced_diags_names`` (`strings`, separated by spaces) - The names given by the user of simple reduced diagnostics. - Also the names of the output `.txt` files. - This reduced diagnostics aims to produce simple outputs - of the time history of some physical quantities. + A list of user-given names for reduced diagnostics. + By default, these names are also prefixing the names of output files. If ``warpx.reduced_diags_names`` is not provided in the input file, - no reduced diagnostics will be done. + no reduced diagnostics will be activated during the run. This is then used in the rest of the input deck; in this documentation we use ```` as a placeholder. @@ -3038,7 +3141,7 @@ Reduced Diagnostics The type of reduced diagnostics associated with this ````. For example, ``ParticleEnergy``, ``FieldEnergy``, etc. All available types are described below in detail. - For all reduced diagnostics, + For all reduced diagnostics that are writing tabular data into text files, the first and the second columns in the output file are the time step and the corresponding physical time in seconds, respectively. @@ -3109,6 +3212,12 @@ Reduced Diagnostics Note that the fields are averaged on the cell centers before their maximum values are computed. + * ``FieldPoyntingFlux`` + Integrates the normal Poynting flux over each domain boundary surface and also integrates the flux over time. + This provides the power and total energy loss into or out of the simulation domain. + The output columns are the flux for each dimension on the lower boundaries, then the higher boundaries, + then the integrated energy loss for each dimension on the the lower and higher boundaries. + * ``FieldProbe`` This type computes the value of each component of the electric and magnetic fields and of the Poynting vector (a measure of electromagnetic flux) at points in the domain. @@ -3545,25 +3654,76 @@ Reduced Diagnostics * ``.bin_min`` (`float`, in eV) The maximum value of :math:`\mathcal{E}^*` for which the differential luminosity is computed. + * ``DifferentialLuminosity2D`` + This type computes the two-dimensional differential luminosity between two species, defined as: + + .. math:: + + \frac{d^2\mathcal{L}}{dE_1 dE_2}(E_1, E_2, t) = \int_0^t dt'\int d\boldsymbol{x}\, \int d\boldsymbol{p}_1 \int d\boldsymbol{p}_2\; + \sqrt{ |\boldsymbol{v}_1 - \boldsymbol{v}_2|^2 - |\boldsymbol{v}_1\times\boldsymbol{v}_2|^2/c^2} \\ + f_1(\boldsymbol{x}, \boldsymbol{p}_1, t')f_2(\boldsymbol{x}, \boldsymbol{p}_2, t') \delta(E_1 - E_1(\boldsymbol{p}_1)) \delta(E_2 - E_2(\boldsymbol{p}_2)) + + where :math:`f_i` is the distribution function of species :math:`i` + (normalized such that :math:`\int \int f(\boldsymbol{x} \boldsymbol{p}, t )d\boldsymbol{x} d\boldsymbol{p} = N` + is the number of particles in species :math:`i` at time :math:`t`), + :math:`\boldsymbol{p}_i` and :math:`E_i (\boldsymbol{p}_i) = \sqrt{m_1^2c^4 + c^2 |\boldsymbol{p}_i|^2}` + are, respectively, the momentum and the energy of a particle of the :math:`i`-th species. + The 2D differential luminosity is given in units of :math:`\text{m}^{-2}.\text{eV}^{-2}`. + + * ``.species`` (`list of two strings`) + The names of the two species for which the differential luminosity is computed. + + * ``.bin_number_1`` (`int` > 0) + The number of bins in energy :math:`E_1` + + * ``.bin_max_1`` (`float`, in eV) + The minimum value of :math:`E_1` for which the 2D differential luminosity is computed. + + * ``.bin_min_1`` (`float`, in eV) + The maximum value of :math:`E_2` for which the 2D differential luminosity is compute + + * ``.bin_number_2`` (`int` > 0) + The number of bins in energy :math:`E_2` + + * ``.bin_max_2`` (`float`, in eV) + The minimum value of :math:`E_2` for which the 2D differential luminosity is computed. + + * ``.bin_min_2`` (`float`, in eV) + The minimum value of :math:`E_2` for which the 2D differential luminosity is computed. + + * ``.file_min_digits`` (`int`) optional (default `6`) + The minimum number of digits used for the iteration number appended to the diagnostic file names. + + The output is a ```` folder containing a set of openPMD files. + The values of the diagnostic are stored in a record labeled `d2L_dE1_dE2`. + An example input file and a loading python script of + using the DifferentialLuminosity2D reduced diagnostics + are given in ``Examples/Tests/diff_lumi_diag/``. + * ``Timestep`` This type outputs the simulation's physical timestep (in seconds) at each mesh refinement level. -* ``.intervals`` (`string`) +* ``reduced_diags.intervals`` (`string`) Using the `Intervals Parser`_ syntax, this string defines the timesteps at which reduced - diagnostics are written to file. + diagnostics are written to the file. + This can also be specified for the specific diagnostic by setting ``.intervals``. -* ``.path`` (`string`) optional (default `./diags/reducedfiles/`) - The path that the output file will be stored. +* ``reduced_diags.path`` (`string`) optional (default `./diags/reducedfiles/`) + The path where the output file will be stored. + This can also be specified for the specific diagnostic by setting ``.path``. -* ``.extension`` (`string`) optional (default `txt`) - The extension of the output file. +* ``reduced_diags.extension`` (`string`) optional (default `txt`) + The extension of the output file (the suffix). + This can also be specified for the specific diagnostic by setting ``.extension``. -* ``.separator`` (`string`) optional (default a `whitespace`) +* ``reduced_diags.separator`` (`string`) optional (default a `whitespace`) The separator between row values in the output file. The default separator is a whitespace. + This can also be specified for the specific diagnostic by setting ``.separator``. -* ``.precision`` (`integer`) optional (default `14`) +* ``reduced_diags.precision`` (`integer`) optional (default `14`) The precision used when writing out the data to the text files. + This can also be specified for the specific diagnostic by setting ``.precision``. Lookup tables and other settings for QED modules ------------------------------------------------ diff --git a/Docs/source/usage/python.rst b/Docs/source/usage/python.rst index 8b40684feb9..1af884b40e7 100644 --- a/Docs/source/usage/python.rst +++ b/Docs/source/usage/python.rst @@ -146,6 +146,10 @@ Particle distributions can be used for to initialize particles in a particle spe .. autoclass:: pywarpx.picmi.AnalyticDistribution +.. autoclass:: pywarpx.picmi.UniformFluxDistribution + +.. autoclass:: pywarpx.picmi.AnalyticFluxDistribution + .. autoclass:: pywarpx.picmi.ParticleListDistribution Particle layouts determine how to microscopically place macro particles in a grid cell. diff --git a/Docs/source/usage/workflows.rst b/Docs/source/usage/workflows.rst index 5c5329e18b8..fa2f73b35d0 100644 --- a/Docs/source/usage/workflows.rst +++ b/Docs/source/usage/workflows.rst @@ -1,7 +1,8 @@ +.. _usage-how-to: .. _usage-workflows: -Workflows -========= +How-To Guides +============= This section collects typical user workflows and best practices for WarpX. diff --git a/Docs/source/usage/workflows/ml_materials/run_warpx_training.py b/Docs/source/usage/workflows/ml_materials/run_warpx_training.py index 9e6b5682ec7..9a246de1cc2 100644 --- a/Docs/source/usage/workflows/ml_materials/run_warpx_training.py +++ b/Docs/source/usage/workflows/ml_materials/run_warpx_training.py @@ -260,7 +260,7 @@ def get_laser(antenna_z, profile_t_peak, fill_in=True): diag_particle_list = ["weighting", "position", "momentum"] coarse_btd_end = int((L_plasma_bulk + 0.001 + stage_spacing * (N_stage - 1)) * 100000) stage_end_snapshots = [ - f"{int((L_plasma_bulk+stage_spacing*ii)*100000)}:{int((L_plasma_bulk+stage_spacing*ii)*100000+50)}:5" + f"{int((L_plasma_bulk + stage_spacing * ii) * 100000)}:{int((L_plasma_bulk + stage_spacing * ii) * 100000 + 50)}:5" for ii in range(1) ] btd_particle_diag = picmi.LabFrameParticleDiagnostic( diff --git a/Docs/source/usage/workflows/ml_materials/train.py b/Docs/source/usage/workflows/ml_materials/train.py index 957a652e0c4..35b02c5cd44 100644 --- a/Docs/source/usage/workflows/ml_materials/train.py +++ b/Docs/source/usage/workflows/ml_materials/train.py @@ -180,7 +180,7 @@ def test_dataset(model, test_source, test_target, loss_fun): ) # Manual: Training loop END t4 = time.time() -print(f"total training time: {t4-t3:.3f}s") +print(f"total training time: {t4 - t3:.3f}s") ######### save model ######### diff --git a/Examples/CMakeLists.txt b/Examples/CMakeLists.txt index f36bcbb9973..b77a3790c36 100644 --- a/Examples/CMakeLists.txt +++ b/Examples/CMakeLists.txt @@ -21,8 +21,8 @@ endif() # dims: 1,2,RZ,3 # nprocs: 1 or 2 (maybe refactor later on to just depend on WarpX_MPI) # inputs: inputs file or PICMI script, WarpX_MPI decides w/ or w/o MPI -# analysis: analysis script, always run without MPI -# output: output file(s) to analyze +# analysis: custom test analysis command, always run without MPI +# checksum: default regression analysis command (checksum benchmark) # dependency: name of base test that must run first # function(add_warpx_test @@ -31,7 +31,7 @@ function(add_warpx_test nprocs inputs analysis - output + checksum dependency ) # cannot run MPI tests w/o MPI build @@ -72,14 +72,25 @@ function(add_warpx_test separate_arguments(ANALYSIS_LIST UNIX_COMMAND "${analysis}") list(GET ANALYSIS_LIST 0 ANALYSIS_FILE) cmake_path(SET ANALYSIS_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${ANALYSIS_FILE}") - # TODO Enable lines below to handle command-line arguments - #list(LENGTH ANALYSIS_LIST ANALYSIS_LIST_LENGTH) - #if(ANALYSIS_LIST_LENGTH GREATER 1) - # list(SUBLIST ANALYSIS_LIST 1 -1 ANALYSIS_ARGS) - # list(JOIN ANALYSIS_ARGS " " ANALYSIS_ARGS) - #else() - # set(ANALYSIS_ARGS "") - #endif() + list(LENGTH ANALYSIS_LIST ANALYSIS_LIST_LENGTH) + if(ANALYSIS_LIST_LENGTH GREATER 1) + list(SUBLIST ANALYSIS_LIST 1 -1 ANALYSIS_ARGS) + list(JOIN ANALYSIS_ARGS " " ANALYSIS_ARGS) + else() + set(ANALYSIS_ARGS "") + endif() + + # get checksum script and optional command-line arguments + separate_arguments(CHECKSUM_LIST UNIX_COMMAND "${checksum}") + list(GET CHECKSUM_LIST 0 CHECKSUM_FILE) + cmake_path(SET CHECKSUM_FILE "${CMAKE_CURRENT_SOURCE_DIR}/${CHECKSUM_FILE}") + list(LENGTH CHECKSUM_LIST CHECKSUM_LIST_LENGTH) + if(CHECKSUM_LIST_LENGTH GREATER 1) + list(SUBLIST CHECKSUM_LIST 1 -1 CHECKSUM_ARGS) + list(JOIN CHECKSUM_ARGS " " CHECKSUM_ARGS) + else() + set(CHECKSUM_ARGS "") + endif() # Python test? set(python OFF) @@ -148,6 +159,9 @@ function(add_warpx_test "amrex.fpe_trap_zero = 1" ) endif() + if(WarpX_TEST_DEBUGGER) + set(runtime_params_fpetrap "amrex.signal_handling = 0") + endif() add_test( NAME ${name}.run COMMAND @@ -175,11 +189,14 @@ function(add_warpx_test # test analysis if(analysis) + # for argparse, do not pass command-line arguments as one quoted string + separate_arguments(ANALYSIS_ARGS UNIX_COMMAND "${ANALYSIS_ARGS}") add_test( NAME ${name}.analysis COMMAND - ${THIS_Python_SCRIPT_EXE} ${ANALYSIS_FILE} - ${output} + ${THIS_Python_SCRIPT_EXE} + ${ANALYSIS_FILE} + ${ANALYSIS_ARGS} WORKING_DIRECTORY ${THIS_WORKING_DIR} ) # test analysis depends on test run @@ -187,18 +204,42 @@ function(add_warpx_test # FIXME Use helper function to handle Windows exceptions set(PYTHONPATH "$ENV{PYTHONPATH}:${CMAKE_PYTHON_OUTPUT_DIRECTORY}") # add paths for custom Python modules - set(PYTHONPATH "${PYTHONPATH}:${WarpX_SOURCE_DIR}/Regression/Checksum") set(PYTHONPATH "${PYTHONPATH}:${WarpX_SOURCE_DIR}/Regression/PostProcessingUtils") set(PYTHONPATH "${PYTHONPATH}:${WarpX_SOURCE_DIR}/Tools/Parser") set(PYTHONPATH "${PYTHONPATH}:${WarpX_SOURCE_DIR}/Tools/PostProcessing") set_property(TEST ${name}.analysis APPEND PROPERTY ENVIRONMENT "PYTHONPATH=${PYTHONPATH}") endif() + # checksum analysis + if(checksum) + # for argparse, do not pass command-line arguments as one quoted string + separate_arguments(CHECKSUM_ARGS UNIX_COMMAND "${CHECKSUM_ARGS}") + add_test( + NAME ${name}.checksum + COMMAND + ${THIS_Python_SCRIPT_EXE} + ${CHECKSUM_FILE} + ${CHECKSUM_ARGS} + WORKING_DIRECTORY ${THIS_WORKING_DIR} + ) + # test analysis depends on test run + set_property(TEST ${name}.checksum APPEND PROPERTY DEPENDS "${name}.run") + if(analysis) + # checksum analysis depends on test analysis + set_property(TEST ${name}.checksum APPEND PROPERTY DEPENDS "${name}.analysis") + endif() + # FIXME Use helper function to handle Windows exceptions + set(PYTHONPATH "$ENV{PYTHONPATH}:${CMAKE_PYTHON_OUTPUT_DIRECTORY}") + # add paths for custom Python modules + set(PYTHONPATH "${PYTHONPATH}:${WarpX_SOURCE_DIR}/Regression/Checksum") + set_property(TEST ${name}.checksum APPEND PROPERTY ENVIRONMENT "PYTHONPATH=${PYTHONPATH}") + endif() + # CI: remove test directory after run if(WarpX_TEST_CLEANUP) add_test( NAME ${name}.cleanup - COMMAND ${CMAKE_COMMAND} -E rm -rf ${THIS_WORKING_DIR} + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_SOURCE_DIR}/Examples/test_cleanup.cmake ${THIS_WORKING_DIR} ) # test cleanup depends on test run set_property(TEST ${name}.cleanup APPEND PROPERTY DEPENDS "${name}.run") @@ -206,6 +247,10 @@ function(add_warpx_test # test cleanup depends on test analysis set_property(TEST ${name}.cleanup APPEND PROPERTY DEPENDS "${name}.analysis") endif() + if(checksum) + # test cleanup depends on test analysis + set_property(TEST ${name}.cleanup APPEND PROPERTY DEPENDS "${name}.checksum") + endif() endif() # Do we depend on another test? @@ -215,6 +260,9 @@ function(add_warpx_test if(analysis) set_property(TEST ${name}.run APPEND PROPERTY DEPENDS "${dependency}.analysis") endif() + if(checksum) + set_property(TEST ${name}.run APPEND PROPERTY DEPENDS "${dependency}.checksum") + endif() if(WarpX_TEST_CLEANUP) # do not clean up dependency test before current test is completed set_property(TEST ${dependency}.cleanup APPEND PROPERTY DEPENDS "${name}.cleanup") diff --git a/Examples/Physics_applications/CMakeLists.txt b/Examples/Physics_applications/CMakeLists.txt index 7f0f0ecfaf7..ed06a840501 100644 --- a/Examples/Physics_applications/CMakeLists.txt +++ b/Examples/Physics_applications/CMakeLists.txt @@ -10,3 +10,4 @@ add_subdirectory(plasma_acceleration) add_subdirectory(plasma_mirror) add_subdirectory(spacecraft_charging) add_subdirectory(uniform_plasma) +add_subdirectory(thomson_parabola_spectrometer) diff --git a/Examples/Physics_applications/beam_beam_collision/CMakeLists.txt b/Examples/Physics_applications/beam_beam_collision/CMakeLists.txt index 09e96f04d7f..fbdb6dd221f 100644 --- a/Examples/Physics_applications/beam_beam_collision/CMakeLists.txt +++ b/Examples/Physics_applications/beam_beam_collision/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_beam_beam_collision # inputs - analysis_default_openpmd_regression.py # analysis - diags/diag1/ # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) label_warpx_test(test_3d_beam_beam_collision slow) diff --git a/Examples/Physics_applications/beam_beam_collision/analysis_default_openpmd_regression.py b/Examples/Physics_applications/beam_beam_collision/analysis_default_openpmd_regression.py deleted file mode 120000 index 73e5ec47001..00000000000 --- a/Examples/Physics_applications/beam_beam_collision/analysis_default_openpmd_regression.py +++ /dev/null @@ -1 +0,0 @@ -../../analysis_default_openpmd_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/beam_beam_collision/analysis_default_regression.py b/Examples/Physics_applications/beam_beam_collision/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Physics_applications/beam_beam_collision/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/capacitive_discharge/CMakeLists.txt b/Examples/Physics_applications/capacitive_discharge/CMakeLists.txt index 5af1d0a0664..5403e374849 100644 --- a/Examples/Physics_applications/capacitive_discharge/CMakeLists.txt +++ b/Examples/Physics_applications/capacitive_discharge/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs "inputs_base_1d_picmi.py --test --pythonsolver" # inputs - analysis_1d.py # analysis - diags/diag1000050 # output + "analysis_1d.py" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 1 # dims 2 # nprocs "inputs_base_1d_picmi.py --test --dsmc" # inputs - analysis_dsmc.py # analysis - diags/diag1000050 # output + "analysis_dsmc.py" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) @@ -26,19 +26,19 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_background_mcc # inputs - analysis_default_regression.py # analysis - diags/diag1000050 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) -# FIXME: can we make this a single precision for now? +# FIXME: can we make this single precision for now? #add_warpx_test( # test_2d_background_mcc_dp_psp # name # 2 # dims # 2 # nprocs -## inputs_test_2d_background_mcc_dp_psp # inputs -# analysis_default_regression.py # analysis -# diags/diag1000050 # output +# inputs_test_2d_background_mcc_dp_psp # inputs +# OFF # analysis +# "analysis_default_regression.py --path diags/diag1000050" # checksum # OFF # dependency #) @@ -47,7 +47,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_background_mcc_picmi.py # inputs - analysis_2d.py # analysis - diags/diag1000050 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000050 --rtol 5e-3" # checksum OFF # dependency ) diff --git a/Examples/Physics_applications/capacitive_discharge/analysis_1d.py b/Examples/Physics_applications/capacitive_discharge/analysis_1d.py index e9043e5dc01..82d98c38210 100755 --- a/Examples/Physics_applications/capacitive_discharge/analysis_1d.py +++ b/Examples/Physics_applications/capacitive_discharge/analysis_1d.py @@ -2,14 +2,8 @@ # Copyright 2022 Modern Electron, David Grote -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # fmt: off ref_density = np.array([ 1.27989677e+14, 2.23601330e+14, 2.55400265e+14, 2.55664972e+14, @@ -51,9 +45,3 @@ density_data = np.load("ion_density_case_1.npy") print(repr(density_data)) assert np.allclose(density_data, ref_density) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Physics_applications/capacitive_discharge/analysis_2d.py b/Examples/Physics_applications/capacitive_discharge/analysis_2d.py deleted file mode 100755 index d4845ffb718..00000000000 --- a/Examples/Physics_applications/capacitive_discharge/analysis_2d.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright 2021 Modern Electron - -# This script checks that the inputs_test_2d_background_mcc_picmi.py run more-or-less matches the -# results from the non-PICMI run. The PICMI run is using an external Poisson -# solver that directly solves the Poisson equation using matrix inversion -# rather than the iterative approach from the MLMG solver. - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=5e-3, -) diff --git a/Examples/Physics_applications/capacitive_discharge/analysis_dsmc.py b/Examples/Physics_applications/capacitive_discharge/analysis_dsmc.py index 1458924b35c..cdaa6bed58f 100755 --- a/Examples/Physics_applications/capacitive_discharge/analysis_dsmc.py +++ b/Examples/Physics_applications/capacitive_discharge/analysis_dsmc.py @@ -2,14 +2,8 @@ # 2023 TAE Technologies -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # fmt: off ref_density = np.array([ 1.27942709e+14, 2.23579371e+14, 2.55384387e+14, 2.55660663e+14, @@ -51,9 +45,3 @@ density_data = np.load("ion_density_case_1.npy") print(repr(density_data)) assert np.allclose(density_data, ref_density) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Physics_applications/capacitive_discharge/inputs_base_1d_picmi.py b/Examples/Physics_applications/capacitive_discharge/inputs_base_1d_picmi.py index 3de88f3b3cb..a03cf1954ad 100644 --- a/Examples/Physics_applications/capacitive_discharge/inputs_base_1d_picmi.py +++ b/Examples/Physics_applications/capacitive_discharge/inputs_base_1d_picmi.py @@ -423,7 +423,7 @@ def run_sim(self): assert hasattr(self.solver, "phi") if libwarpx.amr.ParallelDescriptor.MyProc() == 0: - np.save(f"ion_density_case_{self.n+1}.npy", self.ion_density_array) + np.save(f"ion_density_case_{self.n + 1}.npy", self.ion_density_array) # query the particle z-coordinates if this is run during CI testing # to cover that functionality diff --git a/Examples/Physics_applications/free_electron_laser/CMakeLists.txt b/Examples/Physics_applications/free_electron_laser/CMakeLists.txt index f5bc8d857d2..168f06c9859 100644 --- a/Examples/Physics_applications/free_electron_laser/CMakeLists.txt +++ b/Examples/Physics_applications/free_electron_laser/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_fel # inputs - analysis_fel.py # analysis - diags/diag_labframe # output + "analysis_fel.py diags/diag_labframe" # analysis + "analysis_default_regression.py --path diags/diag_labframe" # checksum OFF # dependency ) diff --git a/Examples/Physics_applications/free_electron_laser/analysis_default_regression.py b/Examples/Physics_applications/free_electron_laser/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Physics_applications/free_electron_laser/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/free_electron_laser/analysis_fel.py b/Examples/Physics_applications/free_electron_laser/analysis_fel.py index 3ab80d195c0..b96ddd47147 100755 --- a/Examples/Physics_applications/free_electron_laser/analysis_fel.py +++ b/Examples/Physics_applications/free_electron_laser/analysis_fel.py @@ -17,16 +17,12 @@ lab-frame diagnostics and boosted-frame diagnostics. """ -import os import sys import numpy as np from openpmd_viewer import OpenPMDTimeSeries from scipy.constants import c, e, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Physical parameters of the test gamma_bunch = 100.6 Bu = 0.5 @@ -136,10 +132,3 @@ def extract_peak_E_boost(iteration): lambda_radiation_lab = lambda_radiation_boost / (2 * gamma_boost) lambda_expected = lambda_u / (2 * gamma_boost**2) assert abs(lambda_radiation_lab - lambda_expected) / lambda_expected < 0.01 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", -) diff --git a/Examples/Physics_applications/laser_acceleration/CMakeLists.txt b/Examples/Physics_applications/laser_acceleration/CMakeLists.txt index 46e97a53d54..28b0e30c2b4 100644 --- a/Examples/Physics_applications/laser_acceleration/CMakeLists.txt +++ b/Examples/Physics_applications/laser_acceleration/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_laser_acceleration # inputs - analysis_default_regression.py # analysis - diags/diag1000100 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_laser_acceleration_fluid_boosted # inputs - analysis_1d_fluid_boosted.py # analysis - diags/diag1000001 # output + "analysis_1d_fluid_boosted.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) label_warpx_test(test_1d_laser_acceleration_fluid_boosted slow) @@ -27,8 +27,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_laser_acceleration_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000100 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -37,8 +37,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_acceleration_boosted # inputs - analysis_default_regression.py # analysis - diags/diag1000002 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -47,8 +47,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_acceleration_mr # inputs - analysis_default_regression.py # analysis - diags/diag1000200 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) @@ -57,8 +57,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_acceleration_mr_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000200 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) @@ -67,8 +67,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_refined_injection # inputs - analysis_refined_injection.py # analysis - diags/diag1000200 # output + "analysis_refined_injection.py diags/diag1000200" # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) @@ -77,8 +77,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_laser_acceleration # inputs - analysis_default_openpmd_regression.py # analysis - diags/diag1/ # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) @@ -87,8 +87,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_laser_acceleration_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000100 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -97,8 +97,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_laser_acceleration_single_precision_comms # inputs - analysis_default_openpmd_regression.py # analysis - diags/diag1/ # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) @@ -107,8 +107,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_laser_acceleration # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -117,8 +117,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_laser_acceleration_opmd # inputs - analysis_openpmd_rz.py # analysis - diags/diag1/ # output + "analysis_openpmd_rz.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) @@ -127,8 +127,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_laser_acceleration_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) label_warpx_test(test_rz_laser_acceleration_picmi slow) diff --git a/Examples/Physics_applications/laser_acceleration/analysis_1d_fluid_boosted.py b/Examples/Physics_applications/laser_acceleration/analysis_1d_fluid_boosted.py index 03369d48adf..bd45f30edbb 100755 --- a/Examples/Physics_applications/laser_acceleration/analysis_1d_fluid_boosted.py +++ b/Examples/Physics_applications/laser_acceleration/analysis_1d_fluid_boosted.py @@ -10,7 +10,6 @@ # This is a script that analyses the simulation results from # the script `inputs_1d`. This simulates a 1D WFA with Pondermotive Envelope: # REF: (Equations 20-23) https://journals.aps.org/rmp/pdf/10.1103/RevModPhys.81.1229 -import os import sys import matplotlib @@ -24,9 +23,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -187,9 +183,3 @@ def odefcn(phi, xi, kp, a0, c, tau, xi_0, lambda_laser): print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Physics_applications/laser_acceleration/analysis_openpmd_rz.py b/Examples/Physics_applications/laser_acceleration/analysis_openpmd_rz.py index 0e07ddf914c..1449e54d8ee 100755 --- a/Examples/Physics_applications/laser_acceleration/analysis_openpmd_rz.py +++ b/Examples/Physics_applications/laser_acceleration/analysis_openpmd_rz.py @@ -1,14 +1,10 @@ #!/usr/bin/env python3 -import os import sys import numpy as np import openpmd_api as io -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - filename = sys.argv[1] series = io.Series(f"{filename}/openpmd_%T.h5", io.Access.read_only) @@ -24,15 +20,15 @@ # this is in C (Python) order; r is the fastest varying index (Nm, Nz, Nr) = jt.shape -assert ( - Nm == 3 -), "Wrong number of angular modes stored or possible incorrect ordering when flushed" -assert ( - Nr == 64 -), "Wrong number of radial points stored or possible incorrect ordering when flushed" -assert ( - Nz == 512 -), "Wrong number of z points stored or possible incorrect ordering when flushed" +assert Nm == 3, ( + "Wrong number of angular modes stored or possible incorrect ordering when flushed" +) +assert Nr == 64, ( + "Wrong number of radial points stored or possible incorrect ordering when flushed" +) +assert Nz == 512, ( + "Wrong number of z points stored or possible incorrect ordering when flushed" +) assert ii.meshes["part_per_grid"][io.Mesh_Record_Component.SCALAR].shape == [ 512, @@ -64,13 +60,6 @@ electron_meanz = np.sum(np.dot(zlist, rhoe0)) / np.sum(rhoe0) beam_meanz = np.sum(np.dot(zlist, rhob0)) / np.sum(rhob0) -assert ( - (electron_meanz > 0) and (beam_meanz < 0) -), "problem with openPMD+RZ. Maybe openPMD+RZ mixed up the order of rho_ diagnostics?" - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", +assert (electron_meanz > 0) and (beam_meanz < 0), ( + "problem with openPMD+RZ. Maybe openPMD+RZ mixed up the order of rho_ diagnostics?" ) diff --git a/Examples/Physics_applications/laser_acceleration/analysis_refined_injection.py b/Examples/Physics_applications/laser_acceleration/analysis_refined_injection.py index d481075c112..8df5e422ddb 100755 --- a/Examples/Physics_applications/laser_acceleration/analysis_refined_injection.py +++ b/Examples/Physics_applications/laser_acceleration/analysis_refined_injection.py @@ -9,16 +9,12 @@ # This script tests the "warpx.refine_plasma=1" option by comparing # the actual number of electrons at step 200 to the expected value -import os import sys import yt yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -58,9 +54,3 @@ rho_slice = rho[13:51, 475] # Test uniformity up to 0.5% relative variation assert rho_slice.std() < 0.005 * abs(rho_slice.mean()) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Physics_applications/laser_ion/CMakeLists.txt b/Examples/Physics_applications/laser_ion/CMakeLists.txt index 66d53165290..cc67bef685c 100644 --- a/Examples/Physics_applications/laser_ion/CMakeLists.txt +++ b/Examples/Physics_applications/laser_ion/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_ion_acc # inputs - analysis_test_laser_ion.py # analysis - diags/diagInst/ # output + "analysis_test_laser_ion.py diags/diagInst/" # analysis + "analysis_default_regression.py --path diags/diagInst/" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_ion_acc_picmi.py # inputs - analysis_test_laser_ion.py # analysis - diags/diagInst/ # output + "analysis_test_laser_ion.py diags/diagInst/" # analysis + "analysis_default_regression.py --path diags/diagInst/" # checksum OFF # dependency ) diff --git a/Examples/Physics_applications/laser_ion/analysis_default_regression.py b/Examples/Physics_applications/laser_ion/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Physics_applications/laser_ion/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/laser_ion/analysis_test_laser_ion.py b/Examples/Physics_applications/laser_ion/analysis_test_laser_ion.py index d2106d33803..360d5d48b5f 100755 --- a/Examples/Physics_applications/laser_ion/analysis_test_laser_ion.py +++ b/Examples/Physics_applications/laser_ion/analysis_test_laser_ion.py @@ -6,9 +6,6 @@ import numpy as np import openpmd_api as io -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - def load_field_from_iteration( series, iteration: int, field: str, coord: str = None @@ -67,14 +64,6 @@ def compare_time_avg_with_instantaneous_diags(dir_inst: str, dir_avg: str): if __name__ == "__main__": - # NOTE: works only in the example directory due to relative path import - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", - ) - # TODO: implement intervals parser for PICMI that allows more complex output periods test_name = os.path.split(os.getcwd())[1] if "picmi" not in test_name: diff --git a/Examples/Physics_applications/laser_ion/inputs_test_2d_laser_ion_acc_picmi.py b/Examples/Physics_applications/laser_ion/inputs_test_2d_laser_ion_acc_picmi.py index 66ba5f64091..c869c770b99 100755 --- a/Examples/Physics_applications/laser_ion/inputs_test_2d_laser_ion_acc_picmi.py +++ b/Examples/Physics_applications/laser_ion/inputs_test_2d_laser_ion_acc_picmi.py @@ -196,7 +196,6 @@ histuH_rdiag = picmi.ReducedDiagnostic( diag_type="ParticleHistogram", name="histuH", - period=100, species=hydrogen, bin_number=1000, bin_min=0.0, @@ -208,7 +207,6 @@ histue_rdiag = picmi.ReducedDiagnostic( diag_type="ParticleHistogram", name="histue", - period=100, species=electrons, bin_number=1000, bin_min=0.0, @@ -222,7 +220,6 @@ histuzAll_rdiag = picmi.ReducedDiagnostic( diag_type="ParticleHistogram", name="histuzAll", - period=100, species=hydrogen, bin_number=1000, bin_min=-0.474, @@ -233,7 +230,6 @@ field_probe_z_rdiag = picmi.ReducedDiagnostic( diag_type="FieldProbe", name="FieldProbe_Z", - period=100, integrate=0, probe_geometry="Line", x_probe=0.0, @@ -246,7 +242,6 @@ field_probe_scat_point_rdiag = picmi.ReducedDiagnostic( diag_type="FieldProbe", name="FieldProbe_ScatPoint", - period=1, integrate=0, probe_geometry="Point", x_probe=0.0, @@ -256,7 +251,6 @@ field_probe_scat_line_rdiag = picmi.ReducedDiagnostic( diag_type="FieldProbe", name="FieldProbe_ScatLine", - period=100, integrate=1, probe_geometry="Line", x_probe=-2.5e-6, @@ -267,7 +261,8 @@ ) load_balance_costs_rdiag = picmi.ReducedDiagnostic( - diag_type="LoadBalanceCosts", name="LBC", period=100 + diag_type="LoadBalanceCosts", + name="LBC", ) # Set up simulation @@ -278,6 +273,7 @@ particle_shape="cubic", warpx_numprocs=[1, 2], # deactivate `numprocs` for dynamic load balancing warpx_use_filter=1, + warpx_reduced_diags_intervals=100, warpx_load_balance_intervals=100, warpx_load_balance_costs_update="heuristic", ) diff --git a/Examples/Physics_applications/laser_ion/plot_2d.py b/Examples/Physics_applications/laser_ion/plot_2d.py index b3aefb80606..87b2d76c8f7 100644 --- a/Examples/Physics_applications/laser_ion/plot_2d.py +++ b/Examples/Physics_applications/laser_ion/plot_2d.py @@ -120,7 +120,7 @@ def visualize_density_iteration(ts, iteration, out_dir): for ax in axs[:-1]: ax.set_xticklabels([]) axs[2].set_xlabel(r"$z$ ($\mu$m)") - fig.suptitle(f"Iteration: {it}, Time: {time/1e-15:.1f} fs") + fig.suptitle(f"Iteration: {it}, Time: {time / 1e-15:.1f} fs") plt.tight_layout() @@ -190,7 +190,7 @@ def visualize_field_iteration(ts, iteration, out_dir): for ax in axs[:-1]: ax.set_xticklabels([]) axs[2].set_xlabel(r"$z$ ($\mu$m)") - fig.suptitle(f"Iteration: {it}, Time: {time/1e-15:.1f} fs") + fig.suptitle(f"Iteration: {it}, Time: {time / 1e-15:.1f} fs") plt.tight_layout() diff --git a/Examples/Physics_applications/plasma_acceleration/CMakeLists.txt b/Examples/Physics_applications/plasma_acceleration/CMakeLists.txt index 00a0f80b457..68e81e4b9e4 100644 --- a/Examples/Physics_applications/plasma_acceleration/CMakeLists.txt +++ b/Examples/Physics_applications/plasma_acceleration/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_plasma_acceleration_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1001000 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1001000" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_plasma_acceleration_boosted # inputs - analysis_default_regression.py # analysis - diags/diag1000020 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_plasma_acceleration_mr # inputs - analysis_default_regression.py # analysis - diags/diag1000400 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000400" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_plasma_acceleration_mr_momentum_conserving # inputs - analysis_default_regression.py # analysis - diags/diag1000400 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000400" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_acceleration_boosted # inputs - analysis_default_regression.py # analysis - diags/diag1000005 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000005" # checksum OFF # dependency ) @@ -56,8 +56,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_acceleration_boosted_hybrid # inputs - analysis_default_regression.py # analysis - diags/diag1000025 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000025" # checksum OFF # dependency ) @@ -66,8 +66,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_acceleration_mr_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000002 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -76,7 +76,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_acceleration_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) diff --git a/Examples/Physics_applications/plasma_mirror/CMakeLists.txt b/Examples/Physics_applications/plasma_mirror/CMakeLists.txt index 073245f758a..0d183ebbf4c 100644 --- a/Examples/Physics_applications/plasma_mirror/CMakeLists.txt +++ b/Examples/Physics_applications/plasma_mirror/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_plasma_mirror # inputs - analysis_default_regression.py # analysis - diags/diag1000020 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) diff --git a/Examples/Physics_applications/spacecraft_charging/CMakeLists.txt b/Examples/Physics_applications/spacecraft_charging/CMakeLists.txt index 95349e525cc..f48cba16496 100644 --- a/Examples/Physics_applications/spacecraft_charging/CMakeLists.txt +++ b/Examples/Physics_applications/spacecraft_charging/CMakeLists.txt @@ -7,8 +7,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_spacecraft_charging_picmi.py # inputs - analysis.py # analysis - diags/diag1/ # output + "analysis.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() diff --git a/Examples/Physics_applications/spacecraft_charging/analysis.py b/Examples/Physics_applications/spacecraft_charging/analysis.py index 1795f5dfb6e..9e4b9e8219f 100755 --- a/Examples/Physics_applications/spacecraft_charging/analysis.py +++ b/Examples/Physics_applications/spacecraft_charging/analysis.py @@ -12,7 +12,6 @@ by the following exponential function: phi(t)=v0(1-exp(-t/tau)) """ -import os import sys import matplotlib.pyplot as plt @@ -22,8 +21,6 @@ from scipy.optimize import curve_fit yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] ts = OpenPMDTimeSeries(filename) @@ -71,13 +68,6 @@ def func(x, v0, tau): print("percentage error for v0 = " + str(diff_v0 * 100) + "%") print("percentage error for tau = " + str(diff_tau * 100) + "%") -assert (diff_v0 < tolerance_v0) and ( - diff_tau < tolerance_tau -), "Test spacecraft_charging did not pass" - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", +assert (diff_v0 < tolerance_v0) and (diff_tau < tolerance_tau), ( + "Test spacecraft_charging did not pass" ) diff --git a/Examples/Physics_applications/spacecraft_charging/analysis_default_regression.py b/Examples/Physics_applications/spacecraft_charging/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Physics_applications/spacecraft_charging/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/thomson_parabola_spectrometer/CMakeLists.txt b/Examples/Physics_applications/thomson_parabola_spectrometer/CMakeLists.txt new file mode 100644 index 00000000000..4a285ca0872 --- /dev/null +++ b/Examples/Physics_applications/thomson_parabola_spectrometer/CMakeLists.txt @@ -0,0 +1,12 @@ +# Add tests (alphabetical order) ############################################## +# + +add_warpx_test( + test_3d_thomson_parabola_spectrometer # name + 3 # dims + 1 # nprocs + inputs_test_3d_thomson_parabola_spectrometer # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency +) diff --git a/Examples/Physics_applications/thomson_parabola_spectrometer/README.rst b/Examples/Physics_applications/thomson_parabola_spectrometer/README.rst new file mode 100644 index 00000000000..10009008714 --- /dev/null +++ b/Examples/Physics_applications/thomson_parabola_spectrometer/README.rst @@ -0,0 +1,56 @@ +.. _examples-thomson_parabola_spectrometer: + +Thomson Parabola Spectrometer +============================= + +This example simulates a Thomson parabola spectrometer (TPS) :cite:t:`ex-Rhee1987`. + +A TPS is a type of detector that separates incoming ions according to their charge-to-mass ratio (:math:`q/m`) and initial velocity (hence energy :math:`E_0 = 1/2 m v_0^2` if we assume non-relativistic dynamics). +TPSs are often used in laser-driven ion acceleration experiments, where different ion species are accelerated at once. To mimic this, we initialize a point-like source of 3 different ion species with different :math:`q/m` and :math:`E_0` (i.e. all ions have the same initial position, representative of a pinhole). + +The ions propagate along :math:`z` through 4 subsequent regions: + + - a vacuum region, the distance between the pinhole and the TPS (0.1 m) + - a region of constant electric field along :math:`x`, (0.19 m, 1e5 V/m) + - a region of constant magnetic field along :math:`x`, (0.872 T, 0.12 m) + - a vacuum region, the distance between the TPS and the screen of the detector (0.2 m) + +The initial particle velocity :math:`v_0` is sampled from a uniform distribution in the range :math:`[v_{min}, v_{max}]` where :math:`v_{min} = \sqrt{E_{max}/m}`, :math:`v_{max} = \sqrt{2E_{max}/m}`, and :math:`E_{max}` is an input parameter for each species. We assume zero transverse momentum. + +The ions are assumed to be test particles embedded in prescribed external fields, meaning that we neglect the self-field due to the ions' motion and the ions do not interact with each other. + +The detector is modeled using a ``BoundaryScrapingDiagnostic`` at the upper :math:`z` boundary of the domain, which stores the attributes of the particles when they exit the simulation box from the corresponding edge. Note that the transverse box size is large enough such that all particles exit the domain from the upper :math:`z` side. + +Run +--- + +The PICMI input file is not available for this example yet. + +For `MPI-parallel `__ runs, prefix these lines with ``mpiexec -n 4 ...`` or ``srun -n 4 ...``, depending on the system. + +.. literalinclude:: inputs_test_3d_thomson_parabola_spectrometer + :language: ini + :caption: You can copy this file from ``Examples/Physics_applications/thomson_parabola_spectrometer/inputs_test_3d_thomson_parabola_spectrometer``. + +Visualize +--------- + +This figure below shows the ion trajectories starting from the pinhole (black star), entering the E and B field regions (purple box), up to the detector (gray plane). +The colors represent the different species: protons in blue, C :sup:`+4` in red, and C :sup:`+6` in green. +The particles are accelerated and deflected through the TPS. + +.. figure:: https://gist.github.com/assets/17280419/3e45e5aa-d1fc-46e3-aa24-d9e0d6a74d1a + :alt: Ion trajectories through a synthetic TPS. + :width: 100% + +In our simulation, the virtual detector stores all the particle data once entering it (i.e. exiting the simulation box). +The figure below shows the ions colored according to their species (same as above) and shaded according to their initial energy. +The :math:`x` coordinate represents the electric deflection, while :math:`y` the magnetic deflection. + +.. figure:: https://gist.github.com/assets/17280419/4dd1adb7-b4ab-481d-bc24-8a7ca51471d9 + :alt: Synthetic TPS screen. + :width: 100% + +.. literalinclude:: analysis.py + :language: ini + :caption: You can copy this file from ``Examples/Physics_applications/thomson_parabola_spectrometer/analysis.py``. diff --git a/Examples/Physics_applications/thomson_parabola_spectrometer/analysis.py b/Examples/Physics_applications/thomson_parabola_spectrometer/analysis.py new file mode 100755 index 00000000000..6f61ed92c72 --- /dev/null +++ b/Examples/Physics_applications/thomson_parabola_spectrometer/analysis.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 + +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np +from openpmd_viewer import OpenPMDTimeSeries +from scipy.constants import c, eV + +mpl.use("Agg") +mpl.rcParams.update({"font.size": 18}) + +MeV = 1e6 * eV + +# open the BoundaryScrapingDiagnostic that represents the detector +series = OpenPMDTimeSeries("./diags/screen/particles_at_zhi/") +# open the Full diagnostic at time zero +series0 = OpenPMDTimeSeries("./diags/diag0/") +# we use the data at time 0 to retrieve the initial energy +# of all the particles the boundary + +# timesteps and real times +it = series.iterations +time = series.t # s +N_iterations = len(it) + +# list of species names +species = series.avail_species +N_species = len(species) + +fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 8), dpi=300) + +# some stuff for plotting +vmin = 0 +vmax = 50 +cmap = ["Reds", "Greens", "Blues"] + +# loop through the species +for s in range(N_species): + print(species[s]) + + # arrays of positions and energies + X, Y, E = [], [], [] + for i in range(N_iterations): + # get particles at detector location + x, y, z, ids = series.get_particle( + ["x", "y", "z", "id"], iteration=it[i], species=species[s], plot=False + ) + # get particles at initialization + uz0, ids0, m = series0.get_particle( + ["uz", "id", "mass"], + iteration=series0.iterations[0], + species=species[s], + plot=False, + ) + + indeces = np.where(np.in1d(ids0, ids))[0] + + E = np.append(E, 0.5 * m[indeces] * (uz0[indeces] * c) ** 2 / MeV) + X = np.append(X, x) + Y = np.append(Y, y) + print(np.min(E), np.max(E)) + + # sort particles according to energy for nicer plot + sorted_indeces = np.argsort(E) + ax.scatter( + X[sorted_indeces], + Y[sorted_indeces], + c=E[sorted_indeces], + vmin=vmin, + vmax=vmax, + cmap=cmap[s], + ) + sorted_indeces = np.argsort(E) + ax.scatter( + X[sorted_indeces], + Y[sorted_indeces], + c=E[sorted_indeces], + vmin=vmin, + vmax=vmax, + cmap=cmap[s], + ) + +# dummy plot just to have a neutral colorbar +im = ax.scatter(np.nan, np.nan, c=np.nan, cmap="Greys_r", vmin=vmin, vmax=vmax) +plt.colorbar(im, label="E [MeV]") +ax.set_xlabel("x [m]") +ax.set_ylabel("y [m]") + +plt.tight_layout() +fig.savefig("detect.png", dpi=300) +plt.close() diff --git a/Examples/Physics_applications/thomson_parabola_spectrometer/analysis_default_regression.py b/Examples/Physics_applications/thomson_parabola_spectrometer/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Physics_applications/thomson_parabola_spectrometer/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Physics_applications/thomson_parabola_spectrometer/inputs_test_3d_thomson_parabola_spectrometer b/Examples/Physics_applications/thomson_parabola_spectrometer/inputs_test_3d_thomson_parabola_spectrometer new file mode 100644 index 00000000000..04e238da86d --- /dev/null +++ b/Examples/Physics_applications/thomson_parabola_spectrometer/inputs_test_3d_thomson_parabola_spectrometer @@ -0,0 +1,192 @@ +############## +#### CONSTANTS +############## +my_constants.MeV = 1e6*q_e + +# distance between pinhole and electric field +my_constants.d1 = 0.1 # m +# length of the electric field region +my_constants.d2 = 0.19 # m +# length of the magnetic field region +my_constants.d3 = 0.12 # m +# distance between the magnetic field and the screen +my_constants.d4 = 0.2 # m + +# constant fields in the TPS +my_constants.E0 = 1e5 # V/m +my_constants.B0 = 0.872 # T + +# transverse domain +my_constants.xmin = -0.4 # m +my_constants.xmax = 0.4 # m +my_constants.ymin = -0.4 # m +my_constants.ymax = 0.4 # m + +# longitudinal domain +my_constants.zmin= -1e-3 # m +my_constants.zmax = d1+d2+d3+d4 + +# each macroparticle corresponds to 1 real particle +my_constants.N_real_particles = 1e3 +my_constants.N_macro_particles = 1e3 + +# maximum energy of the different species +# we assume that all the species have a +# uniform energy distribution in [0.5*Emax,Emax] +my_constants.Emax_hydrogen1_1 = 40*MeV +my_constants.Emax_carbon12_6 = 20*MeV +my_constants.Emax_carbon12_4 = 20*MeV + +# velocity of a very slow particle +# used to estimate the simulation time +my_constants.vz = sqrt(2*1*MeV/(12*m_p)) +my_constants.max_steps = 400 +my_constants.max_time = (-zmin+d1+d2+d3+d4) / vz +my_constants.dt = max_time / max_steps + +############# +#### NUMERICS +############# +algo.particle_shape = 1 +algo.maxwell_solver = none +algo.particle_pusher = boris +amr.max_level = 0 +warpx.verbose = 1 + +######## +#### BOX +######## +amr.n_cell = 8 8 8 +geometry.dims = 3 +geometry.prob_hi = xmax ymax zmax +geometry.prob_lo = xmin ymin zmin + +######### +#### TIME +######### +stop_time = max_time +warpx.const_dt = dt + +############# +#### BOUNDARY +############# +boundary.particle_hi = absorbing absorbing absorbing +boundary.particle_lo = absorbing absorbing absorbing + +############## +#### PARTICLES +############## +particles.species_names = hydrogen1_1 carbon12_6 carbon12_4 + +hydrogen1_1.charge = q_e +hydrogen1_1.initialize_self_fields = 0 +hydrogen1_1.injection_style = gaussian_beam +hydrogen1_1.mass = m_p +hydrogen1_1.momentum_distribution_type = uniform +hydrogen1_1.npart = N_macro_particles +hydrogen1_1.q_tot = N_real_particles*q_e +hydrogen1_1.ux_min = 0 +hydrogen1_1.uy_min = 0 +hydrogen1_1.uz_min = sqrt(Emax_hydrogen1_1/m_p)/clight +hydrogen1_1.ux_max = 0 +hydrogen1_1.uy_max = 0 +hydrogen1_1.uz_max = sqrt(2*Emax_hydrogen1_1/m_p)/clight +hydrogen1_1.x_m = 0 +hydrogen1_1.x_rms = 0 +hydrogen1_1.y_m = 0 +hydrogen1_1.y_rms = 0 +hydrogen1_1.z_m = 0 +hydrogen1_1.z_rms = 0 +hydrogen1_1.do_not_gather = 1 +hydrogen1_1.do_not_deposit = 1 + +# carbon12_6 means carbon ions with 12 nucleons, of which 6 protons +carbon12_6.charge = 6*q_e +carbon12_6.initialize_self_fields = 0 +carbon12_6.injection_style = gaussian_beam +carbon12_6.mass = 12*m_p +carbon12_6.momentum_distribution_type = uniform +carbon12_6.npart = N_macro_particles +carbon12_6.q_tot = N_real_particles*6*q_e +carbon12_6.ux_min = 0 +carbon12_6.uy_min = 0 +carbon12_6.uz_min = sqrt(Emax_carbon12_6/(12*m_p))/clight +carbon12_6.ux_max = 0 +carbon12_6.uy_max = 0 +carbon12_6.uz_max = sqrt(2*Emax_carbon12_6/(12*m_p))/clight +carbon12_6.x_m = 0 +carbon12_6.x_rms = 0 +carbon12_6.y_m = 0 +carbon12_6.y_rms = 0 +carbon12_6.z_m = 0 +carbon12_6.z_rms = 0 +carbon12_6.do_not_gather = 1 +carbon12_6.do_not_deposit = 1 + +carbon12_4.charge = 4*q_e +carbon12_4.initialize_self_fields = 0 +carbon12_4.injection_style = gaussian_beam +carbon12_4.mass = 12*m_p +carbon12_4.momentum_distribution_type = uniform +carbon12_4.npart = N_macro_particles +carbon12_4.q_tot = N_real_particles*4*q_e +carbon12_4.ux_min = 0 +carbon12_4.uy_min = 0 +carbon12_4.uz_min = sqrt(Emax_carbon12_4/(12*m_p))/clight +carbon12_4.ux_max = 0 +carbon12_4.uy_max = 0 +carbon12_4.uz_max = sqrt(2*Emax_carbon12_4/(12*m_p))/clight +carbon12_4.x_m = 0 +carbon12_4.x_rms = 0 +carbon12_4.y_m = 0 +carbon12_4.y_rms = 0 +carbon12_4.z_m = 0 +carbon12_4.z_rms = 0 +carbon12_4.do_not_gather = 1 +carbon12_4.do_not_deposit = 1 + +########### +#### FIELDS +########### +particles.E_ext_particle_init_style = parse_E_ext_particle_function +particles.Ex_external_particle_function(x,y,z,t) = "E0*(z>d1)*(z<(d1+d2))" +particles.Ey_external_particle_function(x,y,z,t) = 0 +particles.Ez_external_particle_function(x,y,z,t) = 0 + +particles.B_ext_particle_init_style = parse_B_ext_particle_function +particles.Bx_external_particle_function(x,y,z,t) = "B0*(z>d1+d2)*(z<(d1+d2+d3))" +particles.By_external_particle_function(x,y,z,t) = 0 +particles.Bz_external_particle_function(x,y,z,t) = 0 + +################ +#### DIAGNOSTICS +################ +diagnostics.diags_names = diag0 screen diag1 + +diag0.diag_type = Full +diag0.fields_to_plot = none +diag0.format = openpmd +diag0.intervals = 0:0 +diag0.write_species = 1 +diag0.species = hydrogen1_1 carbon12_6 carbon12_4 +diag0.dump_last_timestep = 0 + +# diagnostic that collects the particles at the detector's position, +# i.e. when a particle exits the domain from z_max = zhi +# we store it in the screen diagnostic +# we are assuming that most particles will exit the domain at z_max +# which requires a large enough transverse box +screen.diag_type = BoundaryScraping +screen.format = openpmd +screen.intervals = 1 +hydrogen1_1.save_particles_at_zhi = 1 +carbon12_6.save_particles_at_zhi = 1 +carbon12_4.save_particles_at_zhi = 1 + +diag1.diag_type = Full +diag1.fields_to_plot = rho_hydrogen1_1 rho_carbon12_6 rho_carbon12_4 +diag1.format = openpmd +diag1.intervals = 50:50 +diag1.write_species = 1 +diag1.species = hydrogen1_1 carbon12_6 carbon12_4 +diag1.dump_last_timestep = 0 diff --git a/Examples/Physics_applications/uniform_plasma/CMakeLists.txt b/Examples/Physics_applications/uniform_plasma/CMakeLists.txt index 79dec989c1f..6d0f37ab726 100644 --- a/Examples/Physics_applications/uniform_plasma/CMakeLists.txt +++ b/Examples/Physics_applications/uniform_plasma/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_uniform_plasma # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_uniform_plasma # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_uniform_plasma_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000010 # output + "analysis_default_restart.py diags/diag1000010" # analysis + "analysis_default_regression.py --path diags/diag1000010 --rtol 1e-12" # checksum test_3d_uniform_plasma # dependency ) diff --git a/Examples/Tests/CMakeLists.txt b/Examples/Tests/CMakeLists.txt index 6fea9368e78..b80e6158f49 100644 --- a/Examples/Tests/CMakeLists.txt +++ b/Examples/Tests/CMakeLists.txt @@ -15,6 +15,7 @@ add_subdirectory(electrostatic_sphere) add_subdirectory(electrostatic_sphere_eb) add_subdirectory(embedded_boundary_cube) add_subdirectory(embedded_boundary_diffraction) +add_subdirectory(embedded_boundary_em_particle_absorption) add_subdirectory(embedded_boundary_python_api) add_subdirectory(embedded_boundary_rotated_cube) add_subdirectory(embedded_circle) @@ -40,6 +41,7 @@ add_subdirectory(nci_fdtd_stability) add_subdirectory(nci_psatd_stability) add_subdirectory(nodal_electrostatic) add_subdirectory(nuclear_fusion) +add_subdirectory(ohm_solver_cylinder_compression) add_subdirectory(ohm_solver_em_modes) add_subdirectory(ohm_solver_ion_beam_instability) add_subdirectory(ohm_solver_ion_Landau_damping) @@ -70,7 +72,9 @@ add_subdirectory(resampling) add_subdirectory(restart) add_subdirectory(restart_eb) add_subdirectory(rigid_injection) +add_subdirectory(secondary_ion_emission) add_subdirectory(scraping) +add_subdirectory(effective_potential_electrostatic) add_subdirectory(silver_mueller) add_subdirectory(single_particle) add_subdirectory(space_charge_initialization) diff --git a/Examples/Tests/accelerator_lattice/CMakeLists.txt b/Examples/Tests/accelerator_lattice/CMakeLists.txt index f3a28d30d4a..accccde34d0 100644 --- a/Examples/Tests/accelerator_lattice/CMakeLists.txt +++ b/Examples/Tests/accelerator_lattice/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_hard_edged_quadrupoles # inputs - analysis.py # analysis - diags/diag1000050 # output + "analysis.py diags/diag1000050" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_hard_edged_quadrupoles_boosted # inputs - analysis.py # analysis - diags/diag1000050 # output + "analysis.py diags/diag1000050" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_hard_edged_quadrupoles_moving # inputs - analysis.py # analysis - diags/diag1000050 # output + "analysis.py diags/diag1000050" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) diff --git a/Examples/Tests/accelerator_lattice/analysis.py b/Examples/Tests/accelerator_lattice/analysis.py index b208d086d8c..331c5322e03 100755 --- a/Examples/Tests/accelerator_lattice/analysis.py +++ b/Examples/Tests/accelerator_lattice/analysis.py @@ -15,7 +15,6 @@ The motion is slow enough that relativistic effects are ignored. """ -import os import sys import numpy as np @@ -23,8 +22,6 @@ from scipy.constants import c, e, m_e yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] ds = yt.load(filename) @@ -121,18 +118,14 @@ def applylens(x0, vx0, vz0, gamma, lens_length, lens_strength): xx = xx + dt * vx # Compare the analytic to the simulated final values -print(f"Error in x position is {abs(np.abs((xx - xx_sim)/xx))}, which should be < 0.01") print( - f"Error in x velocity is {abs(np.abs((ux - ux_sim)/ux))}, which should be < 0.002" + f"Error in x position is {abs(np.abs((xx - xx_sim) / xx))}, which should be < 0.01" +) +print( + f"Error in x velocity is {abs(np.abs((ux - ux_sim) / ux))}, which should be < 0.002" ) assert abs(np.abs((xx - xx_sim) / xx)) < 0.01, Exception("error in x particle position") assert abs(np.abs((ux - ux_sim) / ux)) < 0.002, Exception( "error in x particle velocity" ) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/accelerator_lattice/analysis_default_regression.py b/Examples/Tests/accelerator_lattice/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/accelerator_lattice/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/boosted_diags/CMakeLists.txt b/Examples/Tests/boosted_diags/CMakeLists.txt index 8deb7f2bee2..b749d7153ea 100644 --- a/Examples/Tests/boosted_diags/CMakeLists.txt +++ b/Examples/Tests/boosted_diags/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_laser_acceleration_btd # inputs - analysis.py # analysis - diags/diag1000003 # output + "analysis.py diags/diag1000003" # analysis + "analysis_default_regression.py --path diags/diag1000003" # checksum OFF # dependency ) diff --git a/Examples/Tests/boosted_diags/analysis.py b/Examples/Tests/boosted_diags/analysis.py index 0d4794a8894..3c26b343d78 100755 --- a/Examples/Tests/boosted_diags/analysis.py +++ b/Examples/Tests/boosted_diags/analysis.py @@ -16,7 +16,6 @@ between the full back-transformed diagnostic and the reduced diagnostic (i.e., x-z slice) . """ -import os import sys import numpy as np @@ -26,9 +25,6 @@ yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - filename = sys.argv[1] # Tolerances to check consistency between legacy BTD and new BTD @@ -55,9 +51,3 @@ ts = OpenPMDTimeSeries("./diags/diag2/") (w,) = ts.get_particle(["w"], species="beam", iteration=3) assert (400 < len(w)) & (len(w) < 600) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/boosted_diags/analysis_default_regression.py b/Examples/Tests/boosted_diags/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/boosted_diags/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/boundaries/CMakeLists.txt b/Examples/Tests/boundaries/CMakeLists.txt index fccd45e2ebf..00a53742cb9 100644 --- a/Examples/Tests/boundaries/CMakeLists.txt +++ b/Examples/Tests/boundaries/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_particle_boundaries # inputs - analysis.py # analysis - diags/diag1000008 # output + "analysis.py diags/diag1000008" # analysis + "analysis_default_regression.py --path diags/diag1000008" # checksum OFF # dependency ) diff --git a/Examples/Tests/boundaries/analysis.py b/Examples/Tests/boundaries/analysis.py index ce3251ea406..29de2bb37cb 100755 --- a/Examples/Tests/boundaries/analysis.py +++ b/Examples/Tests/boundaries/analysis.py @@ -14,7 +14,6 @@ and checks that they end up in the correct place (or are deleted). """ -import os import sys import numpy as np @@ -22,8 +21,6 @@ from scipy.constants import c, m_e yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # The min and max size of the box along the three axis. dmin = -1.0 @@ -104,15 +101,9 @@ def do_periodic(x): assert len(a_id) == 1, "Absorbing particles not absorbed" assert np.all(vx == -vx0), "Reflecting particle velocity not correct" assert np.all(vz == +vz0), "Periodic particle velocity not correct" -assert np.all( - np.abs((xx - xxa) / xx) < 1.0e-15 -), "Reflecting particle position not correct" -assert np.all( - np.abs((zz - zza) / zz) < 1.0e-15 -), "Periodic particle position not correct" - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], +assert np.all(np.abs((xx - xxa) / xx) < 1.0e-15), ( + "Reflecting particle position not correct" +) +assert np.all(np.abs((zz - zza) / zz) < 1.0e-15), ( + "Periodic particle position not correct" ) diff --git a/Examples/Tests/boundaries/analysis_default_regression.py b/Examples/Tests/boundaries/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/boundaries/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/btd_rz/CMakeLists.txt b/Examples/Tests/btd_rz/CMakeLists.txt index 6a85f653c65..3c4bfffb609 100644 --- a/Examples/Tests/btd_rz/CMakeLists.txt +++ b/Examples/Tests/btd_rz/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_btd # inputs - analysis.py # analysis - diags/diag1000289 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000289" # checksum OFF # dependency ) diff --git a/Examples/Tests/btd_rz/analysis.py b/Examples/Tests/btd_rz/analysis.py index 87f74599105..c3f4f0243fa 100755 --- a/Examples/Tests/btd_rz/analysis.py +++ b/Examples/Tests/btd_rz/analysis.py @@ -8,17 +8,11 @@ # fields recorded by the backtransformed diagnostics have the right amplitude, # wavelength, and envelope (i.e. gaussian envelope with the right duration. -import os -import sys - import numpy as np from openpmd_viewer import OpenPMDTimeSeries from scipy.constants import c, e, m_e from scipy.optimize import curve_fit -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - def gaussian_laser(z, a0, z0_phase, z0_prop, ctau, lambda0): """ @@ -34,8 +28,6 @@ def fit_function(z, z0_phase): return gaussian_laser(z, a0, z0_phase, z0_b + Lprop_b, ctau0, lambda0) -plotfile = sys.argv[1] - # The values must be consistent with the values provided in the simulation input t_current = 80e-15 # Time of the snapshot1 z0_antenna = -1.0e-6 # position of laser @@ -57,9 +49,3 @@ def fit_function(z, z0_phase): ## Check that the a0 agrees within 5% of the predicted value assert np.allclose(Ex, Ex_fit, atol=0.18 * Ex.max()) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/btd_rz/analysis_default_regression.py b/Examples/Tests/btd_rz/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/btd_rz/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/collider_relevant_diags/CMakeLists.txt b/Examples/Tests/collider_relevant_diags/CMakeLists.txt index 338f66970bc..d7bd38a9475 100644 --- a/Examples/Tests/collider_relevant_diags/CMakeLists.txt +++ b/Examples/Tests/collider_relevant_diags/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_collider_diagnostics # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/collider_relevant_diags/analysis.py b/Examples/Tests/collider_relevant_diags/analysis.py index 232bc47af21..17e63e69076 100755 --- a/Examples/Tests/collider_relevant_diags/analysis.py +++ b/Examples/Tests/collider_relevant_diags/analysis.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -import os import sys import numpy as np @@ -8,9 +7,6 @@ import pandas as pd from scipy.constants import c, e, hbar, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - sys.path.append("../../../../warpx/Tools/Parser/") from input_file_parser import parse_input_file @@ -179,9 +175,3 @@ def dL_dt(): # dL/dt dL_dt_cr = df[[col for col in df.columns if "dL_dt" in col]].to_numpy() assert np.allclose(dL_dt_cr, dL_dt(), rtol=1e-8) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/collider_relevant_diags/analysis_default_regression.py b/Examples/Tests/collider_relevant_diags/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/collider_relevant_diags/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/collision/CMakeLists.txt b/Examples/Tests/collision/CMakeLists.txt index 36f8a1cb1d6..522dafbfbfb 100644 --- a/Examples/Tests/collision/CMakeLists.txt +++ b/Examples/Tests/collision/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_collision_z # inputs - analysis_collision_1d.py # analysis - diags/diag1000600 # output + "analysis_collision_1d.py diags/diag1000600" # analysis + "analysis_default_regression.py --path diags/diag1000600" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_collision_xz # inputs - analysis_collision_2d.py # analysis - diags/diag1000150 # output + "analysis_collision_2d.py diags/diag1000150" # analysis + "analysis_default_regression.py --path diags/diag1000150" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_collision_xz_picmi.py # inputs - analysis_collision_2d.py # analysis - diags/diag1000150 # output + "analysis_collision_2d.py diags/diag1000150" # analysis + "analysis_default_regression.py --path diags/diag1000150" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_collision_iso # inputs - analysis_collision_3d_isotropization.py # analysis - diags/diag1000100 # output + "analysis_collision_3d_isotropization.py diags/diag1000100" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_collision_xyz # inputs - analysis_collision_3d.py # analysis - diags/diag1000150 # output + "analysis_collision_3d.py diags/diag1000150" # analysis + "analysis_default_regression.py --path diags/diag1000150" # checksum OFF # dependency ) @@ -56,7 +56,7 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_collision # inputs - analysis_collision_rz.py # analysis - diags/diag1000150 # output + "analysis_collision_rz.py diags/diag1000150" # analysis + "analysis_default_regression.py --path diags/diag1000150 --skip-particles" # checksum OFF # dependency ) diff --git a/Examples/Tests/collision/analysis_collision_1d.py b/Examples/Tests/collision/analysis_collision_1d.py index 97ddee0591d..d5cf8b1cebd 100755 --- a/Examples/Tests/collision/analysis_collision_1d.py +++ b/Examples/Tests/collision/analysis_collision_1d.py @@ -15,16 +15,12 @@ # Both populations belong to the same carbon12 ion species. # See test T1b from JCP 413 (2020) by D. Higginson, et al. # -import os import sys import numpy as np import yt from scipy.constants import e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file last_fn = sys.argv[1] ds = yt.load(last_fn) @@ -123,9 +119,3 @@ print("TApar at 30ps error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/collision/analysis_collision_2d.py b/Examples/Tests/collision/analysis_collision_2d.py index 7ce3e4cdf2e..7e2746be752 100755 --- a/Examples/Tests/collision/analysis_collision_2d.py +++ b/Examples/Tests/collision/analysis_collision_2d.py @@ -32,9 +32,6 @@ import post_processing_utils import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - test_name = os.path.split(os.getcwd())[1] tolerance = 0.001 @@ -120,9 +117,3 @@ post_processing_utils.check_random_filter( last_fn, random_filter_fn, random_fraction, dim, species_name ) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/collision/analysis_collision_3d.py b/Examples/Tests/collision/analysis_collision_3d.py index 59c625d3cb8..c160d020cdc 100755 --- a/Examples/Tests/collision/analysis_collision_3d.py +++ b/Examples/Tests/collision/analysis_collision_3d.py @@ -25,16 +25,12 @@ import glob import math -import os import sys import numpy import post_processing_utils import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 0.001 ng = 512 @@ -110,9 +106,3 @@ post_processing_utils.check_random_filter( last_fn, random_filter_fn, random_fraction, dim, species_name ) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/collision/analysis_collision_3d_isotropization.py b/Examples/Tests/collision/analysis_collision_3d_isotropization.py index 2cfe7f9fffd..2656c5bac4d 100755 --- a/Examples/Tests/collision/analysis_collision_3d_isotropization.py +++ b/Examples/Tests/collision/analysis_collision_3d_isotropization.py @@ -11,16 +11,12 @@ # https://smileipic.github.io/tutorials/advanced_collisions.html # https://smileipic.github.io/Smilei/Understand/collisions.html#test-cases-for-collisions -import os import sys import numpy as np import scipy.constants as sc import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - e = sc.e pi = sc.pi ep0 = sc.epsilon_0 @@ -63,9 +59,3 @@ print(f"error = {error}") print(f"tolerance = {tolerance}") assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/collision/analysis_collision_rz.py b/Examples/Tests/collision/analysis_collision_rz.py index 2df2f6500d2..b37887943f8 100755 --- a/Examples/Tests/collision/analysis_collision_rz.py +++ b/Examples/Tests/collision/analysis_collision_rz.py @@ -16,16 +16,12 @@ # tolerance: 1.0e-30 # Possible running time: ~ 1.0 s -import os import sys from glob import glob import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 1.0e-15 last_fn = sys.argv[1] @@ -54,10 +50,3 @@ print("error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/collision/analysis_default_regression.py b/Examples/Tests/collision/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/collision/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/diff_lumi_diag/CMakeLists.txt b/Examples/Tests/diff_lumi_diag/CMakeLists.txt index 481847a023d..9a4e58d0e62 100644 --- a/Examples/Tests/diff_lumi_diag/CMakeLists.txt +++ b/Examples/Tests/diff_lumi_diag/CMakeLists.txt @@ -1,22 +1,25 @@ # Add tests (alphabetical order) ############################################## # - +if(WarpX_FFT) add_warpx_test( test_3d_diff_lumi_diag_leptons # name 3 # dims 2 # nprocs inputs_test_3d_diff_lumi_diag_leptons # inputs - analysis.py # analysis - diags/diag1000080 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000080 --rtol 1e-2" # checksum OFF # dependency ) +endif() +if(WarpX_FFT) add_warpx_test( test_3d_diff_lumi_diag_photons # name 3 # dims 2 # nprocs inputs_test_3d_diff_lumi_diag_photons # inputs - analysis.py # analysis - diags/diag1000080 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000080 --rtol 1e-2" # checksum OFF # dependency ) +endif() diff --git a/Examples/Tests/diff_lumi_diag/analysis.py b/Examples/Tests/diff_lumi_diag/analysis.py index 41501b1915d..f8ed5f79779 100755 --- a/Examples/Tests/diff_lumi_diag/analysis.py +++ b/Examples/Tests/diff_lumi_diag/analysis.py @@ -5,19 +5,20 @@ # In that case, the differential luminosity can be calculated analytically. import os -import sys +import re import numpy as np -from read_raw_data import read_reduced_diags_histogram +from openpmd_viewer import OpenPMDTimeSeries -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# Extract the differential luminosity from the file -_, _, E_bin, bin_data = read_reduced_diags_histogram( - "./diags/reducedfiles/DifferentialLuminosity_beam1_beam2.txt" -) -dL_dE_sim = bin_data[-1] # Differential luminosity at the end of the simulation +# Extract the 1D differential luminosity from the file +filename = "./diags/reducedfiles/DifferentialLuminosity_beam1_beam2.txt" +with open(filename) as f: + # First line: header, contains the energies + line = f.readline() + E_bin = np.array(list(map(float, re.findall("=(.*?)\(", line)))) +data = np.loadtxt(filename) +dE_bin = E_bin[1] - E_bin[0] +dL_dE_sim = data[-1, 2:] # Differential luminosity at the end of the simulation # Beam parameters N = 1.2e10 @@ -37,28 +38,47 @@ * np.exp(-((E_bin - 2 * E_beam) ** 2) / (2 * sigma_E**2)) ) +# Extract the 2D differential luminosity from the file +series = OpenPMDTimeSeries("./diags/reducedfiles/DifferentialLuminosity2d_beam1_beam2/") +d2L_dE1_dE2_sim, info = series.get_field("d2L_dE1_dE2", iteration=80) + +# Compute the analytical 2D differential luminosity for 2 Gaussian beams +assert info.axes[0] == "E2" +assert info.axes[1] == "E1" +E2, E1 = np.meshgrid(info.E2, info.E1, indexing="ij") +d2L_dE1_dE2_th = ( + N**2 + / (2 * (2 * np.pi) ** 2 * sigma_x * sigma_y * sigma_E1 * sigma_E2) + * np.exp( + -((E1 - E_beam) ** 2) / (2 * sigma_E1**2) + - (E2 - E_beam) ** 2 / (2 * sigma_E2**2) + ) +) + # Extract test name from path test_name = os.path.split(os.getcwd())[1] print("test_name", test_name) # Pick tolerance if "leptons" in test_name: - tol = 1e-2 + tol1 = 0.02 + tol2 = 0.04 elif "photons" in test_name: # In the photons case, the particles are # initialized from a density distribution ; # tolerance is larger due to lower particle statistics - tol = 6e-2 + tol1 = 0.021 + tol2 = 0.06 -# Check that the simulation result and analytical result match -error = abs(dL_dE_sim - dL_dE_th).max() / abs(dL_dE_th).max() -print("Relative error: ", error) -print("Tolerance: ", tol) -assert error < tol +# Check that the 1D diagnostic and analytical result match +error1 = abs(dL_dE_sim - dL_dE_th).max() / abs(dL_dE_th).max() +print("Relative error: ", error1) +print("Tolerance: ", tol1) -# compare checksums -evaluate_checksum( - test_name=test_name, - output_file=sys.argv[1], - rtol=1e-2, -) +# Check that the 2D and 1D diagnostics match +error2 = abs(d2L_dE1_dE2_sim - d2L_dE1_dE2_th).max() / abs(d2L_dE1_dE2_th).max() +print("Relative error: ", error2) +print("Tolerance: ", tol2) + +assert error1 < tol1 +assert error2 < tol2 diff --git a/Examples/Tests/diff_lumi_diag/analysis_default_regression.py b/Examples/Tests/diff_lumi_diag/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/diff_lumi_diag/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/diff_lumi_diag/inputs_base_3d b/Examples/Tests/diff_lumi_diag/inputs_base_3d index ba3c823b52b..0c65850e82b 100644 --- a/Examples/Tests/diff_lumi_diag/inputs_base_3d +++ b/Examples/Tests/diff_lumi_diag/inputs_base_3d @@ -28,6 +28,7 @@ my_constants.dt = sigmaz/clight/10. ################################# ####### GENERAL PARAMETERS ###### ################################# + stop_time = T amr.n_cell = nx ny nz amr.max_grid_size = 128 @@ -93,11 +94,21 @@ diag1.dump_last_timestep = 1 diag1.species = beam1 beam2 # REDUCED -warpx.reduced_diags_names = DifferentialLuminosity_beam1_beam2 +warpx.reduced_diags_names = DifferentialLuminosity_beam1_beam2 DifferentialLuminosity2d_beam1_beam2 DifferentialLuminosity_beam1_beam2.type = DifferentialLuminosity -DifferentialLuminosity_beam1_beam2.intervals = 5 +DifferentialLuminosity_beam1_beam2.intervals = 80 DifferentialLuminosity_beam1_beam2.species = beam1 beam2 DifferentialLuminosity_beam1_beam2.bin_number = 128 DifferentialLuminosity_beam1_beam2.bin_max = 2.1*beam_energy_eV -DifferentialLuminosity_beam1_beam2.bin_min = 1.9*beam_energy_eV +DifferentialLuminosity_beam1_beam2.bin_min = 0 + +DifferentialLuminosity2d_beam1_beam2.type = DifferentialLuminosity2D +DifferentialLuminosity2d_beam1_beam2.intervals = 80 +DifferentialLuminosity2d_beam1_beam2.species = beam1 beam2 +DifferentialLuminosity2d_beam1_beam2.bin_number_1 = 128 +DifferentialLuminosity2d_beam1_beam2.bin_max_1 = 1.45*beam_energy_eV +DifferentialLuminosity2d_beam1_beam2.bin_min_1 = 0 +DifferentialLuminosity2d_beam1_beam2.bin_number_2 = 128 +DifferentialLuminosity2d_beam1_beam2.bin_max_2 = 1.45*beam_energy_eV +DifferentialLuminosity2d_beam1_beam2.bin_min_2 = 0 diff --git a/Examples/Tests/diff_lumi_diag/inputs_test_3d_diff_lumi_diag_photons b/Examples/Tests/diff_lumi_diag/inputs_test_3d_diff_lumi_diag_photons index f0ef254d911..90d66938a4a 100644 --- a/Examples/Tests/diff_lumi_diag/inputs_test_3d_diff_lumi_diag_photons +++ b/Examples/Tests/diff_lumi_diag/inputs_test_3d_diff_lumi_diag_photons @@ -3,7 +3,9 @@ FILE = inputs_base_3d # Test with electrons/positrons: use parse_density_function -beam1.species_type = electron +particles.photon_species = beam1 beam2 + +beam1.species_type = photon beam1.injection_style = "NUniformPerCell" beam1.num_particles_per_cell_each_dim = 1 1 1 beam1.profile = parse_density_function @@ -15,7 +17,7 @@ beam1.ymax = 4*sigmay beam1.zmin =-muz-4*sigmaz beam1.zmax =-muz+4*sigmaz -beam2.species_type = positron +beam2.species_type = photon beam2.injection_style = "NUniformPerCell" beam2.num_particles_per_cell_each_dim = 1 1 1 beam2.profile = parse_density_function diff --git a/Examples/Tests/divb_cleaning/CMakeLists.txt b/Examples/Tests/divb_cleaning/CMakeLists.txt index d4aae31472e..d851a7ca322 100644 --- a/Examples/Tests/divb_cleaning/CMakeLists.txt +++ b/Examples/Tests/divb_cleaning/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_divb_cleaning # inputs - analysis.py # analysis - diags/diag1000400 # output + "analysis.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400" # checksum OFF # dependency ) diff --git a/Examples/Tests/divb_cleaning/analysis.py b/Examples/Tests/divb_cleaning/analysis.py index d72226a01cc..6fcd8f6f755 100755 --- a/Examples/Tests/divb_cleaning/analysis.py +++ b/Examples/Tests/divb_cleaning/analysis.py @@ -8,15 +8,11 @@ import sys -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -import os - import numpy as np import yt yt.funcs.mylog.setLevel(50) -from checksumAPI import evaluate_checksum from scipy.constants import c # Name of the last plotfile @@ -51,9 +47,3 @@ tolerance = 1e-1 assert rel_error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/divb_cleaning/analysis_default_regression.py b/Examples/Tests/divb_cleaning/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/divb_cleaning/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/dive_cleaning/CMakeLists.txt b/Examples/Tests/dive_cleaning/CMakeLists.txt index c23c2aef539..c5fe87baad0 100644 --- a/Examples/Tests/dive_cleaning/CMakeLists.txt +++ b/Examples/Tests/dive_cleaning/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_dive_cleaning # inputs - analysis.py # analysis - diags/diag1000128 # output + "analysis.py diags/diag1000128" # analysis + "analysis_default_regression.py --path diags/diag1000128" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_dive_cleaning # inputs - analysis.py # analysis - diags/diag1000128 # output + "analysis.py diags/diag1000128" # analysis + "analysis_default_regression.py --path diags/diag1000128" # checksum OFF # dependency ) diff --git a/Examples/Tests/dive_cleaning/analysis_default_regression.py b/Examples/Tests/dive_cleaning/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/dive_cleaning/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/effective_potential_electrostatic/CMakeLists.txt b/Examples/Tests/effective_potential_electrostatic/CMakeLists.txt new file mode 100644 index 00000000000..528ee6d1e08 --- /dev/null +++ b/Examples/Tests/effective_potential_electrostatic/CMakeLists.txt @@ -0,0 +1,12 @@ +# Add tests (alphabetical order) ############################################## +# + +add_warpx_test( + test_3d_effective_potential_electrostatic_picmi # name + 3 # dims + 2 # nprocs + inputs_test_3d_effective_potential_electrostatic_picmi.py # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/field_diag/" # checksum + OFF # dependency +) diff --git a/Examples/Tests/effective_potential_electrostatic/analysis.py b/Examples/Tests/effective_potential_electrostatic/analysis.py new file mode 100755 index 00000000000..20998e0a066 --- /dev/null +++ b/Examples/Tests/effective_potential_electrostatic/analysis.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# +# --- Analysis script for the effective potential Poisson solver test. This test +# --- is based on the adiabatic plasma expansion benchmark from Connor et al. (2021) +# --- doi.org/10.1109/TPS.2021.3072353. +# --- The electron density distribution (as a function of radius) is compared +# --- with the analytically calculated density based on the input parameters +# --- of the test simulation at each output timestep. + +import dill +import matplotlib.pyplot as plt +import numpy as np +from openpmd_viewer import OpenPMDTimeSeries +from scipy.interpolate import RegularGridInterpolator + +from pywarpx import picmi + +constants = picmi.constants + +# load simulation parameters +with open("sim_parameters.dpkl", "rb") as f: + sim = dill.load(f) + +# characteristic expansion time +tau = sim["sigma_0"] * np.sqrt(sim["M"] / (constants.kb * (sim["T_e"] + sim["T_i"]))) + + +def get_analytic_density(r, t): + expansion_factor = 1.0 + t**2 / tau**2 + T = sim["T_e"] / expansion_factor + sigma = sim["sigma_0"] * np.sqrt(expansion_factor) + return ( + sim["n_plasma"] * (T / sim["T_e"]) ** 1.5 * np.exp(-(r**2) / (2.0 * sigma**2)) + ) + + +def get_radial_function(field, info): + """Helper function to transform Cartesian data to polar data and average + over theta and phi.""" + r_grid = np.linspace(0, np.max(info.z) - 1e-3, 30) + theta_grid = np.linspace(0, 2 * np.pi, 40, endpoint=False) + phi_grid = np.linspace(0, np.pi, 20) + + r, t, p = np.meshgrid(r_grid, theta_grid, phi_grid, indexing="ij") + x_sp = r * np.sin(p) * np.cos(t) + y_sp = r * np.sin(p) * np.sin(t) + z_sp = r * np.cos(p) + + interp = RegularGridInterpolator((info.x, info.y, info.z), field) + field_sp = interp((x_sp, y_sp, z_sp)) + return r_grid, np.mean(field_sp, axis=(1, 2)) + + +diag_dir = "diags/field_diag" +ts = OpenPMDTimeSeries(diag_dir, check_all_files=True) + +rms_errors = np.zeros(len(ts.iterations)) + +for ii, it in enumerate(ts.iterations): + rho_e, info = ts.get_field(field="rho_electrons", iteration=it) + r_grid, n_e = get_radial_function(-rho_e / constants.q_e, info) + + n_e_analytic = get_analytic_density(r_grid, ts.t[ii]) + rms_errors[ii] = ( + np.sqrt(np.mean(np.sum((n_e - n_e_analytic) ** 2))) / n_e_analytic[0] + ) + + plt.plot(r_grid, n_e_analytic, "k--", alpha=0.6) + plt.plot(r_grid, n_e, label=f"t = {ts.t[ii] * 1e6:.2f} $\mu$s") + +print("RMS error (%) in density: ", rms_errors) +assert np.all(rms_errors < 0.05) + +plt.ylabel("$n_e$ (m$^{-3}$)") +plt.xlabel("r (m)") +plt.grid() +plt.legend() +plt.show() diff --git a/Examples/Tests/effective_potential_electrostatic/analysis_default_regression.py b/Examples/Tests/effective_potential_electrostatic/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/effective_potential_electrostatic/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/effective_potential_electrostatic/inputs_test_3d_effective_potential_electrostatic_picmi.py b/Examples/Tests/effective_potential_electrostatic/inputs_test_3d_effective_potential_electrostatic_picmi.py new file mode 100644 index 00000000000..018739aa682 --- /dev/null +++ b/Examples/Tests/effective_potential_electrostatic/inputs_test_3d_effective_potential_electrostatic_picmi.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +# +# --- Test script for the effective potential Poisson solver. This test is based +# --- on the adiabatic plasma expansion benchmark from Connor et al. (2021) +# --- doi.org/10.1109/TPS.2021.3072353. +# --- In the benchmark an expanding plasma ball with Gaussian density distribution +# --- in the radial direction is simulated and the time evolution of the +# --- density of the electron species is compared to an approximate analytic solution. +# --- The example is modified slightly in the following ways: +# --- 1) The original example used an electromagnetic solver with absorbing +# --- boundaries while the present case encloses the plasma in a conducting +# --- sphere. +# --- 2) The domain and plasma parameters for this case has been modified to +# --- set the cell-size and time step such that the explicit electrostatic +# --- solver is unstable. + +import dill +import numpy as np +from mpi4py import MPI as mpi +from scipy.special import erf + +from pywarpx import picmi + +constants = picmi.constants + +comm = mpi.COMM_WORLD + +simulation = picmi.Simulation(warpx_serialize_initial_conditions=True, verbose=0) + +m_ion = 25 # Ion mass (electron masses) + +# Plasma parameters +n_plasma = 5e12 # Plasma density (m^-3) +sigma_0 = 22 # Initial Gaussian distribution standard deviation (Debye lengths) +T_e = 100.0 # Electron temperature (K) +T_i = 10.0 # Ion temperature (K) + +# Spatial domain +R = 86 # Radius of metallic sphere (Debye lengths) +NZ = 72 # Number of cells in each direction + +# Temporal domain (if not run as a CI test) +LT = 0.6e-6 # Simulation temporal length (s) + +# Numerical parameters +NPARTS = 500000 # Seed number of particles +DT = 0.8 # Time step (electron streaming) + +# Solver parameter +C_EP = 1.0 # Effective potential factor + +####################################################################### +# Calculate various plasma parameters based on the simulation input # +####################################################################### + +# Ion mass (kg) +M = m_ion * constants.m_e + +# Electron plasma frequency (Hz) +f_pe = np.sqrt(constants.q_e**2 * n_plasma / (constants.m_e * constants.ep0)) / ( + 2.0 * np.pi +) + +# Debye length (m) +lambda_e = np.sqrt(constants.ep0 * constants.kb * T_e / (n_plasma * constants.q_e**2)) + +# Thermal velocities (m/s) from v_th = np.sqrt(kT / m) +v_ti = np.sqrt(T_i * constants.kb / M) +v_te = np.sqrt(T_e * constants.kb / constants.m_e) + +R *= lambda_e +sigma_0 *= lambda_e + +dz = 2.0 * R / (NZ - 4) +Lz = dz * NZ +dt = DT * dz / v_te + +total_steps = int(LT / dt) +diag_steps = total_steps // 3 +total_steps = diag_steps * 3 + +# dump attributes needed for analysis to a dill pickle file +if comm.rank == 0: + parameter_dict = { + "sigma_0": sigma_0, + "M": M, + "T_i": T_i, + "T_e": T_e, + "n_plasma": n_plasma, + } + with open("sim_parameters.dpkl", "wb") as f: + dill.dump(parameter_dict, f) + +# print out plasma parameters +if comm.rank == 0: + print( + f"Initializing simulation with input parameters:\n" + f"\tT_e = {T_e:.1f} K\n" + f"\tT_i = {T_i:.1f} K\n" + f"\tn = {n_plasma:.1e} m^-3\n" + ) + print( + f"Plasma parameters:\n" + f"\tlambda_e = {lambda_e:.1e} m\n" + f"\tt_pe = {1.0 / f_pe:.1e} s\n" + f"\tv_ti = {v_ti:.1e} m/s\n" + ) + print( + f"Numerical parameters:\n" + f"\tdz/lambda_e = {dz / lambda_e:.2f}\n" + f"\tdt*w_pe = {dt * f_pe * 2.0 * np.pi:.2f}\n" + f"\tdiag steps = {diag_steps:d}\n" + f"\ttotal steps = {total_steps:d}\n" + ) + + +####################################################################### +# Set geometry and boundary conditions # +####################################################################### + +grid = picmi.Cartesian3DGrid( + number_of_cells=[NZ] * 3, + lower_bound=[-Lz / 2.0] * 3, + upper_bound=[Lz / 2.0] * 3, + lower_boundary_conditions=["neumann"] * 3, + upper_boundary_conditions=["neumann"] * 3, + lower_boundary_conditions_particles=["absorbing"] * 3, + upper_boundary_conditions_particles=["absorbing"] * 3, + warpx_max_grid_size=NZ // 2, +) +simulation.time_step_size = dt +simulation.max_steps = total_steps +simulation.current_deposition_algo = "direct" +simulation.particle_shape = 1 +simulation.verbose = 1 + +####################################################################### +# Insert spherical boundary as EB # +####################################################################### + +embedded_boundary = picmi.EmbeddedBoundary( + implicit_function=f"(x**2+y**2+z**2-{R**2})", + potential=0.0, +) +simulation.embedded_boundary = embedded_boundary + +####################################################################### +# Field solver # +####################################################################### + +solver = picmi.ElectrostaticSolver( + grid=grid, + method="Multigrid", + warpx_effective_potential=True, + warpx_effective_potential_factor=C_EP, + warpx_self_fields_verbosity=0, +) +simulation.solver = solver + +####################################################################### +# Particle types setup # +####################################################################### + +total_parts = ( + n_plasma + * sigma_0**2 + * ( + (2.0 * np.pi) ** 1.5 * sigma_0 * erf(R / (np.sqrt(2) * sigma_0)) + + 4.0 * np.pi * R * np.exp(-(R**2) / (2.0 * sigma_0**2)) + ) +) + +electrons = picmi.Species( + name="electrons", + particle_type="electron", + initial_distribution=picmi.GaussianBunchDistribution( + n_physical_particles=total_parts, + rms_bunch_size=[sigma_0] * 3, + rms_velocity=[v_te] * 3, + ), +) +simulation.add_species( + electrons, + layout=picmi.PseudoRandomLayout(grid=grid, n_macroparticles=NPARTS), +) + +ions = picmi.Species( + name="ions", + charge="q_e", + mass=M, + initial_distribution=picmi.GaussianBunchDistribution( + n_physical_particles=total_parts, + rms_bunch_size=[sigma_0] * 3, + rms_velocity=[v_ti] * 3, + ), +) +simulation.add_species( + ions, + layout=picmi.PseudoRandomLayout(grid=grid, n_macroparticles=NPARTS), +) + +####################################################################### +# Add diagnostics # +####################################################################### + +field_diag = picmi.FieldDiagnostic( + name="field_diag", + grid=grid, + period=diag_steps, + data_list=[ + "E", + "J", + "T_electrons", + "T_ions", + "phi", + "rho_electrons", + "rho_ions", + ], + write_dir="diags", + warpx_format="openpmd", + warpx_openpmd_backend="h5", +) +simulation.add_diagnostic(field_diag) + +####################################################################### +# Initialize simulation # +####################################################################### + +simulation.initialize_inputs() +simulation.initialize_warpx() + +####################################################################### +# Execute simulation # +####################################################################### + +simulation.step() diff --git a/Examples/Tests/electrostatic_dirichlet_bc/CMakeLists.txt b/Examples/Tests/electrostatic_dirichlet_bc/CMakeLists.txt index 1325d1a6bf5..039181096a8 100644 --- a/Examples/Tests/electrostatic_dirichlet_bc/CMakeLists.txt +++ b/Examples/Tests/electrostatic_dirichlet_bc/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_dirichlet_bc # inputs - analysis.py # analysis - diags/diag1000100 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_dirichlet_bc_picmi.py # inputs - analysis.py # analysis - diags/diag1000100 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) diff --git a/Examples/Tests/electrostatic_dirichlet_bc/analysis.py b/Examples/Tests/electrostatic_dirichlet_bc/analysis.py index 1b8f6923c1c..82fe061c3a8 100755 --- a/Examples/Tests/electrostatic_dirichlet_bc/analysis.py +++ b/Examples/Tests/electrostatic_dirichlet_bc/analysis.py @@ -14,16 +14,10 @@ # Possible running time: ~ 19 s import glob -import os -import re -import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - files = sorted(glob.glob("diags/diag1*"))[1:] assert len(files) > 0 @@ -45,11 +39,3 @@ assert np.allclose(potentials_lo, expected_potentials_lo, rtol=0.1) assert np.allclose(potentials_hi, expected_potentials_hi, rtol=0.1) - -# compare checksums -test_name = os.path.split(os.getcwd())[1] -test_name = re.sub("_picmi", "", test_name) # same checksums for PICMI test -evaluate_checksum( - test_name=test_name, - output_file=sys.argv[1], -) diff --git a/Examples/Tests/electrostatic_dirichlet_bc/analysis_default_regression.py b/Examples/Tests/electrostatic_dirichlet_bc/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/electrostatic_dirichlet_bc/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/electrostatic_sphere/CMakeLists.txt b/Examples/Tests/electrostatic_sphere/CMakeLists.txt index 3d17c4462f8..fc69ac8ba6e 100644 --- a/Examples/Tests/electrostatic_sphere/CMakeLists.txt +++ b/Examples/Tests/electrostatic_sphere/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000030 # output + "analysis_electrostatic_sphere.py diags/diag1000030" # analysis + "analysis_default_regression.py --path diags/diag1000030" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_lab_frame # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000030 # output + "analysis_electrostatic_sphere.py diags/diag1000030" # analysis + "analysis_default_regression.py --path diags/diag1000030" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_lab_frame_mr_emass_10 # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000002 # output + "analysis_electrostatic_sphere.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_rel_nodal # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000030 # output + "analysis_electrostatic_sphere.py diags/diag1000030" # analysis + "analysis_default_regression.py --path diags/diag1000030" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_adaptive # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000054 # output + "analysis_electrostatic_sphere.py diags/diag1000054" # analysis + "analysis_default_regression.py --path diags/diag1000054" # checksum OFF # dependency ) @@ -56,7 +56,7 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_electrostatic_sphere # inputs - analysis_electrostatic_sphere.py # analysis - diags/diag1000030 # output + "analysis_electrostatic_sphere.py diags/diag1000030" # analysis + "analysis_default_regression.py --path diags/diag1000030" # checksum OFF # dependency ) diff --git a/Examples/Tests/electrostatic_sphere/analysis_default_regression.py b/Examples/Tests/electrostatic_sphere/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/electrostatic_sphere/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/electrostatic_sphere/analysis_electrostatic_sphere.py b/Examples/Tests/electrostatic_sphere/analysis_electrostatic_sphere.py index dd15a6492f1..2176dcbd7c4 100755 --- a/Examples/Tests/electrostatic_sphere/analysis_electrostatic_sphere.py +++ b/Examples/Tests/electrostatic_sphere/analysis_electrostatic_sphere.py @@ -28,9 +28,6 @@ from scipy.constants import c from scipy.optimize import fsolve -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - yt.funcs.mylog.setLevel(0) # Open plotfile specified in command line @@ -192,9 +189,3 @@ def return_energies(iteration): assert abs((Ek_i + Ep_i) - (Ek_f + Ep_f)) < 0.003 * ( Ek_i + Ep_i ) # Check conservation of energy - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/electrostatic_sphere_eb/CMakeLists.txt b/Examples/Tests/electrostatic_sphere_eb/CMakeLists.txt index 7f7b1389119..0511212c4d5 100644 --- a/Examples/Tests/electrostatic_sphere_eb/CMakeLists.txt +++ b/Examples/Tests/electrostatic_sphere_eb/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_eb # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_eb_mixed_bc # inputs - analysis_default_regression.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) endif() @@ -31,8 +31,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_electrostatic_sphere_eb_picmi.py # inputs - analysis.py # analysis - diags/diag1000002 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) endif() @@ -43,8 +43,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_electrostatic_sphere_eb # inputs - analysis_rz.py # analysis - diags/diag1000001 # output + "analysis_rz.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles" # checksum OFF # dependency ) endif() @@ -55,8 +55,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_electrostatic_sphere_eb_mr # inputs - analysis_rz_mr.py # analysis - diags/diag1/ # output + "analysis_rz_mr.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/electrostatic_sphere_eb/analysis.py b/Examples/Tests/electrostatic_sphere_eb/analysis.py index e12070119ac..114db2871ee 100755 --- a/Examples/Tests/electrostatic_sphere_eb/analysis.py +++ b/Examples/Tests/electrostatic_sphere_eb/analysis.py @@ -4,13 +4,8 @@ # using the same reference file as for the non-PICMI test since the two # tests are otherwise the same. -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") # Check reduced diagnostics for charge on EB import numpy as np -from checksumAPI import evaluate_checksum from scipy.constants import epsilon_0 # Theoretical charge on the embedded boundary, for sphere at potential phi_0 @@ -27,9 +22,3 @@ data_eighth = np.loadtxt("diags/reducedfiles/eb_charge_one_eighth.txt") q_sim_eighth = data_eighth[1, 2] assert abs((q_sim_eighth - q_th / 8) / (q_th / 8)) < 0.06 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/electrostatic_sphere_eb/analysis_rz.py b/Examples/Tests/electrostatic_sphere_eb/analysis_rz.py index e3976c95e68..be9033e2b14 100755 --- a/Examples/Tests/electrostatic_sphere_eb/analysis_rz.py +++ b/Examples/Tests/electrostatic_sphere_eb/analysis_rz.py @@ -16,16 +16,12 @@ # tolerance: 0.004 # Possible running time: < 1 s -import os import sys import numpy as np import yt from unyt import m -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 0.0041 fn = sys.argv[1] @@ -66,10 +62,3 @@ print("max error of Er = ", errmax_Er) print("tolerance = ", tolerance) assert errmax_phi < tolerance and errmax_Er < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/electrostatic_sphere_eb/analysis_rz_mr.py b/Examples/Tests/electrostatic_sphere_eb/analysis_rz_mr.py index 586b35fc7a4..55365bd4c76 100755 --- a/Examples/Tests/electrostatic_sphere_eb/analysis_rz_mr.py +++ b/Examples/Tests/electrostatic_sphere_eb/analysis_rz_mr.py @@ -12,15 +12,11 @@ # Thus the analytical solution has the form: # phi(r) = A+B*log(r), Er(r) = -B/r. -import os import sys import numpy as np from openpmd_viewer import OpenPMDTimeSeries -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 0.004 print(f"tolerance = {tolerance}") @@ -109,10 +105,3 @@ def get_error_per_lev(ts, level): nlevels = 0 if level_fields == [] else int(level_fields[-1][-1]) for level in range(nlevels + 1): get_error_per_lev(ts, level) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", -) diff --git a/Examples/Tests/embedded_boundary_cube/CMakeLists.txt b/Examples/Tests/embedded_boundary_cube/CMakeLists.txt index 0044ed04ec8..ac509955088 100644 --- a/Examples/Tests/embedded_boundary_cube/CMakeLists.txt +++ b/Examples/Tests/embedded_boundary_cube/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 2 # dims 1 # nprocs inputs_test_2d_embedded_boundary_cube # inputs - analysis_fields_2d.py # analysis - diags/diag1000114 # output + "analysis_fields_2d.py diags/diag1000114" # analysis + "analysis_default_regression.py --path diags/diag1000114" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_embedded_boundary_cube # inputs - analysis_fields.py # analysis - diags/diag1000208 # output + "analysis_fields.py diags/diag1000208" # analysis + "analysis_default_regression.py --path diags/diag1000208" # checksum OFF # dependency ) endif() @@ -31,8 +31,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_embedded_boundary_cube_macroscopic # inputs - analysis_fields.py # analysis - diags/diag1000208 # output + "analysis_fields.py diags/diag1000208" # analysis + "analysis_default_regression.py --path diags/diag1000208" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/embedded_boundary_cube/analysis_default_regression.py b/Examples/Tests/embedded_boundary_cube/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_boundary_cube/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/embedded_boundary_cube/analysis_fields.py b/Examples/Tests/embedded_boundary_cube/analysis_fields.py index 3202ccfaca2..4cb4a60f603 100755 --- a/Examples/Tests/embedded_boundary_cube/analysis_fields.py +++ b/Examples/Tests/embedded_boundary_cube/analysis_fields.py @@ -8,9 +8,6 @@ import yt from scipy.constants import c, mu_0, pi -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # This is a script that analyses the simulation results from # the script `inputs_3d`. This simulates a TMmnp mode in a PEC cubic resonator. # The magnetic field in the simulation is given (in theory) by: @@ -109,9 +106,3 @@ Bz_sim = data[("mesh", "Bz")].to_ndarray() rel_err_z = np.sqrt(np.sum(np.square(Bz_sim - Bz_th)) / np.sum(np.square(Bz_th))) assert rel_err_z < rel_tol_err - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/embedded_boundary_cube/analysis_fields_2d.py b/Examples/Tests/embedded_boundary_cube/analysis_fields_2d.py index 454d78169b7..bb35ad93cb8 100755 --- a/Examples/Tests/embedded_boundary_cube/analysis_fields_2d.py +++ b/Examples/Tests/embedded_boundary_cube/analysis_fields_2d.py @@ -1,15 +1,11 @@ #!/usr/bin/env python3 -import os import sys import numpy as np import yt from scipy.constants import c, mu_0, pi -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # This is a script that analyses the simulation results from # the script `inputs_3d`. This simulates a TMmnp mode in a PEC cubic resonator. # The magnetic field in the simulation is given (in theory) by: @@ -62,9 +58,3 @@ # Compute relative l^2 error on Ey Ey_sim = data["Ey"].to_ndarray() rel_err_y = np.sqrt(np.sum(np.square(Ey_sim / c - By_th)) / np.sum(np.square(By_th))) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/embedded_boundary_cube/inputs_base_3d b/Examples/Tests/embedded_boundary_cube/inputs_base_3d index 9710701d871..70ddd8f8f64 100644 --- a/Examples/Tests/embedded_boundary_cube/inputs_base_3d +++ b/Examples/Tests/embedded_boundary_cube/inputs_base_3d @@ -13,8 +13,8 @@ boundary.field_lo = pec pec pec boundary.field_hi = pec pec pec eb2.geom_type = box -eb2.box_lo = -0.5 -0.5 -0.5 -eb2.box_hi = 0.5 0.5 0.5 +eb2.box_lo = -0.501 -0.501 -0.501 # Ensures that the stair-case EB is exactly at -0.5 +eb2.box_hi = 0.501 0.501 0.501 # Ensures that the stair-case EB is exactly at 0.5 eb2.box_has_fluid_inside = true # Alternatively one could use parser to build EB # Note that for amrex EB implicit function, >0 is covered, =0 is boundary and <0 is regular. diff --git a/Examples/Tests/embedded_boundary_cube/inputs_test_2d_embedded_boundary_cube b/Examples/Tests/embedded_boundary_cube/inputs_test_2d_embedded_boundary_cube index 684325dc030..46272052c2c 100644 --- a/Examples/Tests/embedded_boundary_cube/inputs_test_2d_embedded_boundary_cube +++ b/Examples/Tests/embedded_boundary_cube/inputs_test_2d_embedded_boundary_cube @@ -12,10 +12,10 @@ warpx.abort_on_warning_threshold = medium boundary.field_lo = pec pec boundary.field_hi = pec pec -my_constants.xmin = -0.5 -my_constants.zmin = -0.5 -my_constants.xmax = 0.5 -my_constants.zmax = 0.5 +my_constants.xmin = -0.501 # Ensures that the stair-case EB is exactly at -0.5 +my_constants.zmin = -0.501 # Ensures that the stair-case EB is exactly at -0.5 +my_constants.xmax = 0.501 # Ensures that the stair-case EB is exactly at 0.5 +my_constants.zmax = 0.501 # Ensures that the stair-case EB is exactly at 0.5 # Note that for amrex EB implicit function, >0 is covered, =0 is boundary and <0 is regular. warpx.eb_implicit_function = "max(max(x+xmin,-(x+xmax)), max(z+zmin,-(z+zmax)))" diff --git a/Examples/Tests/embedded_boundary_diffraction/CMakeLists.txt b/Examples/Tests/embedded_boundary_diffraction/CMakeLists.txt index 6297cf1fa5c..456e9f9b630 100644 --- a/Examples/Tests/embedded_boundary_diffraction/CMakeLists.txt +++ b/Examples/Tests/embedded_boundary_diffraction/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_embedded_boundary_diffraction # inputs - analysis_fields.py # analysis - diags/diag1/ # output + "analysis_fields.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/embedded_boundary_diffraction/analysis_default_regression.py b/Examples/Tests/embedded_boundary_diffraction/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_boundary_diffraction/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/embedded_boundary_diffraction/analysis_fields.py b/Examples/Tests/embedded_boundary_diffraction/analysis_fields.py index 8f0b7818516..599bcea71f9 100755 --- a/Examples/Tests/embedded_boundary_diffraction/analysis_fields.py +++ b/Examples/Tests/embedded_boundary_diffraction/analysis_fields.py @@ -7,16 +7,12 @@ theta_diffraction = 1.22 * lambda / d """ -import os import sys import numpy as np from openpmd_viewer import OpenPMDTimeSeries from scipy.ndimage import gaussian_filter1d -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - filename = sys.argv[1] ts = OpenPMDTimeSeries(filename) @@ -41,10 +37,3 @@ def r_first_minimum(iz): # Check that this corresponds to the prediction from the Airy pattern theta_diffraction = np.arcsin(1.22 * 0.1 / 0.4) / 2 assert np.all(abs(r[50:] - theta_diffraction * info.z[50:]) < 0.03) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", -) diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/CMakeLists.txt b/Examples/Tests/embedded_boundary_em_particle_absorption/CMakeLists.txt new file mode 100644 index 00000000000..0aa5b48b2b7 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/CMakeLists.txt @@ -0,0 +1,110 @@ +# Add tests (alphabetical order) ############################################## +# + +if(WarpX_EB) + add_warpx_test( + test_3d_embedded_boundary_em_particle_absorption_sh_factor_1 # name + 3 # dims + 1 # nprocs + inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_1 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_3d_embedded_boundary_em_particle_absorption_sh_factor_2 # name + 3 # dims + 1 # nprocs + inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_2 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_3d_embedded_boundary_em_particle_absorption_sh_factor_3 # name + 3 # dims + 1 # nprocs + inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_3 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_2d_embedded_boundary_em_particle_absorption_sh_factor_1 # name + 2 # dims + 1 # nprocs + inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_1 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_2d_embedded_boundary_em_particle_absorption_sh_factor_2 # name + 2 # dims + 1 # nprocs + inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_2 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_2d_embedded_boundary_em_particle_absorption_sh_factor_3 # name + 2 # dims + 1 # nprocs + inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_3 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_rz_embedded_boundary_em_particle_absorption_sh_factor_1 # name + RZ # dims + 1 # nprocs + inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_1 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_rz_embedded_boundary_em_particle_absorption_sh_factor_2 # name + RZ # dims + 1 # nprocs + inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_2 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() + +if(WarpX_EB) + add_warpx_test( + test_rz_embedded_boundary_em_particle_absorption_sh_factor_3 # name + RZ # dims + 1 # nprocs + inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_3 # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1" # checksum + OFF # dependency + ) +endif() diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/analysis.py b/Examples/Tests/embedded_boundary_em_particle_absorption/analysis.py new file mode 100755 index 00000000000..3ba44a8ac1b --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/analysis.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +""" +This analysis script checks that there is no spurious charge build-up when a particle is absorbed by an embedded boundary. + +More specifically, this test simulates two particles of oppposite charge that are initialized at +the same position and then move in opposite directions. The particles are surrounded by a cylindrical +embedded boundary, and are absorbed when their trajectory intersects this boundary. With an +electromagnetic solver, this can lead to spurious charge build-up (i.e., div(E)!= rho/epsion_0) +that remains at the position where particle was absorbed. + +Note that, in this test, there will also be a (non-spurious) component of div(E) that propagates +along the embedded boundary, due to electromagnetic waves reflecting on this boundary. +When checking for static, spurious charge build-up, we average div(E) in time to remove this component. + +The test is performed in 2D, 3D and RZ. +(In 2D, the cylindrical embedded boundary becomes two parallel plates) +""" + +from openpmd_viewer import OpenPMDTimeSeries + +ts = OpenPMDTimeSeries("./diags/diag1/") + +divE_stacked = ts.iterate( + lambda iteration: ts.get_field("divE", iteration=iteration)[0] +) +start_avg_iter = 25 +end_avg_iter = 100 +divE_avg = divE_stacked[start_avg_iter:end_avg_iter].mean(axis=0) + +# Adjust the tolerance so that the remaining error due to the propagating +# div(E) (after averaging) is below this tolerance, but so that any typical +# spurious charge build-up is above this tolerance. This is dimension-dependent. +dim = ts.fields_metadata["divE"]["geometry"] +if dim == "3dcartesian": + tolerance = 7e-11 +elif dim == "2dcartesian": + tolerance = 3.5e-10 +elif dim == "thetaMode": + # In RZ: there are issues with divE on axis + # Set the few cells around the axis to 0 for this test + divE_avg[:, 13:19] = 0 + tolerance = 4e-12 + + +def check_tolerance(array, tolerance): + assert abs(array).max() <= tolerance, ( + f"Test did not pass: the max error {abs(array).max()} exceeded the tolerance of {tolerance}." + ) + print("All elements of are within the tolerance.") + + +check_tolerance(divE_avg, tolerance) diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/analysis_default_regression.py b/Examples/Tests/embedded_boundary_em_particle_absorption/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_base b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_base new file mode 100644 index 00000000000..6c940d2298e --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_base @@ -0,0 +1,35 @@ +max_step = 100 +amr.max_level = 0 +amr.blocking_factor = 8 +amr.max_grid_size = 256 + +algo.charge_deposition = standard +algo.field_gathering = energy-conserving +warpx.const_dt = 1.17957283598e-09 +warpx.use_filter = 0 + +my_constants.R = 6.35 +warpx.eb_implicit_function = "(x**2 + y**2 - R**2)" + +particles.species_names = electron positron + +electron.charge = -q_e +electron.mass = m_e +electron.injection_style = "SingleParticle" +electron.single_particle_pos = 0.0 0.0 0.0 +electron.single_particle_u = 1.e20 0.0 0.4843221e20 # gamma*beta +electron.single_particle_weight = 1.0 + +positron.charge = q_e +positron.mass = m_e +positron.injection_style = "SingleParticle" +positron.single_particle_pos = 0.0 0.0 0.0 +positron.single_particle_u = -1.e20 0.0 -0.4843221e20 # gamma*beta +positron.single_particle_weight = 1.0 + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 1 +diag1.diag_type = Full +diag1.fields_to_plot = divE rho +diag1.format = openpmd diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_1 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_1 new file mode 100644 index 00000000000..99110df1634 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_1 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 2 +amr.n_cell = 32 32 +geometry.prob_lo = -10 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = pec absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 1 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_2 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_2 new file mode 100644 index 00000000000..4cdbfc5dd5e --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_2 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 2 +amr.n_cell = 32 32 +geometry.prob_lo = -10 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = pec absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 2 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_3 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_3 new file mode 100644 index 00000000000..6113f0668fe --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_2d_embedded_boundary_em_particle_absorption_sh_factor_3 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 2 +amr.n_cell = 32 32 +geometry.prob_lo = -10 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = pec absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 3 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_1 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_1 new file mode 100644 index 00000000000..ea977877a2d --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_1 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 3 +amr.n_cell = 32 32 32 +geometry.prob_lo = -10 -10 -10 +geometry.prob_hi = 10 10 10 +boundary.field_lo = pec pec absorbing_silver_mueller +boundary.field_hi = pec pec absorbing_silver_mueller + +algo.particle_shape = 1 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_2 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_2 new file mode 100644 index 00000000000..ea977877a2d --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_2 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 3 +amr.n_cell = 32 32 32 +geometry.prob_lo = -10 -10 -10 +geometry.prob_hi = 10 10 10 +boundary.field_lo = pec pec absorbing_silver_mueller +boundary.field_hi = pec pec absorbing_silver_mueller + +algo.particle_shape = 1 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_3 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_3 new file mode 100644 index 00000000000..553e5e058e7 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_3d_embedded_boundary_em_particle_absorption_sh_factor_3 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = 3 +amr.n_cell = 32 32 32 +geometry.prob_lo = -10 -10 -10 +geometry.prob_hi = 10 10 10 +boundary.field_lo = pec pec absorbing_silver_mueller +boundary.field_hi = pec pec absorbing_silver_mueller + +algo.particle_shape = 3 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_1 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_1 new file mode 100644 index 00000000000..7faf7fd8934 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_1 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = RZ +amr.n_cell = 16 32 +geometry.prob_lo = 0 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = none absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 1 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_2 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_2 new file mode 100644 index 00000000000..7faf7fd8934 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_2 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = RZ +amr.n_cell = 16 32 +geometry.prob_lo = 0 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = none absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 1 diff --git a/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_3 b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_3 new file mode 100644 index 00000000000..aad65594c96 --- /dev/null +++ b/Examples/Tests/embedded_boundary_em_particle_absorption/inputs_test_rz_embedded_boundary_em_particle_absorption_sh_factor_3 @@ -0,0 +1,11 @@ +# base input parameters +FILE = inputs_base + +geometry.dims = RZ +amr.n_cell = 16 32 +geometry.prob_lo = 0 -10 +geometry.prob_hi = 10 10 +boundary.field_lo = none absorbing_silver_mueller +boundary.field_hi = pec absorbing_silver_mueller + +algo.particle_shape = 3 diff --git a/Examples/Tests/embedded_boundary_python_api/CMakeLists.txt b/Examples/Tests/embedded_boundary_python_api/CMakeLists.txt index fe820c76f22..3e79e526218 100644 --- a/Examples/Tests/embedded_boundary_python_api/CMakeLists.txt +++ b/Examples/Tests/embedded_boundary_python_api/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_embedded_boundary_picmi.py # inputs - analysis.py # analysis - diags/diag1000002 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/embedded_boundary_python_api/analysis.py b/Examples/Tests/embedded_boundary_python_api/analysis.py deleted file mode 100755 index 7fda682f618..00000000000 --- a/Examples/Tests/embedded_boundary_python_api/analysis.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 - -# This script just checks that the PICMI file executed successfully. -# If it did there will be a plotfile for the final step. - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -step = int(sys.argv[1][-5:]) -assert step == 2 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/embedded_boundary_python_api/analysis_default_regression.py b/Examples/Tests/embedded_boundary_python_api/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_boundary_python_api/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/embedded_boundary_python_api/inputs_test_3d_embedded_boundary_picmi.py b/Examples/Tests/embedded_boundary_python_api/inputs_test_3d_embedded_boundary_picmi.py index 7148cde2d3e..7bd7cd68f25 100755 --- a/Examples/Tests/embedded_boundary_python_api/inputs_test_3d_embedded_boundary_picmi.py +++ b/Examples/Tests/embedded_boundary_python_api/inputs_test_3d_embedded_boundary_picmi.py @@ -43,7 +43,7 @@ flag_correct_div = False -solver = picmi.ElectromagneticSolver(grid=grid, method="Yee", cfl=1.0) +solver = picmi.ElectromagneticSolver(grid=grid, method="ECT", cfl=1.0) n_cavity = 30 L_cavity = n_cavity * unit diff --git a/Examples/Tests/embedded_boundary_rotated_cube/CMakeLists.txt b/Examples/Tests/embedded_boundary_rotated_cube/CMakeLists.txt index fcfe97905d8..cb7fa405210 100644 --- a/Examples/Tests/embedded_boundary_rotated_cube/CMakeLists.txt +++ b/Examples/Tests/embedded_boundary_rotated_cube/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 2 # dims 1 # nprocs inputs_test_2d_embedded_boundary_rotated_cube # inputs - analysis_fields_2d.py # analysis - diags/diag1000068 # output + "analysis_fields_2d.py diags/diag1000068" # analysis + "analysis_default_regression.py --path diags/diag1000068" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_embedded_boundary_rotated_cube # inputs - analysis_fields_3d.py # analysis - diags/diag1000111 # output + "analysis_fields_3d.py diags/diag1000111" # analysis + "analysis_default_regression.py --path diags/diag1000111" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/embedded_boundary_rotated_cube/analysis_default_regression.py b/Examples/Tests/embedded_boundary_rotated_cube/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_boundary_rotated_cube/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_2d.py b/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_2d.py index 451913fd54d..dbb74b174e7 100755 --- a/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_2d.py +++ b/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_2d.py @@ -1,15 +1,11 @@ #!/usr/bin/env python3 -import os import sys import numpy as np import yt from scipy.constants import c, mu_0, pi -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # This is a script that analyses the simulation results from # the script `inputs_3d`. This simulates a TMmnp mode in a PEC cubic resonator. # The magnetic field in the simulation is given (in theory) by: @@ -67,9 +63,3 @@ # Compute relative l^2 error on By rel_err_y = np.sqrt(np.sum(np.square(By_sim - By_th)) / np.sum(np.square(By_th))) assert rel_err_y < rel_tol_err - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_3d.py b/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_3d.py index 838c9c82479..00d1ba2280f 100755 --- a/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_3d.py +++ b/Examples/Tests/embedded_boundary_rotated_cube/analysis_fields_3d.py @@ -7,16 +7,12 @@ # License: BSD-3-Clause-LBNL -import os import sys import numpy as np import yt from scipy.constants import c, mu_0, pi -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # This is a script that analyses the simulation results from # the script `inputs_3d`. This simulates a TMmnp mode in a PEC cubic resonator rotated by pi/8. # The magnetic field in the simulation is given (in theory) by: @@ -143,9 +139,3 @@ np.sum(np.square(Bz_sim[:, :, :, 0] - Bz_th)) / np.sum(np.square(Bz_th)) ) assert rel_err_z < rel_tol_err - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/embedded_circle/CMakeLists.txt b/Examples/Tests/embedded_circle/CMakeLists.txt index 4b9ee426569..1a0577da82e 100644 --- a/Examples/Tests/embedded_circle/CMakeLists.txt +++ b/Examples/Tests/embedded_circle/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 2 # dims 2 # nprocs inputs_test_2d_embedded_circle # inputs - analysis.py # analysis - diags/diag1000011 + OFF # analysis + "analysis_default_regression.py --path diags/diag1000011 --rtol 1e-2" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/embedded_circle/analysis.py b/Examples/Tests/embedded_circle/analysis.py deleted file mode 100755 index d1bb04fedb6..00000000000 --- a/Examples/Tests/embedded_circle/analysis.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-2, -) diff --git a/Examples/Tests/embedded_circle/analysis_default_regression.py b/Examples/Tests/embedded_circle/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/embedded_circle/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/energy_conserving_thermal_plasma/CMakeLists.txt b/Examples/Tests/energy_conserving_thermal_plasma/CMakeLists.txt index c89d439b75e..a925cc537f4 100644 --- a/Examples/Tests/energy_conserving_thermal_plasma/CMakeLists.txt +++ b/Examples/Tests/energy_conserving_thermal_plasma/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_energy_conserving_thermal_plasma # inputs - analysis.py # analysis - diags/diag1000500 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) diff --git a/Examples/Tests/energy_conserving_thermal_plasma/analysis.py b/Examples/Tests/energy_conserving_thermal_plasma/analysis.py index 0d29f85e7eb..5991d888e20 100755 --- a/Examples/Tests/energy_conserving_thermal_plasma/analysis.py +++ b/Examples/Tests/energy_conserving_thermal_plasma/analysis.py @@ -12,14 +12,8 @@ # than other gathering scheme. This tests checks that the energy does not increase by # more than 0.3% over the duration of the simulatoin. -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Get energy as a function of time, from reduced diagnostics EFdata = np.genfromtxt("./diags/reducedfiles/EF.txt") # Field energy EPdata = np.genfromtxt("./diags/reducedfiles/EP.txt") # Particle energy @@ -29,9 +23,3 @@ print(abs(E - E[0]) / E[0]) # Check that the energy is conserved to 0.3% assert np.all(abs(E - E[0]) / E[0] < 0.003) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/energy_conserving_thermal_plasma/analysis_default_regression.py b/Examples/Tests/energy_conserving_thermal_plasma/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/energy_conserving_thermal_plasma/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/field_ionization/CMakeLists.txt b/Examples/Tests/field_ionization/CMakeLists.txt index 9154173ac5f..71e34dbc5fc 100644 --- a/Examples/Tests/field_ionization/CMakeLists.txt +++ b/Examples/Tests/field_ionization/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_ionization_boost # inputs - analysis.py # analysis - diags/diag1000420 # output + "analysis.py diags/diag1000420" # analysis + "analysis_default_regression.py --path diags/diag1000420" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_ionization_lab # inputs - analysis.py # analysis - diags/diag1001600 # output + "analysis.py diags/diag1001600" # analysis + "analysis_default_regression.py --path diags/diag1001600" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_ionization_picmi.py # inputs - analysis.py # analysis - diags/diag1001600 # output + "analysis.py diags/diag1001600" # analysis + "analysis_default_regression.py --path diags/diag1001600" # checksum OFF # dependency ) diff --git a/Examples/Tests/field_ionization/analysis.py b/Examples/Tests/field_ionization/analysis.py index a02c293601b..bafc47f2145 100755 --- a/Examples/Tests/field_ionization/analysis.py +++ b/Examples/Tests/field_ionization/analysis.py @@ -18,15 +18,12 @@ ions are N5+, in agreement with theory from Chen's article. """ -import os import sys import numpy as np import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Open plotfile specified in command line, and get ion's ionization level. filename = sys.argv[1] @@ -106,9 +103,3 @@ print("particle_orig_z has reasonable values") except yt.utilities.exceptions.YTFieldNotFound: pass # The backtransformed diagnostic version of the test does not have orig_z - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/field_ionization/analysis_default_regression.py b/Examples/Tests/field_ionization/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/field_ionization/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/field_probe/CMakeLists.txt b/Examples/Tests/field_probe/CMakeLists.txt index bbddbd7839e..8b052dc3b66 100644 --- a/Examples/Tests/field_probe/CMakeLists.txt +++ b/Examples/Tests/field_probe/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 2 # dims 2 # nprocs inputs_test_2d_field_probe # inputs - analysis.py # analysis - diags/diag1000544 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000544" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/field_probe/analysis.py b/Examples/Tests/field_probe/analysis.py index e974e284b65..57085fb7cdc 100755 --- a/Examples/Tests/field_probe/analysis.py +++ b/Examples/Tests/field_probe/analysis.py @@ -18,15 +18,9 @@ which can be solved analytically. """ -import os -import sys - import numpy as np import pandas as pd -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - filename = "diags/reducedfiles/FP_line.txt" # Open data file @@ -65,9 +59,3 @@ def I_envelope(x, lam=0.2e-6, a=0.3e-6, D=1.7e-6): print("Average error greater than 2.5%") assert averror < 2.5 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/field_probe/analysis_default_regression.py b/Examples/Tests/field_probe/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/field_probe/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/flux_injection/CMakeLists.txt b/Examples/Tests/flux_injection/CMakeLists.txt index 0929fc3d4c4..390c76ec58e 100644 --- a/Examples/Tests/flux_injection/CMakeLists.txt +++ b/Examples/Tests/flux_injection/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_flux_injection # inputs - analysis_flux_injection_3d.py # analysis - diags/diag1000002 # output + "analysis_flux_injection_3d.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_flux_injection # inputs - analysis_flux_injection_rz.py # analysis - diags/diag1000120 # output + "analysis_flux_injection_rz.py diags/diag1000120" # analysis + "analysis_default_regression.py --path diags/diag1000120" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_flux_injection_from_eb # inputs - analysis_flux_injection_from_eb.py # analysis - diags/diag1000010 # output + "analysis_flux_injection_from_eb.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_flux_injection_from_eb # inputs - analysis_flux_injection_from_eb.py # analysis - diags/diag1000010 # output + "analysis_flux_injection_from_eb.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) @@ -46,7 +46,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_flux_injection_from_eb # inputs - analysis_flux_injection_from_eb.py # analysis - diags/diag1000010 # output + "analysis_flux_injection_from_eb.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) diff --git a/Examples/Tests/flux_injection/analysis_default_regression.py b/Examples/Tests/flux_injection/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/flux_injection/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/flux_injection/analysis_flux_injection_3d.py b/Examples/Tests/flux_injection/analysis_flux_injection_3d.py index dc89780703d..53baf9511f4 100755 --- a/Examples/Tests/flux_injection/analysis_flux_injection_3d.py +++ b/Examples/Tests/flux_injection/analysis_flux_injection_3d.py @@ -21,7 +21,6 @@ of space) """ -import os import sys import matplotlib.pyplot as plt @@ -30,9 +29,6 @@ from scipy.constants import c, m_e, m_p from scipy.special import erf -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - yt.funcs.mylog.setLevel(0) # Open plotfile specified in command line @@ -146,9 +142,3 @@ def compare_gaussian_flux(u, w, u_th, u_m, label=""): plt.tight_layout() plt.savefig("Distribution.png") - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/flux_injection/analysis_flux_injection_from_eb.py b/Examples/Tests/flux_injection/analysis_flux_injection_from_eb.py index 36ff50bea06..96488fd7e71 100755 --- a/Examples/Tests/flux_injection/analysis_flux_injection_from_eb.py +++ b/Examples/Tests/flux_injection/analysis_flux_injection_from_eb.py @@ -13,7 +13,6 @@ the particle distributions are consistent with the expected distributions. """ -import os import re import sys @@ -23,16 +22,13 @@ from scipy.constants import c, m_e from scipy.special import erf -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -import checksumAPI - yt.funcs.mylog.setLevel(0) # Open plotfile specified in command line fn = sys.argv[1] ds = yt.load(fn) ad = ds.all_data() -t_max = ds.current_time.item() # time of simulation +t_inj = 0.5e-8 # duration for which the flux injection was active # Extract the dimensionality of the simulation with open("./warpx_used_inputs", "r") as f: @@ -52,7 +48,7 @@ emission_surface = 4 * np.pi * R**2 # in m^2 elif dims == "2D": emission_surface = 2 * np.pi * R # in m -Ntot = flux * emission_surface * t_max +Ntot = flux * emission_surface * t_inj # Parameters of the histogram hist_bins = 50 @@ -151,11 +147,8 @@ def compare_gaussian_flux(u, w, u_th, u_m, label=""): wy = nz * vx - nx * vz wz = nx * vy - ny * vx u_perp2 = ux * wx + uy * wy + uz * wz -compare_gaussian(u_perp2, w, u_th=0.01, label="u_perp") +compare_gaussian(u_perp2, w, u_th=0.01, label="u_perp2") +plt.legend() plt.tight_layout() plt.savefig("Distribution.png") - -# Verify checksum -test_name = os.path.split(os.getcwd())[1] -checksumAPI.evaluate_checksum(test_name, fn) diff --git a/Examples/Tests/flux_injection/analysis_flux_injection_rz.py b/Examples/Tests/flux_injection/analysis_flux_injection_rz.py index 33b487cc36b..170fb08128d 100755 --- a/Examples/Tests/flux_injection/analysis_flux_injection_rz.py +++ b/Examples/Tests/flux_injection/analysis_flux_injection_rz.py @@ -25,15 +25,11 @@ - The total number of electrons corresponds to the expected flux. """ -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - yt.funcs.mylog.setLevel(0) # Open plotfile specified in command line @@ -56,9 +52,3 @@ assert np.allclose(w.sum(), n_tot, rtol=0.05) # Check that the particles are at the right radius assert np.all((r >= 1.48) & (r <= 1.92)) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/flux_injection/inputs_base_from_eb b/Examples/Tests/flux_injection/inputs_base_from_eb index 3e32d8799b6..618fd1c941a 100644 --- a/Examples/Tests/flux_injection/inputs_base_from_eb +++ b/Examples/Tests/flux_injection/inputs_base_from_eb @@ -1,5 +1,5 @@ # Maximum number of time steps -max_step = 10 +max_step = 20 # The lo and hi ends of grids are multipliers of blocking factor amr.blocking_factor = 8 @@ -13,7 +13,7 @@ amr.max_level = 0 # Deactivate Maxwell solver algo.maxwell_solver = none -warpx.const_dt = 1e-9 +warpx.const_dt = 0.5e-9 # Embedded boundary warpx.eb_implicit_function = "-(x**2+y**2+z**2-2**2)" @@ -29,6 +29,8 @@ electron.inject_from_embedded_boundary = 1 electron.num_particles_per_cell = 100 electron.flux_profile = parse_flux_function electron.flux_function(x,y,z,t) = "1." +electron.flux_tmin = 0.25e-8 +electron.flux_tmax = 0.75e-8 electron.momentum_distribution_type = gaussianflux electron.ux_th = 0.01 electron.uy_th = 0.01 diff --git a/Examples/Tests/flux_injection/inputs_test_2d_flux_injection_from_eb b/Examples/Tests/flux_injection/inputs_test_2d_flux_injection_from_eb index f2e6f177887..291ef329ad6 100644 --- a/Examples/Tests/flux_injection/inputs_test_2d_flux_injection_from_eb +++ b/Examples/Tests/flux_injection/inputs_test_2d_flux_injection_from_eb @@ -1,7 +1,7 @@ FILE = inputs_base_from_eb # number of grid points -amr.n_cell = 16 16 +amr.n_cell = 32 32 # Geometry geometry.dims = 2 diff --git a/Examples/Tests/flux_injection/inputs_test_3d_flux_injection_from_eb b/Examples/Tests/flux_injection/inputs_test_3d_flux_injection_from_eb index 81ddc039977..59db133e484 100644 --- a/Examples/Tests/flux_injection/inputs_test_3d_flux_injection_from_eb +++ b/Examples/Tests/flux_injection/inputs_test_3d_flux_injection_from_eb @@ -1,7 +1,7 @@ FILE = inputs_base_from_eb # number of grid points -amr.n_cell = 16 16 16 +amr.n_cell = 32 32 32 # Geometry geometry.dims = 3 diff --git a/Examples/Tests/flux_injection/inputs_test_rz_flux_injection_from_eb b/Examples/Tests/flux_injection/inputs_test_rz_flux_injection_from_eb index 4c970257f57..c206a154646 100644 --- a/Examples/Tests/flux_injection/inputs_test_rz_flux_injection_from_eb +++ b/Examples/Tests/flux_injection/inputs_test_rz_flux_injection_from_eb @@ -1,7 +1,7 @@ FILE = inputs_base_from_eb # number of grid points -amr.n_cell = 8 16 +amr.n_cell = 16 32 # Geometry geometry.dims = RZ diff --git a/Examples/Tests/gaussian_beam/CMakeLists.txt b/Examples/Tests/gaussian_beam/CMakeLists.txt index ae0cf57ed15..2a1f4918458 100644 --- a/Examples/Tests/gaussian_beam/CMakeLists.txt +++ b/Examples/Tests/gaussian_beam/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_focusing_gaussian_beam # inputs - analysis.py # analysis - diags/diag1000000 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000000" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_gaussian_beam_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) diff --git a/Examples/Tests/gaussian_beam/analysis.py b/Examples/Tests/gaussian_beam/analysis.py index a2278b2cf7a..a5a6caf8e42 100755 --- a/Examples/Tests/gaussian_beam/analysis.py +++ b/Examples/Tests/gaussian_beam/analysis.py @@ -7,15 +7,9 @@ # License: BSD-3-Clause-LBNL -import os -import sys - import numpy as np -from scipy.constants import c, eV, m_e, micro, nano - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum from openpmd_viewer import OpenPMDTimeSeries +from scipy.constants import c, eV, m_e, micro, nano GeV = 1e9 * eV energy = 125.0 * GeV @@ -67,9 +61,3 @@ def s(z, sigma0, emit): assert np.allclose(sx, sx_theory, rtol=0.051, atol=0) assert np.allclose(sy, sy_theory, rtol=0.038, atol=0) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/implicit/CMakeLists.txt b/Examples/Tests/implicit/CMakeLists.txt index dabd4de66b8..e4bde9bbeaf 100644 --- a/Examples/Tests/implicit/CMakeLists.txt +++ b/Examples/Tests/implicit/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_semi_implicit_picard # inputs - analysis_1d.py # analysis - diags/diag1000100 # output + "analysis_1d.py" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_theta_implicit_picard # inputs - analysis_1d.py # analysis - diags/diag1000100 # output + "analysis_1d.py" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) @@ -26,8 +26,18 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_theta_implicit_jfnk_vandb # inputs - analysis_vandb_jfnk_2d.py # analysis - diags/diag1000020 # output + "analysis_vandb_jfnk_2d.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum + OFF # dependency +) + +add_warpx_test( + test_2d_theta_implicit_jfnk_vandb_filtered # name + 2 # dims + 2 # nprocs + inputs_test_2d_theta_implicit_jfnk_vandb_filtered # inputs + "analysis_vandb_jfnk_2d.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) @@ -36,7 +46,19 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_theta_implicit_jfnk_vandb_picmi.py # inputs - analysis_vandb_jfnk_2d.py # analysis - diags/diag1000020 # output + "analysis_vandb_jfnk_2d.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) + +if(WarpX_FFT) + add_warpx_test( + test_2d_theta_implicit_strang_psatd # name + 2 # dims + 2 # nprocs + inputs_test_2d_theta_implicit_strang_psatd # inputs + "analysis_2d_psatd.py" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum + OFF # dependency + ) +endif() diff --git a/Examples/Tests/implicit/analysis_1d.py b/Examples/Tests/implicit/analysis_1d.py index 665fcaac951..aa54cd279ce 100755 --- a/Examples/Tests/implicit/analysis_1d.py +++ b/Examples/Tests/implicit/analysis_1d.py @@ -11,13 +11,9 @@ # the script `inputs_1d`. This simulates a 1D periodic plasma using the implicit solver. import os import re -import sys import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - field_energy = np.loadtxt("diags/reducedfiles/field_energy.txt", skiprows=1) particle_energy = np.loadtxt("diags/reducedfiles/particle_energy.txt", skiprows=1) @@ -37,9 +33,3 @@ print(f"tolerance: {tolerance_rel}") assert max_delta_E < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/implicit/analysis_2d_psatd.py b/Examples/Tests/implicit/analysis_2d_psatd.py new file mode 100755 index 00000000000..507fc6f2c4a --- /dev/null +++ b/Examples/Tests/implicit/analysis_2d_psatd.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +# Copyright 2024 Justin Angus, David Grote +# +# +# This file is part of WarpX. +# +# License: BSD-3-Clause-LBNL +# +# This is a script that analyses the simulation results from the script `inputs_vandb_2d`. +# This simulates a 2D periodic plasma using the implicit solver +# with the Villasenor deposition using shape factor 2. + +import numpy as np + +field_energy = np.loadtxt("diags/reducedfiles/field_energy.txt", skiprows=1) +particle_energy = np.loadtxt("diags/reducedfiles/particle_energy.txt", skiprows=1) + +total_energy = field_energy[:, 2] + particle_energy[:, 2] + +delta_E = (total_energy - total_energy[0]) / total_energy[0] +max_delta_E = np.abs(delta_E).max() + +# This case should have near machine precision conservation of energy +tolerance_rel_energy = 2.1e-14 + +print(f"max change in energy: {max_delta_E}") +print(f"tolerance: {tolerance_rel_energy}") + +assert max_delta_E < tolerance_rel_energy diff --git a/Examples/Tests/implicit/analysis_default_regression.py b/Examples/Tests/implicit/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/implicit/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/implicit/analysis_vandb_jfnk_2d.py b/Examples/Tests/implicit/analysis_vandb_jfnk_2d.py index 29a2c870574..dcbacdfde1f 100755 --- a/Examples/Tests/implicit/analysis_vandb_jfnk_2d.py +++ b/Examples/Tests/implicit/analysis_vandb_jfnk_2d.py @@ -10,19 +10,12 @@ # This is a script that analyses the simulation results from the script `inputs_vandb_2d`. # This simulates a 2D periodic plasma using the implicit solver # with the Villasenor deposition using shape factor 2. -import os import sys import numpy as np import yt from scipy.constants import e, epsilon_0 -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# this will be the name of the plot file -fn = sys.argv[1] - field_energy = np.loadtxt("diags/reducedfiles/field_energy.txt", skiprows=1) particle_energy = np.loadtxt("diags/reducedfiles/particle_energy.txt", skiprows=1) @@ -65,9 +58,3 @@ print(f"tolerance: {tolerance_rel_charge}") assert drho_rms < tolerance_rel_charge - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/implicit/inputs_test_1d_semi_implicit_picard b/Examples/Tests/implicit/inputs_test_1d_semi_implicit_picard index 8ef0304bebb..39df05ff72c 100644 --- a/Examples/Tests/implicit/inputs_test_1d_semi_implicit_picard +++ b/Examples/Tests/implicit/inputs_test_1d_semi_implicit_picard @@ -85,7 +85,6 @@ diag1.electrons.variables = z w ux uy uz diag1.protons.variables = z w ux uy uz warpx.reduced_diags_names = particle_energy field_energy +reduced_diags.intervals = 1 particle_energy.type = ParticleEnergy -particle_energy.intervals = 1 field_energy.type = FieldEnergy -field_energy.intervals = 1 diff --git a/Examples/Tests/implicit/inputs_test_1d_theta_implicit_picard b/Examples/Tests/implicit/inputs_test_1d_theta_implicit_picard index 2ed4d746708..80e4e7033fc 100644 --- a/Examples/Tests/implicit/inputs_test_1d_theta_implicit_picard +++ b/Examples/Tests/implicit/inputs_test_1d_theta_implicit_picard @@ -85,7 +85,6 @@ diag1.electrons.variables = z w ux uy uz diag1.protons.variables = z w ux uy uz warpx.reduced_diags_names = particle_energy field_energy +reduced_diags.intervals = 1 particle_energy.type = ParticleEnergy -particle_energy.intervals = 1 field_energy.type = FieldEnergy -field_energy.intervals = 1 diff --git a/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb index 0cdf2ebe40d..c0cd729f50c 100644 --- a/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb +++ b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb @@ -52,6 +52,7 @@ implicit_evolve.particle_tolerance = 1.0e-12 #picard.relative_tolerance = 0.0 #1.0e-12 #picard.absolute_tolerance = 0.0 #1.0e-24 #picard.require_convergence = false +#picard.diagnostic_file = "diags/picard_solver.txt" implicit_evolve.nonlinear_solver = "newton" newton.verbose = true @@ -59,6 +60,7 @@ newton.max_iterations = 20 newton.relative_tolerance = 1.0e-12 newton.absolute_tolerance = 0.0 newton.require_convergence = false +newton.diagnostic_file = "diags/newton_solver.txt" gmres.verbose_int = 2 gmres.max_iterations = 1000 @@ -109,7 +111,6 @@ diag1.electrons.variables = x z w ux uy uz diag1.protons.variables = x z w ux uy uz warpx.reduced_diags_names = particle_energy field_energy +reduced_diags.intervals = 1 particle_energy.type = ParticleEnergy -particle_energy.intervals = 1 field_energy.type = FieldEnergy -field_energy.intervals = 1 diff --git a/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb_filtered b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb_filtered new file mode 100644 index 00000000000..c7457e02af8 --- /dev/null +++ b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_jfnk_vandb_filtered @@ -0,0 +1,114 @@ +################################# +########## CONSTANTS ############ +################################# + +my_constants.n0 = 1.e30 # m^-3 +my_constants.Ti = 100. # eV +my_constants.Te = 100. # eV +my_constants.wpe = q_e*sqrt(n0/(m_e*epsilon0)) +my_constants.de0 = clight/wpe +my_constants.nppcz = 10 # number of particles/cell in z +my_constants.dt = 0.1/wpe # s + +################################# +####### GENERAL PARAMETERS ###### +################################# +max_step = 20 +amr.n_cell = 40 40 +amr.max_grid_size = 8 +amr.blocking_factor = 8 +amr.max_level = 0 +geometry.dims = 2 +geometry.prob_lo = 0.0 0.0 # physical domain +geometry.prob_hi = 10.0*de0 10.0*de0 + +################################# +####### Boundary condition ###### +################################# +boundary.field_lo = periodic periodic +boundary.field_hi = periodic periodic + +################################# +############ NUMERICS ########### +################################# +warpx.abort_on_warning_threshold = high +warpx.serialize_initial_conditions = 1 +warpx.verbose = 1 +warpx.const_dt = dt +#warpx.cfl = 0.5656 +warpx.use_filter = 1 + +algo.maxwell_solver = Yee +algo.evolve_scheme = "theta_implicit_em" +#algo.evolve_scheme = "semi_implicit_em" + +implicit_evolve.theta = 0.5 +implicit_evolve.max_particle_iterations = 21 +implicit_evolve.particle_tolerance = 1.0e-12 + +#implicit_evolve.nonlinear_solver = "picard" +#picard.verbose = true +#picard.max_iterations = 25 +#picard.relative_tolerance = 0.0 #1.0e-12 +#picard.absolute_tolerance = 0.0 #1.0e-24 +#picard.require_convergence = false + +implicit_evolve.nonlinear_solver = "newton" +newton.verbose = true +newton.max_iterations = 20 +newton.relative_tolerance = 1.0e-12 +newton.absolute_tolerance = 0.0 +newton.require_convergence = false + +gmres.verbose_int = 2 +gmres.max_iterations = 1000 +gmres.relative_tolerance = 1.0e-8 +gmres.absolute_tolerance = 0.0 + +algo.particle_pusher = "boris" +#algo.particle_pusher = "higuera" + +algo.particle_shape = 2 +#algo.current_deposition = "direct" +#algo.current_deposition = "esirkepov" +algo.current_deposition = "villasenor" + +################################# +############ PLASMA ############# +################################# +particles.species_names = electrons protons + +electrons.charge = -q_e +electrons.mass = m_e +electrons.injection_style = "NUniformPerCell" +electrons.num_particles_per_cell_each_dim = nppcz nppcz +electrons.profile = constant +electrons.density = 1.e30 # number per m^3 +electrons.momentum_distribution_type = "gaussian" +electrons.ux_th = sqrt(Te*q_e/m_e)/clight +electrons.uy_th = sqrt(Te*q_e/m_e)/clight +electrons.uz_th = sqrt(Te*q_e/m_e)/clight + +protons.charge = q_e +protons.mass = m_p +protons.injection_style = "NUniformPerCell" +protons.num_particles_per_cell_each_dim = nppcz nppcz +protons.profile = constant +protons.density = 1.e30 # number per m^3 +protons.momentum_distribution_type = "gaussian" +protons.ux_th = sqrt(Ti*q_e/m_p)/clight +protons.uy_th = sqrt(Ti*q_e/m_p)/clight +protons.uz_th = sqrt(Ti*q_e/m_p)/clight + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 20 +diag1.diag_type = Full +diag1.fields_to_plot = Ex Ey Ez Bx By Bz jx jy jz rho divE +diag1.electrons.variables = x z w ux uy uz +diag1.protons.variables = x z w ux uy uz + +warpx.reduced_diags_names = particle_energy field_energy +reduced_diags.intervals = 1 +particle_energy.type = ParticleEnergy +field_energy.type = FieldEnergy diff --git a/Examples/Tests/implicit/inputs_test_2d_theta_implicit_strang_psatd b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_strang_psatd new file mode 100644 index 00000000000..46bc6b3d301 --- /dev/null +++ b/Examples/Tests/implicit/inputs_test_2d_theta_implicit_strang_psatd @@ -0,0 +1,97 @@ +################################# +########## CONSTANTS ############ +################################# + +my_constants.n0 = 1.e30 # m^-3 +my_constants.nz = 40 +my_constants.Ti = 100. # eV +my_constants.Te = 100. # eV +my_constants.wpe = q_e*sqrt(n0/(m_e*epsilon0)) +my_constants.de0 = clight/wpe +my_constants.nppcz = 10 # number of particles/cell in z +my_constants.dt = 0.1/wpe # s + +################################# +####### GENERAL PARAMETERS ###### +################################# +max_step = 20 +amr.n_cell = nz nz +amr.max_grid_size = nz +amr.max_level = 0 +geometry.dims = 2 +geometry.prob_lo = 0.0 0.0 # physical domain +geometry.prob_hi = 10.0*de0 10.0*de0 + +################################# +####### Boundary condition ###### +################################# +boundary.field_lo = periodic periodic +boundary.field_hi = periodic periodic + +################################# +############ NUMERICS ########### +################################# +warpx.serialize_initial_conditions = 1 +warpx.verbose = 1 +warpx.const_dt = dt +#warpx.cfl = 0.5656 +warpx.use_filter = 0 + +algo.maxwell_solver = psatd +algo.evolve_scheme = strang_implicit_spectral_em +implicit_evolve.nonlinear_solver = "picard" + +picard.verbose = true +picard.max_iterations = 9 +picard.relative_tolerance = 0.0 +picard.absolute_tolerance = 0.0 +picard.require_convergence = false + +algo.particle_pusher = "boris" + +algo.particle_shape = 2 +algo.current_deposition = direct +algo.charge_deposition = standard +algo.field_gathering = energy-conserving +interpolation.galerkin_scheme = 0 + +psatd.periodic_single_box_fft = 1 +psatd.update_with_rho = 0 + +################################# +############ PLASMA ############# +################################# +particles.species_names = electrons protons + +electrons.species_type = electron +electrons.injection_style = "NUniformPerCell" +electrons.num_particles_per_cell_each_dim = nppcz nppcz +electrons.profile = constant +electrons.density = n0 +electrons.momentum_distribution_type = gaussian +electrons.ux_th = sqrt(Te*q_e/m_e)/clight +electrons.uy_th = sqrt(Te*q_e/m_e)/clight +electrons.uz_th = sqrt(Te*q_e/m_e)/clight + +protons.species_type = proton +protons.injection_style = "NUniformPerCell" +protons.num_particles_per_cell_each_dim = nppcz nppcz +protons.profile = constant +protons.density = n0 +protons.momentum_distribution_type = gaussian +protons.ux_th = sqrt(Ti*q_e/m_p)/clight +protons.uy_th = sqrt(Ti*q_e/m_p)/clight +protons.uz_th = sqrt(Ti*q_e/m_p)/clight + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 20 +diag1.diag_type = Full +diag1.fields_to_plot = Ex Ey Ez Bx By Bz jx jy jz rho divE +diag1.electrons.variables = x z w ux uy uz +diag1.protons.variables = x z w ux uy uz + +warpx.reduced_diags_names = particle_energy field_energy +reduced_diags.intervals = 1 +particle_energy.type = ParticleEnergy +field_energy.type = FieldEnergy diff --git a/Examples/Tests/initial_distribution/CMakeLists.txt b/Examples/Tests/initial_distribution/CMakeLists.txt index 04af9708cb2..06fce4dddcb 100644 --- a/Examples/Tests/initial_distribution/CMakeLists.txt +++ b/Examples/Tests/initial_distribution/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_initial_distribution # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/initial_distribution/analysis.py b/Examples/Tests/initial_distribution/analysis.py index 834934df255..8b2c8ca74e2 100755 --- a/Examples/Tests/initial_distribution/analysis.py +++ b/Examples/Tests/initial_distribution/analysis.py @@ -18,17 +18,11 @@ # 9 denotes gaussian_parser distribution w/ spatially-varying mean and thermal velocity # The distribution is obtained through reduced diagnostic ParticleHistogram. -import os -import sys - import numpy as np import scipy.constants as scc import scipy.special as scs from read_raw_data import read_reduced_diags, read_reduced_diags_histogram -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # print tolerance tolerance = 0.02 print("Tolerance:", tolerance) @@ -448,9 +442,3 @@ def Gaussian(mean, sigma, u): print("gaussian_parse_momentum_function velocity difference:", f9_error) assert f9_error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/initial_distribution/analysis_default_regression.py b/Examples/Tests/initial_distribution/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/initial_distribution/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/initial_plasma_profile/CMakeLists.txt b/Examples/Tests/initial_plasma_profile/CMakeLists.txt index eb45e64dfab..064bbc29907 100644 --- a/Examples/Tests/initial_plasma_profile/CMakeLists.txt +++ b/Examples/Tests/initial_plasma_profile/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_parabolic_channel_initialization # inputs - analysis.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles --rtol 1e-4" # checksum OFF # dependency ) diff --git a/Examples/Tests/initial_plasma_profile/analysis.py b/Examples/Tests/initial_plasma_profile/analysis.py deleted file mode 100755 index d372bd30a93..00000000000 --- a/Examples/Tests/initial_plasma_profile/analysis.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright 2020 Michael Rowan -# -# This file is part of WarpX. -# -# License: BSD-3-Clause-LBNL - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-4, - do_particles=False, -) diff --git a/Examples/Tests/initial_plasma_profile/analysis_default_regression.py b/Examples/Tests/initial_plasma_profile/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/initial_plasma_profile/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ion_stopping/CMakeLists.txt b/Examples/Tests/ion_stopping/CMakeLists.txt index 83e15287e18..666b28244dd 100644 --- a/Examples/Tests/ion_stopping/CMakeLists.txt +++ b/Examples/Tests/ion_stopping/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_ion_stopping # inputs - analysis.py # analysis - diags/diag1000010 # output + "analysis.py diags/diag1000010" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) diff --git a/Examples/Tests/ion_stopping/analysis.py b/Examples/Tests/ion_stopping/analysis.py index 45983538025..6b92bb304a5 100755 --- a/Examples/Tests/ion_stopping/analysis.py +++ b/Examples/Tests/ion_stopping/analysis.py @@ -11,16 +11,12 @@ # is used in the C++ to check the resulting # particle energies. -import os import sys import numpy as np import yt from scipy.constants import e, epsilon_0, k, m_e, m_p -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Define constants using the WarpX names for the evals below q_e = e kb = k @@ -193,9 +189,3 @@ def stopping_from_ions(dt, ni, Ti, mi, Zi, Zb, ion_mass, ion_energy): assert np.all(error2 < tolerance) assert np.all(error3 < tolerance) assert np.all(error4 < tolerance) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/ion_stopping/analysis_default_regression.py b/Examples/Tests/ion_stopping/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ion_stopping/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/langmuir/CMakeLists.txt b/Examples/Tests/langmuir/CMakeLists.txt index b259083c695..c01fed9125a 100644 --- a/Examples/Tests/langmuir/CMakeLists.txt +++ b/Examples/Tests/langmuir/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_langmuir_multi # inputs - analysis_1d.py # analysis - diags/diag1000080 # output + "analysis_1d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_mr # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_mr_anisotropic # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_mr_momentum_conserving # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -57,8 +57,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_mr_psatd # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -68,8 +68,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_nodal # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -78,8 +78,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000040 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -89,8 +89,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_psatd # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -101,8 +101,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_langmuir_multi_psatd_current_correction # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -113,8 +113,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_langmuir_multi_psatd_current_correction_nodal # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -125,8 +125,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_psatd_momentum_conserving # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -137,8 +137,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_psatd_multiJ # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -149,8 +149,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_psatd_multiJ_nodal # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -161,8 +161,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_langmuir_multi_psatd_nodal # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -173,8 +173,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_langmuir_multi_psatd_vay_deposition # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -185,8 +185,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_langmuir_multi_psatd_vay_deposition_nodal # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -197,8 +197,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_langmuir_multi_psatd_vay_deposition_particle_shape_4 # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -208,8 +208,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -218,8 +218,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_nodal # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -228,8 +228,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_langmuir_multi_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000040 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -239,8 +239,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -251,8 +251,8 @@ if(WarpX_FFT) 3 # dims 1 # nprocs inputs_test_3d_langmuir_multi_psatd_current_correction # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -263,8 +263,8 @@ if(WarpX_FFT) 3 # dims 1 # nprocs inputs_test_3d_langmuir_multi_psatd_current_correction_nodal # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -275,8 +275,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd_div_cleaning # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -287,8 +287,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd_momentum_conserving # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -299,8 +299,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd_multiJ # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -311,8 +311,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd_multiJ_nodal # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -323,8 +323,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_langmuir_multi_psatd_nodal # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -335,8 +335,8 @@ if(WarpX_FFT) 3 # dims 1 # nprocs inputs_test_3d_langmuir_multi_psatd_vay_deposition # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) endif() @@ -347,8 +347,8 @@ if(WarpX_FFT) 3 # dims 1 # nprocs inputs_test_3d_langmuir_multi_psatd_vay_deposition_nodal # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) label_warpx_test(test_3d_langmuir_multi_psatd_vay_deposition_nodal slow) @@ -359,8 +359,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_langmuir_multi # inputs - analysis_rz.py # analysis - diags/diag1000080 # output + "analysis_rz.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -369,8 +369,8 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_langmuir_multi_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000040 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -380,8 +380,8 @@ if(WarpX_FFT) RZ # dims 2 # nprocs inputs_test_rz_langmuir_multi_psatd # inputs - analysis_rz.py # analysis - diags/diag1000080 # output + "analysis_rz.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -392,8 +392,8 @@ if(WarpX_FFT) RZ # dims 1 # nprocs inputs_test_rz_langmuir_multi_psatd_current_correction # inputs - analysis_rz.py # analysis - diags/diag1000080 # output + "analysis_rz.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() @@ -404,8 +404,8 @@ if(WarpX_FFT) RZ # dims 2 # nprocs inputs_test_rz_langmuir_multi_psatd_multiJ # inputs - analysis_rz.py # analysis - diags/diag1000080 # output + "analysis_rz.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/langmuir/analysis_1d.py b/Examples/Tests/langmuir/analysis_1d.py index 8eefd95b4f7..60a088d1309 100755 --- a/Examples/Tests/langmuir/analysis_1d.py +++ b/Examples/Tests/langmuir/analysis_1d.py @@ -26,9 +26,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # test name test_name = os.path.split(os.getcwd())[1] @@ -125,9 +122,3 @@ def get_theoretical_field(field, t): print("error_rel = {}".format(error_rel)) print("tolerance = {}".format(tolerance)) assert error_rel < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir/analysis_2d.py b/Examples/Tests/langmuir/analysis_2d.py index 31995e896a5..3aa246008a6 100755 --- a/Examples/Tests/langmuir/analysis_2d.py +++ b/Examples/Tests/langmuir/analysis_2d.py @@ -26,9 +26,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # test name test_name = os.path.split(os.getcwd())[1] @@ -162,9 +159,3 @@ def get_theoretical_field(field, t): print("error_rel = {}".format(error_rel)) print("tolerance = {}".format(tolerance)) assert error_rel < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir/analysis_3d.py b/Examples/Tests/langmuir/analysis_3d.py index 05f1c585ec0..75b9c5ba71c 100755 --- a/Examples/Tests/langmuir/analysis_3d.py +++ b/Examples/Tests/langmuir/analysis_3d.py @@ -26,9 +26,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # test name test_name = os.path.split(os.getcwd())[1] @@ -211,9 +208,3 @@ def get_theoretical_field(field, t): print("error_rel = {}".format(error_rel)) print("tolerance = {}".format(tolerance)) assert error_rel < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir/analysis_rz.py b/Examples/Tests/langmuir/analysis_rz.py index 64f8cfb6313..a0697b93ab9 100755 --- a/Examples/Tests/langmuir/analysis_rz.py +++ b/Examples/Tests/langmuir/analysis_rz.py @@ -29,9 +29,6 @@ import post_processing_utils from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -182,9 +179,3 @@ def Ez(z, r, epsilon, k0, w0, wp, t): post_processing_utils.check_random_filter( fn, random_filter_fn, random_fraction, dim, species_name ) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir_fluids/CMakeLists.txt b/Examples/Tests/langmuir_fluids/CMakeLists.txt index 054e9c80d3a..df6732200c6 100644 --- a/Examples/Tests/langmuir_fluids/CMakeLists.txt +++ b/Examples/Tests/langmuir_fluids/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_langmuir_fluid # inputs - analysis_1d.py # analysis - diags/diag1000080 # output + "analysis_1d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_langmuir_fluid # inputs - analysis_2d.py # analysis - diags/diag1000080 # output + "analysis_2d.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_langmuir_fluid # inputs - analysis_3d.py # analysis - diags/diag1000040 # output + "analysis_3d.py diags/diag1000040" # analysis + "analysis_default_regression.py --path diags/diag1000040" # checksum OFF # dependency ) @@ -36,7 +36,7 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_langmuir_fluid # inputs - analysis_rz.py # analysis - diags/diag1000080 # output + "analysis_rz.py diags/diag1000080" # analysis + "analysis_default_regression.py --path diags/diag1000080" # checksum OFF # dependency ) diff --git a/Examples/Tests/langmuir_fluids/analysis_1d.py b/Examples/Tests/langmuir_fluids/analysis_1d.py index c448303783f..f60c76660b5 100755 --- a/Examples/Tests/langmuir_fluids/analysis_1d.py +++ b/Examples/Tests/langmuir_fluids/analysis_1d.py @@ -11,7 +11,6 @@ # the script `inputs.multi.rt`. This simulates a 1D periodic plasma wave. # The electric field in the simulation is given (in theory) by: # $$ E_z = \epsilon \,\frac{m_e c^2 k_z}{q_e}\sin(k_z z)\sin( \omega_p t)$$ -import os import sys import matplotlib @@ -25,9 +24,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -147,9 +143,3 @@ def get_theoretical_rho_field(field, t): print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir_fluids/analysis_2d.py b/Examples/Tests/langmuir_fluids/analysis_2d.py index d8ba50a9df1..46b9948884c 100755 --- a/Examples/Tests/langmuir_fluids/analysis_2d.py +++ b/Examples/Tests/langmuir_fluids/analysis_2d.py @@ -13,7 +13,6 @@ # $$ E_x = \epsilon \,\frac{m_e c^2 k_x}{q_e}\sin(k_x x)\cos(k_y y)\cos(k_z z)\sin( \omega_p t)$$ # $$ E_y = \epsilon \,\frac{m_e c^2 k_y}{q_e}\cos(k_x x)\sin(k_y y)\cos(k_z z)\sin( \omega_p t)$$ # $$ E_z = \epsilon \,\frac{m_e c^2 k_z}{q_e}\cos(k_x x)\cos(k_y y)\sin(k_z z)\sin( \omega_p t)$$ -import os import sys import matplotlib.pyplot as plt @@ -25,9 +24,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -177,9 +173,3 @@ def get_theoretical_rho_field(field, t): print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir_fluids/analysis_3d.py b/Examples/Tests/langmuir_fluids/analysis_3d.py index 899dc72424b..6a15c175843 100755 --- a/Examples/Tests/langmuir_fluids/analysis_3d.py +++ b/Examples/Tests/langmuir_fluids/analysis_3d.py @@ -13,7 +13,6 @@ # $$ E_x = \epsilon \,\frac{m_e c^2 k_x}{q_e}\sin(k_x x)\cos(k_y y)\cos(k_z z)\sin( \omega_p t)$$ # $$ E_y = \epsilon \,\frac{m_e c^2 k_y}{q_e}\cos(k_x x)\sin(k_y y)\cos(k_z z)\sin( \omega_p t)$$ # $$ E_z = \epsilon \,\frac{m_e c^2 k_z}{q_e}\cos(k_x x)\cos(k_y y)\sin(k_z z)\sin( \omega_p t)$$ -import os import sys import matplotlib.pyplot as plt @@ -25,9 +24,6 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -211,9 +207,3 @@ def get_theoretical_rho_field(field, t): print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/langmuir_fluids/analysis_default_regression.py b/Examples/Tests/langmuir_fluids/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/langmuir_fluids/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/langmuir_fluids/analysis_rz.py b/Examples/Tests/langmuir_fluids/analysis_rz.py index 0e918a6ab31..de6853db556 100755 --- a/Examples/Tests/langmuir_fluids/analysis_rz.py +++ b/Examples/Tests/langmuir_fluids/analysis_rz.py @@ -14,7 +14,6 @@ # Unrelated to the Langmuir waves, we also test the plotfile particle filter function in this # analysis script. import os -import re import sys import matplotlib @@ -28,17 +27,11 @@ import numpy as np from scipy.constants import c, e, epsilon_0, m_e -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] test_name = os.path.split(os.getcwd())[1] -# Parse test name and check if current correction (psatd.current_correction) is applied -current_correction = True if re.search("current_correction", fn) else False - # Parameters (these parameters must match the parameters in `inputs.multi.rz.rt`) epsilon = 0.01 n = 2.0e24 @@ -225,9 +218,3 @@ def rho(z, r, epsilon, k0, w0, wp, t): print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/larmor/CMakeLists.txt b/Examples/Tests/larmor/CMakeLists.txt index 6a3368a4fca..f089b4dc958 100644 --- a/Examples/Tests/larmor/CMakeLists.txt +++ b/Examples/Tests/larmor/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_larmor # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) diff --git a/Examples/Tests/laser_injection/CMakeLists.txt b/Examples/Tests/laser_injection/CMakeLists.txt index cec027deb70..30d18c6d063 100644 --- a/Examples/Tests/laser_injection/CMakeLists.txt +++ b/Examples/Tests/laser_injection/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_laser_injection # inputs - analysis_1d.py # analysis - diags/diag1000240 # output + "analysis_1d.py diags/diag1000240" # analysis + "analysis_default_regression.py --path diags/diag1000240" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_injection # inputs - analysis_2d.py # analysis - diags/diag1000240 # output + "analysis_2d.py diags/diag1000240" # analysis + "analysis_default_regression.py --path diags/diag1000240" # checksum OFF # dependency ) @@ -26,7 +26,27 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_laser_injection # inputs - analysis_3d.py # analysis - diags/diag1000020 # output + "analysis_3d.py" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum + OFF # dependency +) + +add_warpx_test( + test_1d_laser_injection_implicit # name + 1 # dims + 2 # nprocs + inputs_test_1d_laser_injection_implicit # inputs + "analysis_1d.py diags/diag1000240" # analysis + "analysis_default_regression.py --path diags/diag1000240" # checksum + OFF # dependency +) + +add_warpx_test( + test_2d_laser_injection_implicit # name + 2 # dims + 2 # nprocs + inputs_test_2d_laser_injection_implicit # inputs + "analysis_2d.py diags/diag1000240" # analysis + "analysis_default_regression.py --path diags/diag1000240" # checksum OFF # dependency ) diff --git a/Examples/Tests/laser_injection/analysis_1d.py b/Examples/Tests/laser_injection/analysis_1d.py index 5ce7065c967..98ce6ca47c5 100755 --- a/Examples/Tests/laser_injection/analysis_1d.py +++ b/Examples/Tests/laser_injection/analysis_1d.py @@ -12,7 +12,6 @@ # the simulation and it compares it with theory. It also checks that the # central frequency of the Fourier transform is the expected one. -import os import sys import matplotlib @@ -23,9 +22,6 @@ import numpy as np from scipy.signal import hilbert -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.05 @@ -192,12 +188,6 @@ def main(): check_laser(filename_end) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/laser_injection/analysis_2d.py b/Examples/Tests/laser_injection/analysis_2d.py index 5e2d9ebf280..33b87823ebd 100755 --- a/Examples/Tests/laser_injection/analysis_2d.py +++ b/Examples/Tests/laser_injection/analysis_2d.py @@ -17,7 +17,6 @@ # the simulation and it compares it with theory. It also checks that the # central frequency of the Fourier transform is the expected one. -import os import sys import matplotlib @@ -29,9 +28,6 @@ from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.signal import hilbert -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.05 @@ -225,12 +221,6 @@ def main(): check_laser(filename_end) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/laser_injection/analysis_3d.py b/Examples/Tests/laser_injection/analysis_3d.py index 153b721b526..2ce123169d5 100755 --- a/Examples/Tests/laser_injection/analysis_3d.py +++ b/Examples/Tests/laser_injection/analysis_3d.py @@ -8,26 +8,14 @@ # License: BSD-3-Clause-LBNL -import os -import sys - import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # you can save an image to be displayed on the website t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) plt.plot(t, s) plt.savefig("laser_analysis.png") - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection/analysis_default_regression.py b/Examples/Tests/laser_injection/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/laser_injection/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/laser_injection/inputs_test_1d_laser_injection_implicit b/Examples/Tests/laser_injection/inputs_test_1d_laser_injection_implicit new file mode 100644 index 00000000000..758e2cebaa1 --- /dev/null +++ b/Examples/Tests/laser_injection/inputs_test_1d_laser_injection_implicit @@ -0,0 +1,79 @@ +# Maximum number of time steps +max_step = 240 + +# number of grid points +amr.n_cell = 352 + +# Maximum allowable size of each subdomain in the problem domain; +# this is used to decompose the domain for parallel calculations. +amr.max_grid_size = 32 + +# Maximum level in hierarchy (for now must be 0, i.e., one level in total) +amr.max_level = 0 + +# Geometry +geometry.dims = 1 +geometry.prob_lo = -15.e-6 # physical domain +geometry.prob_hi = 15.e-6 + +boundary.field_lo = pec +boundary.field_hi = pec + +warpx.serialize_initial_conditions = 1 + +# Verbosity +warpx.verbose = 1 + +# Algorithms +algo.current_deposition = esirkepov +warpx.use_filter = 0 + +# implicit evolve scheme +algo.evolve_scheme = "semi_implicit_em" +# +implicit_evolve.nonlinear_solver = "newton" +newton.verbose = true +newton.max_iterations = 21 +newton.relative_tolerance = 1.0e-8 +newton.require_convergence = true +# +gmres.verbose_int = 2 +gmres.max_iterations = 1000 +gmres.relative_tolerance = 1.0e-4 + +# CFL +warpx.cfl = 0.9 + +# Order of particle shape factors +algo.particle_shape = 1 + +# Laser +lasers.names = laser1 +laser1.profile = Gaussian +laser1.position = 0.e-6 0.e-6 0.e-6 # This point is on the laser plane +laser1.direction = 0. 0. 1. # The plane normal direction +laser1.polarization = 1. 1. 0. # The main polarization vector +laser1.e_max = 4.e12 # Maximum amplitude of the laser field (in V/m) +laser1.wavelength = 1.0e-6 # The wavelength of the laser (in meters) +laser1.profile_waist = 5.e-6 # The waist of the laser (in meters) +laser1.profile_duration = 10.e-15 # The duration of the laser (in seconds) +laser1.profile_t_peak = 24.e-15 # The time at which the laser reaches its peak (in seconds) +laser1.profile_focal_distance = 13.109e-6 # Focal distance from the antenna (in meters) + # With this focal distance the laser is at focus + # at the end of the simulation. + +# Diagnostics +diagnostics.diags_names = diag1 openpmd +diag1.intervals = 20 +diag1.diag_type = Full + +openpmd.intervals = 20 +openpmd.diag_type = Full +openpmd.format = openpmd + +# Moving window +warpx.do_moving_window = 1 +warpx.moving_window_dir = z +warpx.moving_window_v = 1.0 # in units of the speed of light +warpx.start_moving_window_step = 20 +warpx.end_moving_window_step = 200 diff --git a/Examples/Tests/laser_injection/inputs_test_2d_laser_injection_implicit b/Examples/Tests/laser_injection/inputs_test_2d_laser_injection_implicit new file mode 100644 index 00000000000..be6a704b171 --- /dev/null +++ b/Examples/Tests/laser_injection/inputs_test_2d_laser_injection_implicit @@ -0,0 +1,75 @@ +# Maximum number of time steps +max_step = 240 + +# number of grid points +amr.n_cell = 480 352 + +# Maximum allowable size of each subdomain in the problem domain; +# this is used to decompose the domain for parallel calculations. +amr.max_grid_size = 32 + +# Maximum level in hierarchy (for now must be 0, i.e., one level in total) +amr.max_level = 0 + +# Geometry +geometry.dims = 2 +geometry.prob_lo = -20.e-6 -15.e-6 # physical domain +geometry.prob_hi = 20.e-6 15.e-6 + +boundary.field_lo = pec periodic +boundary.field_hi = pec periodic + +warpx.serialize_initial_conditions = 1 + +# Verbosity +warpx.verbose = 1 + +# Algorithms +algo.current_deposition = esirkepov +warpx.use_filter = 0 + +# implicit evolve scheme +algo.evolve_scheme = "semi_implicit_em" +# +implicit_evolve.nonlinear_solver = "newton" +newton.verbose = true +newton.max_iterations = 21 +newton.relative_tolerance = 1.0e-8 +newton.require_convergence = true +# +gmres.verbose_int = 2 +gmres.max_iterations = 1000 +gmres.relative_tolerance = 1.0e-4 + +# CFL +warpx.cfl = 1.0 + +# Order of particle shape factors +algo.particle_shape = 1 + +# Laser +lasers.names = laser1 +laser1.profile = Gaussian +laser1.position = 10.e-6 0.e-6 0.e-6 # This point is on the laser plane +laser1.direction = 2. 0. 1. # The plane normal direction +laser1.polarization = 1. 1. -2. # The main polarization vector +laser1.e_max = 4.e12 # Maximum amplitude of the laser field (in V/m) +laser1.wavelength = 1.0e-6 # The wavelength of the laser (in meters) +laser1.profile_waist = 5.e-6 # The waist of the laser (in meters) +laser1.profile_duration = 10.e-15 # The duration of the laser (in seconds) +laser1.profile_t_peak = 24.e-15 # The time at which the laser reaches its peak (in seconds) +laser1.profile_focal_distance = 13.109e-6 # Focal distance from the antenna (in meters) + # With this focal distance the laser is at focus + # at the end of the simulation. + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 240 +diag1.diag_type = Full + +# Moving window +warpx.do_moving_window = 1 +warpx.moving_window_dir = x +warpx.moving_window_v = 1.0 # in units of the speed of light +warpx.start_moving_window_step = 20 +warpx.end_moving_window_step = 200 diff --git a/Examples/Tests/laser_injection_from_file/CMakeLists.txt b/Examples/Tests/laser_injection_from_file/CMakeLists.txt index 4b4024b9029..d585160bc8f 100644 --- a/Examples/Tests/laser_injection_from_file/CMakeLists.txt +++ b/Examples/Tests/laser_injection_from_file/CMakeLists.txt @@ -7,7 +7,7 @@ add_warpx_test( 1 # nprocs inputs_test_1d_laser_injection_from_lasy_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 1 # dims 1 # nprocs inputs_test_1d_laser_injection_from_lasy_file # inputs - analysis_1d.py # analysis - diags/diag1000251 # output + "analysis_1d.py diags/diag1000251" # analysis + "analysis_default_regression.py --path diags/diag1000251" # checksum test_1d_laser_injection_from_lasy_file_prepare # dependency ) @@ -27,7 +27,7 @@ add_warpx_test( 1 # nprocs inputs_test_1d_laser_injection_from_lasy_file_boost_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 1 # dims 1 # nprocs inputs_test_1d_laser_injection_from_lasy_file_boost # inputs - analysis_1d_boost.py # analysis - diags/diag1000001 # output + "analysis_1d_boost.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum test_1d_laser_injection_from_lasy_file_boost_prepare # dependency ) @@ -47,7 +47,7 @@ add_warpx_test( 1 # nprocs inputs_test_2d_laser_injection_from_binary_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -56,8 +56,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_laser_injection_from_binary_file # inputs - analysis_2d_binary.py # analysis - diags/diag1000250 # output + "analysis_2d_binary.py diags/diag1000250" # analysis + "analysis_default_regression.py --path diags/diag1000250" # checksum test_2d_laser_injection_from_binary_file_prepare # dependency ) @@ -67,7 +67,7 @@ add_warpx_test( 1 # nprocs inputs_test_2d_laser_injection_from_lasy_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -76,8 +76,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_laser_injection_from_lasy_file # inputs - analysis_2d.py # analysis - diags/diag1000251 # output + "analysis_2d.py diags/diag1000251" # analysis + "analysis_default_regression.py --path diags/diag1000251" # checksum test_2d_laser_injection_from_lasy_file_prepare # dependency ) @@ -87,7 +87,7 @@ add_warpx_test( 1 # nprocs inputs_test_3d_laser_injection_from_lasy_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -96,8 +96,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_laser_injection_from_lasy_file # inputs - analysis_3d.py # analysis - diags/diag1000251 # output + "analysis_3d.py diags/diag1000251" # analysis + "analysis_default_regression.py --path diags/diag1000251" # checksum test_3d_laser_injection_from_lasy_file_prepare # dependency ) @@ -107,7 +107,7 @@ add_warpx_test( 1 # nprocs inputs_test_rz_laser_injection_from_lasy_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -116,8 +116,8 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_laser_injection_from_lasy_file # inputs - analysis_rz.py # analysis - diags/diag1000252 # output + "analysis_rz.py diags/diag1000252" # analysis + "analysis_default_regression.py --path diags/diag1000252" # checksum test_rz_laser_injection_from_lasy_file_prepare # dependency ) @@ -127,7 +127,7 @@ add_warpx_test( 1 # nprocs inputs_test_rz_laser_injection_from_RZ_lasy_file_prepare.py # inputs OFF # analysis - OFF # output + OFF # checksum OFF # dependency ) @@ -136,7 +136,7 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_laser_injection_from_RZ_lasy_file # inputs - analysis_from_RZ_file.py # analysis - diags/diag1000612 # output + "analysis_from_RZ_file.py diags/diag1000612" # analysis + "analysis_default_regression.py --path diags/diag1000612" # checksum test_rz_laser_injection_from_RZ_lasy_file_prepare # dependency ) diff --git a/Examples/Tests/laser_injection_from_file/analysis_1d.py b/Examples/Tests/laser_injection_from_file/analysis_1d.py index c6542ed1ac8..bd6a78f5949 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_1d.py +++ b/Examples/Tests/laser_injection_from_file/analysis_1d.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in 1D, for both envelope and central frequency -import os import sys import matplotlib @@ -27,9 +26,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -112,9 +108,3 @@ def gauss_env(T, Z): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_1d_boost.py b/Examples/Tests/laser_injection_from_file/analysis_1d_boost.py index e410369cb45..b51b32714de 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_1d_boost.py +++ b/Examples/Tests/laser_injection_from_file/analysis_1d_boost.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in 1D, for both envelope and central frequency -import os import sys import matplotlib @@ -27,9 +26,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -112,9 +108,3 @@ def gauss_env(T, Z): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_2d.py b/Examples/Tests/laser_injection_from_file/analysis_2d.py index 1e6704f55a5..21f5c186b7a 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_2d.py +++ b/Examples/Tests/laser_injection_from_file/analysis_2d.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in 2D, for both envelope and central frequency -import os import sys import matplotlib @@ -27,9 +26,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -138,9 +134,3 @@ def gauss_env(T, X, Y, Z): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_2d_binary.py b/Examples/Tests/laser_injection_from_file/analysis_2d_binary.py index 7fc14824471..d223026a073 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_2d_binary.py +++ b/Examples/Tests/laser_injection_from_file/analysis_2d_binary.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in 2D, for both envelope and central frequency -import os import sys import matplotlib @@ -26,9 +25,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -145,9 +141,3 @@ def gauss_env(T, XX, ZZ): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_3d.py b/Examples/Tests/laser_injection_from_file/analysis_3d.py index 3921e3d5930..cc19b742134 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_3d.py +++ b/Examples/Tests/laser_injection_from_file/analysis_3d.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in 3D, for both envelope and central frequency -import os import sys import matplotlib @@ -27,9 +26,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -144,9 +140,3 @@ def gauss_env(T, X, Y, Z): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_default_regression.py b/Examples/Tests/laser_injection_from_file/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/laser_injection_from_file/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/laser_injection_from_file/analysis_from_RZ_file.py b/Examples/Tests/laser_injection_from_file/analysis_from_RZ_file.py index f797ddb5d90..041e2917ece 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_from_RZ_file.py +++ b/Examples/Tests/laser_injection_from_file/analysis_from_RZ_file.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in RZ, for both envelope and central frequency -import os import sys import matplotlib @@ -28,9 +27,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -146,9 +142,3 @@ def laguerre_env(T, X, Y, Z, p, m): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_injection_from_file/analysis_rz.py b/Examples/Tests/laser_injection_from_file/analysis_rz.py index c37c6d8b3c2..1ad73b34c4b 100755 --- a/Examples/Tests/laser_injection_from_file/analysis_rz.py +++ b/Examples/Tests/laser_injection_from_file/analysis_rz.py @@ -13,7 +13,6 @@ # - Compute the theory for laser envelope at time T # - Compare theory and simulation in RZ, for both envelope and central frequency -import os import sys import matplotlib @@ -27,9 +26,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Maximum acceptable error for this test relative_error_threshold = 0.065 @@ -139,9 +135,3 @@ def gauss_env(T, X, Y, Z): relative_error_freq = np.abs(freq - exp_freq) / exp_freq print("Relative error frequency: ", relative_error_freq) assert relative_error_freq < relative_error_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/laser_on_fine/CMakeLists.txt b/Examples/Tests/laser_on_fine/CMakeLists.txt index 479374137df..9d9e48e54be 100644 --- a/Examples/Tests/laser_on_fine/CMakeLists.txt +++ b/Examples/Tests/laser_on_fine/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_laser_on_fine # inputs - analysis_default_regression.py # analysis - diags/diag1000050 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) diff --git a/Examples/Tests/load_external_field/CMakeLists.txt b/Examples/Tests/load_external_field/CMakeLists.txt index 0713dc877df..8641f307e16 100644 --- a/Examples/Tests/load_external_field/CMakeLists.txt +++ b/Examples/Tests/load_external_field/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_load_external_field_grid_picmi.py # inputs - analysis_3d.py # analysis - diags/diag1000300 # output + "analysis_3d.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_load_external_field_particle_picmi.py # inputs - analysis_3d.py # analysis - diags/diag1000300 # output + "analysis_3d.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_load_external_field_grid # inputs - analysis_rz.py # analysis - diags/diag1000300 # output + "analysis_rz.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_load_external_field_grid_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000300 # output + "analysis_default_restart.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum test_rz_load_external_field_grid # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_load_external_field_particles # inputs - analysis_rz.py # analysis - diags/diag1000300 # output + "analysis_rz.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -56,7 +56,7 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_load_external_field_particles_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000300 # output + "analysis_default_restart.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum test_rz_load_external_field_particles # dependency ) diff --git a/Examples/Tests/load_external_field/analysis_3d.py b/Examples/Tests/load_external_field/analysis_3d.py index 05cba3ea7bd..433a4bad5e8 100755 --- a/Examples/Tests/load_external_field/analysis_3d.py +++ b/Examples/Tests/load_external_field/analysis_3d.py @@ -16,15 +16,11 @@ # tolerance: 1.0e-8 # Possible running time: 2.756646401 s -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 1.0e-8 x0 = 0.12238072 y0 = 0.00965394 @@ -43,9 +39,3 @@ print("error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/load_external_field/analysis_default_regression.py b/Examples/Tests/load_external_field/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/load_external_field/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/load_external_field/analysis_rz.py b/Examples/Tests/load_external_field/analysis_rz.py index 7de160cdd50..e5601647d4a 100755 --- a/Examples/Tests/load_external_field/analysis_rz.py +++ b/Examples/Tests/load_external_field/analysis_rz.py @@ -16,15 +16,11 @@ # tolerance: 1.0e-8 # Possible running time: 0.327827743 s -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 1.0e-8 r0 = 0.12402005 z0 = 4.3632492 @@ -40,9 +36,3 @@ print("error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/magnetostatic_eb/CMakeLists.txt b/Examples/Tests/magnetostatic_eb/CMakeLists.txt index 3eb2da03136..5c0a87fd10a 100644 --- a/Examples/Tests/magnetostatic_eb/CMakeLists.txt +++ b/Examples/Tests/magnetostatic_eb/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_magnetostatic_eb # inputs - analysis_default_regression.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_magnetostatic_eb_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) endif() @@ -31,8 +31,8 @@ if(WarpX_EB) RZ # dims 1 # nprocs inputs_test_rz_magnetostatic_eb_picmi.py # inputs - analysis_rz.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/magnetostatic_eb/analysis_rz.py b/Examples/Tests/magnetostatic_eb/analysis_rz.py deleted file mode 100755 index f31069ad230..00000000000 --- a/Examples/Tests/magnetostatic_eb/analysis_rz.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/maxwell_hybrid_qed/CMakeLists.txt b/Examples/Tests/maxwell_hybrid_qed/CMakeLists.txt index 2c65c0a6ecb..c02d8abc567 100644 --- a/Examples/Tests/maxwell_hybrid_qed/CMakeLists.txt +++ b/Examples/Tests/maxwell_hybrid_qed/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_maxwell_hybrid_qed_solver # inputs - analysis.py # analysis - diags/diag1000300 # output + "analysis.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/maxwell_hybrid_qed/analysis_default_regression.py b/Examples/Tests/maxwell_hybrid_qed/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/maxwell_hybrid_qed/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/nci_fdtd_stability/CMakeLists.txt b/Examples/Tests/nci_fdtd_stability/CMakeLists.txt index e58e5bfb58f..9af4034c3ca 100644 --- a/Examples/Tests/nci_fdtd_stability/CMakeLists.txt +++ b/Examples/Tests/nci_fdtd_stability/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_nci_corrector # inputs - analysis_ncicorr.py # analysis - diags/diag1000600 # output + "analysis_ncicorr.py diags/diag1000600" # analysis + "analysis_default_regression.py --path diags/diag1000600" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_nci_corrector_mr # inputs - analysis_ncicorr.py # analysis - diags/diag1000600 # output + "analysis_ncicorr.py diags/diag1000600" # analysis + "analysis_default_regression.py --path diags/diag1000600" # checksum OFF # dependency ) diff --git a/Examples/Tests/nci_fdtd_stability/analysis_default_regression.py b/Examples/Tests/nci_fdtd_stability/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/nci_fdtd_stability/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/nci_fdtd_stability/analysis_ncicorr.py b/Examples/Tests/nci_fdtd_stability/analysis_ncicorr.py index ad635bf0fbe..290cdea819f 100755 --- a/Examples/Tests/nci_fdtd_stability/analysis_ncicorr.py +++ b/Examples/Tests/nci_fdtd_stability/analysis_ncicorr.py @@ -8,7 +8,6 @@ # License: BSD-3-Clause-LBNL -import os import re import sys @@ -18,9 +17,6 @@ yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - fn = sys.argv[1] use_MR = re.search("nci_correctorMR", fn) is not None @@ -49,9 +45,3 @@ print("energy from this run: %s" % energy) assert energy < energy_threshold - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/nci_psatd_stability/CMakeLists.txt b/Examples/Tests/nci_psatd_stability/CMakeLists.txt index f2b4ceae8ba..210fb13f542 100644 --- a/Examples/Tests/nci_psatd_stability/CMakeLists.txt +++ b/Examples/Tests/nci_psatd_stability/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_averaged_galilean_psatd # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_averaged_galilean_psatd_hybrid # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -31,8 +31,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_comoving_psatd_hybrid # inputs - analysis_default_regression.py # analysis - diags/diag1000400 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000400" # checksum OFF # dependency ) endif() @@ -43,8 +43,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_galilean_psatd # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -55,8 +55,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_galilean_psatd_current_correction # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -67,8 +67,8 @@ if(WarpX_FFT) 2 # dims 1 # nprocs inputs_test_2d_galilean_psatd_current_correction_psb # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -79,8 +79,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_galilean_psatd_hybrid # inputs - analysis_default_regression.py # analysis - diags/diag1000400 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000400" # checksum OFF # dependency ) endif() @@ -91,8 +91,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_averaged_galilean_psatd # inputs - analysis_galilean.py # analysis - diags/diag1000160 # output + "analysis_galilean.py diags/diag1000160" # analysis + "analysis_default_regression.py --path diags/diag1000160 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -103,8 +103,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_averaged_galilean_psatd_hybrid # inputs - analysis_galilean.py # analysis - diags/diag1000160 # output + "analysis_galilean.py diags/diag1000160" # analysis + "analysis_default_regression.py --path diags/diag1000160 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -115,8 +115,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_galilean_psatd # inputs - analysis_galilean.py # analysis - diags/diag1000300 # output + "analysis_galilean.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -127,8 +127,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_galilean_psatd_current_correction # inputs - analysis_galilean.py # analysis - diags/diag1000300 # output + "analysis_galilean.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -139,8 +139,8 @@ if(WarpX_FFT) 3 # dims 1 # nprocs inputs_test_3d_galilean_psatd_current_correction_psb # inputs - analysis_galilean.py # analysis - diags/diag1000300 # output + "analysis_galilean.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -151,8 +151,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_uniform_plasma_multiJ # inputs - analysis_multiJ.py # analysis - diags/diag1000300 # output + "analysis_multiJ.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) endif() @@ -163,8 +163,8 @@ if(WarpX_FFT) RZ # dims 1 # nprocs inputs_test_rz_galilean_psatd # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -175,8 +175,8 @@ if(WarpX_FFT) RZ # dims 2 # nprocs inputs_test_rz_galilean_psatd_current_correction # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -187,8 +187,8 @@ if(WarpX_FFT) RZ # dims 1 # nprocs inputs_test_rz_galilean_psatd_current_correction_psb # inputs - analysis_galilean.py # analysis - diags/diag1000400 # output + "analysis_galilean.py diags/diag1000400" # analysis + "analysis_default_regression.py --path diags/diag1000400 --rtol 1e-8" # checksum OFF # dependency ) endif() @@ -199,8 +199,8 @@ if(WarpX_FFT) RZ # dims 2 # nprocs inputs_test_rz_multiJ_psatd # inputs - analysis_default_regression.py # analysis - diags/diag1000025 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000025" # checksum OFF # dependency ) label_warpx_test(test_rz_multiJ_psatd slow) diff --git a/Examples/Tests/nci_psatd_stability/analysis_galilean.py b/Examples/Tests/nci_psatd_stability/analysis_galilean.py index 99f14d91371..43bdaedabbf 100755 --- a/Examples/Tests/nci_psatd_stability/analysis_galilean.py +++ b/Examples/Tests/nci_psatd_stability/analysis_galilean.py @@ -13,7 +13,6 @@ (suppressed by the Galilean PSATD method, without or with averaging, respectively). """ -import os import re import sys @@ -22,8 +21,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -117,10 +114,3 @@ print(f"err_charge = {err_charge}") print(f"tol_charge = {tol_charge}") assert err_charge < tol_charge - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-8, -) diff --git a/Examples/Tests/nci_psatd_stability/analysis_multiJ.py b/Examples/Tests/nci_psatd_stability/analysis_multiJ.py index 6dcfb6565fe..19ba722781b 100755 --- a/Examples/Tests/nci_psatd_stability/analysis_multiJ.py +++ b/Examples/Tests/nci_psatd_stability/analysis_multiJ.py @@ -10,7 +10,6 @@ both J and rho constant in time, and with divergence cleaning). """ -import os import sys import numpy as np @@ -18,8 +17,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -49,9 +46,3 @@ print(f"err_energy = {err_energy}") print(f"tol_energy = {tol_energy}") assert err_energy < tol_energy - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/nodal_electrostatic/CMakeLists.txt b/Examples/Tests/nodal_electrostatic/CMakeLists.txt index a6b3f5b0102..026ab1a34bc 100644 --- a/Examples/Tests/nodal_electrostatic/CMakeLists.txt +++ b/Examples/Tests/nodal_electrostatic/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_nodal_electrostatic_solver # inputs - analysis.py # analysis - diags/diag1000010 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) label_warpx_test(test_3d_nodal_electrostatic_solver slow) diff --git a/Examples/Tests/nodal_electrostatic/analysis.py b/Examples/Tests/nodal_electrostatic/analysis.py index f015d525280..b6d22d60a79 100755 --- a/Examples/Tests/nodal_electrostatic/analysis.py +++ b/Examples/Tests/nodal_electrostatic/analysis.py @@ -1,13 +1,7 @@ #!/usr/bin/env python3 -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # check that the maximum chi value is small fname = "diags/reducedfiles/ParticleExtrema_beam_p.txt" chi_max = np.loadtxt(fname)[:, 19] @@ -17,9 +11,3 @@ fname = "diags/reducedfiles/ParticleNumber.txt" pho_num = np.loadtxt(fname)[:, 7] assert pho_num.all() == 0.0 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/nodal_electrostatic/analysis_default_regression.py b/Examples/Tests/nodal_electrostatic/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/nodal_electrostatic/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/nuclear_fusion/CMakeLists.txt b/Examples/Tests/nuclear_fusion/CMakeLists.txt index c3ee8848e59..74d937601bd 100644 --- a/Examples/Tests/nuclear_fusion/CMakeLists.txt +++ b/Examples/Tests/nuclear_fusion/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_proton_boron_fusion # inputs - analysis_proton_boron_fusion.py # analysis - diags/diag1000001 # output + "analysis_proton_boron_fusion.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_deuterium_deuterium_fusion # inputs - analysis_two_product_fusion.py # analysis - diags/diag1000001 # output + "analysis_two_product_fusion.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_deuterium_deuterium_fusion_intraspecies # inputs - analysis_deuterium_deuterium_3d_intraspecies.py # analysis - diags/diag1000010 # output + "analysis_deuterium_deuterium_3d_intraspecies.py" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_deuterium_tritium_fusion # inputs - analysis_two_product_fusion.py # analysis - diags/diag1000001 # output + "analysis_two_product_fusion.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_proton_boron_fusion # inputs - analysis_proton_boron_fusion.py # analysis - diags/diag1000001 # output + "analysis_proton_boron_fusion.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -56,7 +56,7 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_deuterium_tritium_fusion # inputs - analysis_two_product_fusion.py # analysis - diags/diag1000001 # output + "analysis_two_product_fusion.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/nuclear_fusion/analysis_default_regression.py b/Examples/Tests/nuclear_fusion/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/nuclear_fusion/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/nuclear_fusion/analysis_deuterium_deuterium_3d_intraspecies.py b/Examples/Tests/nuclear_fusion/analysis_deuterium_deuterium_3d_intraspecies.py index 8ae0e768815..2b06a8c3f25 100755 --- a/Examples/Tests/nuclear_fusion/analysis_deuterium_deuterium_3d_intraspecies.py +++ b/Examples/Tests/nuclear_fusion/analysis_deuterium_deuterium_3d_intraspecies.py @@ -23,14 +23,8 @@ # Nuclear fusion, 32(4), p.611. # DOI: https://doi.org/10.1088/0029-5515/32/4/I07 -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Load data from reduced diagnostics (physical time and neutron weights) time = np.loadtxt("./reduced_diags/particle_number.txt", usecols=1) neutron = np.loadtxt("./reduced_diags/particle_number.txt", usecols=9) @@ -48,9 +42,3 @@ print("error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/nuclear_fusion/analysis_proton_boron_fusion.py b/Examples/Tests/nuclear_fusion/analysis_proton_boron_fusion.py index c69080ac726..917cd86f258 100755 --- a/Examples/Tests/nuclear_fusion/analysis_proton_boron_fusion.py +++ b/Examples/Tests/nuclear_fusion/analysis_proton_boron_fusion.py @@ -5,16 +5,12 @@ # # License: BSD-3-Clause-LBNL -import os import re import sys -import yt - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") import numpy as np import scipy.constants as scc -from checksumAPI import evaluate_checksum +import yt ## This script performs various checks for the proton boron nuclear fusion module. The simulation ## that we check is made of 5 different tests, each with different proton, boron and alpha species. @@ -880,12 +876,6 @@ def main(): rho_end = field_data_end["rho"].to_ndarray() check_charge_conservation(rho_start, rho_end) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/nuclear_fusion/analysis_two_product_fusion.py b/Examples/Tests/nuclear_fusion/analysis_two_product_fusion.py index 1a458a25e4a..38ab699a3a4 100755 --- a/Examples/Tests/nuclear_fusion/analysis_two_product_fusion.py +++ b/Examples/Tests/nuclear_fusion/analysis_two_product_fusion.py @@ -5,16 +5,12 @@ # # License: BSD-3-Clause-LBNL -import os import re import sys -import yt - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") import numpy as np import scipy.constants as scc -from checksumAPI import evaluate_checksum +import yt ## This script performs various checks for the fusion module. The simulation ## that we check is made of 2 different tests, each with different reactant and product species. @@ -555,12 +551,6 @@ def main(): rho_end = field_data_end["rho"].to_ndarray() check_charge_conservation(rho_start, rho_end) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/ohm_solver_cylinder_compression/CMakeLists.txt b/Examples/Tests/ohm_solver_cylinder_compression/CMakeLists.txt new file mode 100644 index 00000000000..c813d669fa6 --- /dev/null +++ b/Examples/Tests/ohm_solver_cylinder_compression/CMakeLists.txt @@ -0,0 +1,24 @@ +# Add tests (alphabetical order) ############################################## +# + +add_warpx_test( + test_3d_ohm_solver_cylinder_compression_picmi # name + 3 # dims + 2 # nprocs + "inputs_test_3d_ohm_solver_cylinder_compression_picmi.py --test" # inputs + OFF # analysis + "analysis_default_regression.py --path diags/diag1000020 --rtol 1e-6" # checksum + OFF # dependency +) +label_warpx_test(test_3d_ohm_solver_cylinder_compression_picmi slow) + +add_warpx_test( + test_rz_ohm_solver_cylinder_compression_picmi # name + RZ # dims + 2 # nprocs + "inputs_test_rz_ohm_solver_cylinder_compression_picmi.py --test" # inputs + OFF # analysis + "analysis_default_regression.py --path diags/diag1000020 --rtol 1e-6" # output + OFF # dependency +) +label_warpx_test(test_rz_ohm_solver_cylinder_compression_picmi slow) diff --git a/Examples/Tests/ohm_solver_cylinder_compression/analysis_default_regression.py b/Examples/Tests/ohm_solver_cylinder_compression/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ohm_solver_cylinder_compression/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_3d_ohm_solver_cylinder_compression_picmi.py b/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_3d_ohm_solver_cylinder_compression_picmi.py new file mode 100644 index 00000000000..a871bc97108 --- /dev/null +++ b/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_3d_ohm_solver_cylinder_compression_picmi.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +# +# --- Test script for the kinetic-fluid hybrid model in WarpX wherein ions are +# --- treated as kinetic particles and electrons as an isothermal, inertialess +# --- background fluid. The script demonstrates the use of this model to +# --- simulate adiabatic compression of a plasma cylinder initialized from an +# --- analytical Grad-Shafranov solution. + +import argparse +import shutil +import sys +from pathlib import Path + +import numpy as np +import openpmd_api as io +from mpi4py import MPI as mpi + +from pywarpx import fields, picmi + +constants = picmi.constants + +comm = mpi.COMM_WORLD + +simulation = picmi.Simulation(warpx_serialize_initial_conditions=True, verbose=False) + + +class PlasmaCylinderCompression(object): + # B0 is chosen with all other quantities scaled by it + n0 = 1e20 + T_i = 10 # eV + T_e = 0 + p0 = n0 * constants.q_e * T_i + + B0 = np.sqrt(2 * constants.mu0 * p0) # Initial magnetic field strength (T) + + # Do a 2x uniform B-field compression + dB = B0 + + # Flux Conserver radius + R_c = 0.5 + + # Plasma Radius (These values control the analytical GS solution) + R_p = 0.25 + delta_p = 0.025 + + # Domain parameters + LX = 2.0 * R_c * 1.05 # m + LY = 2.0 * R_c * 1.05 + LZ = 0.5 # m + + LT = 10 # ion cyclotron periods + DT = 1e-3 # ion cyclotron periods + + # Resolution parameters + NX = 256 + NY = 256 + NZ = 128 + + # Starting number of particles per cell + NPPC = 100 + + # Number of substeps used to update B + substeps = 20 + + def Bz(self, r): + return np.sqrt( + self.B0**2 + - 2.0 + * constants.mu0 + * self.n0 + * constants.q_e + * self.T_i + / (1.0 + np.exp((r - self.R_p) / self.delta_p)) + ) + + def __init__(self, test, verbose): + self.test = test + self.verbose = verbose or self.test + + self.Lx = self.LX + self.Ly = self.LY + self.Lz = self.LZ + + self.DX = self.LX / self.NX + self.DY = self.LY / self.NY + self.DZ = self.LZ / self.NZ + + if comm.rank == 0: + # Write uniform compression dataset to OpenPMD to exercise reading openPMD data + # for the time varying external fields + xvec = np.linspace(-self.LX, self.LX, num=2 * self.NX) + yvec = np.linspace(-self.LY, self.LY, num=2 * self.NY) + zvec = np.linspace(-self.LZ, self.LZ, num=2 * self.NZ) + XM, YM, ZM = np.meshgrid(xvec, yvec, zvec, indexing="ij") + + RM = np.sqrt(XM**2 + YM**2) + + Ax_data = -0.25 * YM * self.dB + Ay_data = 0.25 * XM * self.dB + Az_data = np.zeros_like(RM) + + # Write vector potential to file to exercise field loading via OpenPMD + series = io.Series("Afield.h5", io.Access.create) + + it = series.iterations[0] + + A = it.meshes["A"] + A.grid_spacing = [self.DX, self.DY, self.DZ] + A.grid_global_offset = [-self.LX, -self.LY, -self.LZ] + A.grid_unit_SI = 1.0 + A.axis_labels = ["x", "y", "z"] + A.data_order = "C" + A.unit_dimension = { + io.Unit_Dimension.M: 1.0, + io.Unit_Dimension.T: -2.0, + io.Unit_Dimension.I: -1.0, + io.Unit_Dimension.L: -1.0, + } + + Ax = A["x"] + Ay = A["y"] + Az = A["z"] + + Ax.position = [0.0, 0.0] + Ay.position = [0.0, 0.0] + Az.position = [0.0, 0.0] + + Ax_dataset = io.Dataset(Ax_data.dtype, Ax_data.shape) + + Ay_dataset = io.Dataset(Ay_data.dtype, Ay_data.shape) + + Az_dataset = io.Dataset(Az_data.dtype, Az_data.shape) + + Ax.reset_dataset(Ax_dataset) + Ay.reset_dataset(Ay_dataset) + Az.reset_dataset(Az_dataset) + + Ax.store_chunk(Ax_data) + Ay.store_chunk(Ay_data) + Az.store_chunk(Az_data) + + series.flush() + series.close() + + comm.Barrier() + + # calculate various plasma parameters based on the simulation input + self.get_plasma_quantities() + + self.dt = self.DT * self.t_ci + + # run very low resolution as a CI test + if self.test: + self.total_steps = 20 + self.diag_steps = self.total_steps // 5 + self.NX = 64 + self.NY = 64 + self.NZ = 32 + else: + self.total_steps = int(self.LT / self.DT) + self.diag_steps = 100 + + # print out plasma parameters + if comm.rank == 0: + print( + f"Initializing simulation with input parameters:\n" + f"\tTi = {self.T_i:.1f} eV\n" + f"\tn0 = {self.n0:.1e} m^-3\n" + f"\tB0 = {self.B0:.2f} T\n", + f"\tDX/DY = {self.DX / self.l_i:.3f} c/w_pi\n" + f"\tDZ = {self.DZ / self.l_i:.3f} c/w_pi\n", + ) + print( + f"Plasma parameters:\n" + f"\tl_i = {self.l_i:.1e} m\n" + f"\tt_ci = {self.t_ci:.1e} s\n" + f"\tv_ti = {self.vi_th:.1e} m/s\n" + f"\tvA = {self.vA:.1e} m/s\n" + ) + print( + f"Numerical parameters:\n" + f"\tdz = {self.Lz / self.NZ:.1e} m\n" + f"\tdt = {self.dt:.1e} s\n" + f"\tdiag steps = {self.diag_steps:d}\n" + f"\ttotal steps = {self.total_steps:d}\n" + ) + + self.setup_run() + + def get_plasma_quantities(self): + """Calculate various plasma parameters based on the simulation input.""" + + # Ion mass (kg) + self.M = constants.m_p + + # Cyclotron angular frequency (rad/s) and period (s) + self.w_ci = constants.q_e * abs(self.B0) / self.M + self.t_ci = 2.0 * np.pi / self.w_ci + + # Ion plasma frequency (Hz) + self.w_pi = np.sqrt(constants.q_e**2 * self.n0 / (self.M * constants.ep0)) + + # Ion skin depth (m) + self.l_i = constants.c / self.w_pi + + # # Alfven speed (m/s): vA = B / sqrt(mu0 * n * (M + m)) = c * omega_ci / w_pi + self.vA = abs(self.B0) / np.sqrt( + constants.mu0 * self.n0 * (constants.m_e + self.M) + ) + + # calculate thermal speeds + self.vi_th = np.sqrt(self.T_i * constants.q_e / self.M) + + # Ion Larmor radius (m) + self.rho_i = self.vi_th / self.w_ci + + def load_fields(self): + Bx = fields.BxFPExternalWrapper(include_ghosts=False) + By = fields.ByFPExternalWrapper(include_ghosts=False) + Bz = fields.BzFPExternalWrapper(include_ghosts=False) + + Bx[:, :] = 0.0 + By[:, :] = 0.0 + + XM, YM, ZM = np.meshgrid( + Bz.mesh("x"), Bz.mesh("y"), Bz.mesh("z"), indexing="ij" + ) + + RM = np.sqrt(XM**2 + YM**2) + + Bz[:, :] = self.Bz(RM) + comm.Barrier() + + def setup_run(self): + """Setup simulation components.""" + + ####################################################################### + # Set geometry and boundary conditions # + ####################################################################### + + # Create grid + self.grid = picmi.Cartesian3DGrid( + number_of_cells=[self.NX, self.NY, self.NZ], + lower_bound=[-0.5 * self.Lx, -0.5 * self.Ly, -0.5 * self.Lz], + upper_bound=[0.5 * self.Lx, 0.5 * self.Ly, 0.5 * self.Lz], + lower_boundary_conditions=["dirichlet", "dirichlet", "periodic"], + upper_boundary_conditions=["dirichlet", "dirichlet", "periodic"], + lower_boundary_conditions_particles=["absorbing", "absorbing", "periodic"], + upper_boundary_conditions_particles=["absorbing", "absorbing", "periodic"], + warpx_max_grid_size=self.NZ, + ) + simulation.time_step_size = self.dt + simulation.max_steps = self.total_steps + simulation.current_deposition_algo = "direct" + simulation.particle_shape = 1 + simulation.use_filter = True + simulation.verbose = self.verbose + + ####################################################################### + # Field solver and external field # + ####################################################################### + # External Field definition. Sigmoid starting around 2.5 us + A_ext = { + "uniform_file": { + "read_from_file": True, + "path": "Afield.h5", + "A_time_external_function": "1/(1+exp(5*(1-(t-t0_ramp)*sqrt(2)/tau_ramp)))", + }, + "uniform_analytical": { + "Ax_external_function": f"-0.25*y*{self.dB}", + "Ay_external_function": f"0.25*x*{self.dB}", + "Az_external_function": "0", + "A_time_external_function": "1/(1+exp(5*(1-(t-t0_ramp)*sqrt(2)/tau_ramp)))", + }, + } + + self.solver = picmi.HybridPICSolver( + grid=self.grid, + gamma=1.0, + Te=self.T_e, + n0=self.n0, + n_floor=0.05 * self.n0, + plasma_resistivity="if(rho<=rho_floor,eta_v,eta_p)", + plasma_hyper_resistivity=1e-8, + substeps=self.substeps, + A_external=A_ext, + tau_ramp=20e-6, + t0_ramp=5e-6, + rho_floor=0.05 * self.n0 * constants.q_e, + eta_p=1e-8, + eta_v=1e-3, + ) + simulation.solver = self.solver + + simulation.embedded_boundary = picmi.EmbeddedBoundary( + implicit_function="(x**2+y**2-R_w**2)", R_w=self.R_c + ) + + # Add field loader callback + B_ext = picmi.LoadInitialFieldFromPython( + load_from_python=self.load_fields, + warpx_do_divb_cleaning_external=True, + load_B=True, + load_E=False, + ) + simulation.add_applied_field(B_ext) + + ####################################################################### + # Particle types setup # + ####################################################################### + r_omega = "(sqrt(x*x+y*y)*q_e*B0/m_p)" + dlnndr = "((-1/delta_p)/(1+exp(-(sqrt(x*x+y*y)-R_p)/delta_p)))" + vth = f"0.5*(-{r_omega}+sqrt({r_omega}*{r_omega}+4*q_e*T_i*{dlnndr}/m_p))" + + momentum_expr = [f"y*{vth}", f"-x*{vth}", "0"] + + self.ions = picmi.Species( + name="ions", + charge="q_e", + mass=self.M, + initial_distribution=picmi.AnalyticDistribution( + density_expression="n0_p/(1+exp((sqrt(x*x+y*y)-R_p)/delta_p))", + momentum_expressions=momentum_expr, + warpx_momentum_spread_expressions=[f"{str(self.vi_th)}"] * 3, + warpx_density_min=0.01 * self.n0, + R_p=self.R_p, + delta_p=self.delta_p, + n0_p=self.n0, + B0=self.B0, + T_i=self.T_i, + ), + ) + simulation.add_species( + self.ions, + layout=picmi.PseudoRandomLayout( + grid=self.grid, n_macroparticles_per_cell=self.NPPC + ), + ) + + ####################################################################### + # Add diagnostics # + ####################################################################### + + if self.test: + particle_diag = picmi.ParticleDiagnostic( + name="diag1", + period=self.diag_steps, + species=[self.ions], + data_list=["ux", "uy", "uz", "x", "z", "weighting"], + write_dir="diags", + warpx_format="plotfile", + ) + simulation.add_diagnostic(particle_diag) + field_diag = picmi.FieldDiagnostic( + name="diag1", + grid=self.grid, + period=self.diag_steps, + data_list=["B", "E", "rho"], + write_dir="diags", + warpx_format="plotfile", + ) + simulation.add_diagnostic(field_diag) + + ####################################################################### + # Initialize # + ####################################################################### + + if comm.rank == 0: + if Path.exists(Path("diags")): + shutil.rmtree("diags") + Path("diags").mkdir(parents=True, exist_ok=True) + + # Initialize inputs and WarpX instance + simulation.initialize_inputs() + simulation.initialize_warpx() + + +########################## +# parse input parameters +########################## + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--test", + help="toggle whether this script is run as a short CI test", + action="store_true", +) +parser.add_argument( + "-v", + "--verbose", + help="Verbose output", + action="store_true", +) +args, left = parser.parse_known_args() +sys.argv = sys.argv[:1] + left + +run = PlasmaCylinderCompression(test=args.test, verbose=args.verbose) +simulation.step() diff --git a/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_rz_ohm_solver_cylinder_compression_picmi.py b/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_rz_ohm_solver_cylinder_compression_picmi.py new file mode 100644 index 00000000000..17fc6d68144 --- /dev/null +++ b/Examples/Tests/ohm_solver_cylinder_compression/inputs_test_rz_ohm_solver_cylinder_compression_picmi.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +# +# --- Test script for the kinetic-fluid hybrid model in WarpX wherein ions are +# --- treated as kinetic particles and electrons as an isothermal, inertialess +# --- background fluid. The script demonstrates the use of this model to +# --- simulate adiabatic compression of a plasma cylinder initialized from an +# --- analytical Grad-Shafranov solution. + +import argparse +import shutil +import sys +from pathlib import Path + +import numpy as np +import openpmd_api as io +from mpi4py import MPI as mpi + +from pywarpx import fields, picmi + +constants = picmi.constants + +comm = mpi.COMM_WORLD + +simulation = picmi.Simulation(warpx_serialize_initial_conditions=True, verbose=False) + + +class PlasmaCylinderCompression(object): + # B0 is chosen with all other quantities scaled by it + n0 = 1e20 + T_i = 10 # eV + T_e = 0 + p0 = n0 * constants.q_e * T_i + + B0 = np.sqrt(2 * constants.mu0 * p0) # External magnetic field strength (T) + + # Do a 2x uniform B-field compression + dB = B0 + + # Flux Conserver radius + R_c = 0.5 + + # Plasma Radius (These values control the analytical GS solution) + R_p = 0.25 + delta_p = 0.025 + + # Domain parameters + LR = R_c # m + LZ = 0.25 * R_c # m + + LT = 10 # ion cyclotron periods + DT = 1e-3 # ion cyclotron periods + + # Resolution parameters + NR = 128 + NZ = 32 + + # Starting number of particles per cell + NPPC = 100 + + # Number of substeps used to update B + substeps = 20 + + def Bz(self, r): + return np.sqrt( + self.B0**2 + - 2.0 + * constants.mu0 + * self.n0 + * constants.q_e + * self.T_i + / (1.0 + np.exp((r - self.R_p) / self.delta_p)) + ) + + def __init__(self, test, verbose): + self.test = test + self.verbose = verbose or self.test + + self.Lr = self.LR + self.Lz = self.LZ + + self.DR = self.LR / self.NR + self.DZ = self.LZ / self.NZ + + # Write A to OpenPMD for a uniform B field to exercise file based loader + if comm.rank == 0: + mvec = np.array([0]) + rvec = np.linspace(0, 2 * self.LR, num=2 * self.NR) + zvec = np.linspace(-self.LZ, self.LZ, num=2 * self.NZ) + MM, RM, ZM = np.meshgrid(mvec, rvec, zvec, indexing="ij") + + # Write uniform compression dataset to OpenPMD to exercise reading openPMD data + # for the time varying external fields + Ar_data = np.zeros_like(RM) + Az_data = np.zeros_like(RM) + + # Only include half of the compression field here + At_data = 0.25 * RM * self.dB + + # Write vector potential to file to exercise field loading via + series = io.Series("Afield.h5", io.Access.create) + + it = series.iterations[0] + + A = it.meshes["A"] + A.geometry = io.Geometry.thetaMode + A.geometry_parameters = "m=0" + A.grid_spacing = [self.DR, self.DZ] + A.grid_global_offset = [0.0, -self.LZ] + A.grid_unit_SI = 1.0 + A.axis_labels = ["r", "z"] + A.data_order = "C" + A.unit_dimension = { + io.Unit_Dimension.M: 1.0, + io.Unit_Dimension.T: -2.0, + io.Unit_Dimension.I: -1.0, + io.Unit_Dimension.L: -1.0, + } + + Ar = A["r"] + At = A["t"] + Az = A["z"] + + Ar.position = [0.0, 0.0] + At.position = [0.0, 0.0] + Az.position = [0.0, 0.0] + + Ar_dataset = io.Dataset(Ar_data.dtype, Ar_data.shape) + + At_dataset = io.Dataset(At_data.dtype, At_data.shape) + + Az_dataset = io.Dataset(Az_data.dtype, Az_data.shape) + + Ar.reset_dataset(Ar_dataset) + At.reset_dataset(At_dataset) + Az.reset_dataset(Az_dataset) + + Ar.store_chunk(Ar_data) + At.store_chunk(At_data) + Az.store_chunk(Az_data) + + series.flush() + series.close() + + comm.Barrier() + + # calculate various plasma parameters based on the simulation input + self.get_plasma_quantities() + + self.dt = self.DT * self.t_ci + + # run very low resolution as a CI test + if self.test: + self.total_steps = 20 + self.diag_steps = self.total_steps // 5 + self.NR = 64 + self.NZ = 16 + else: + self.total_steps = int(self.LT / self.DT) + self.diag_steps = 100 + + # print out plasma parameters + if comm.rank == 0: + print( + f"Initializing simulation with input parameters:\n" + f"\tTi = {self.T_i:.1f} eV\n" + f"\tn0 = {self.n0:.1e} m^-3\n" + f"\tB0 = {self.B0:.2f} T\n", + f"\tDR = {self.DR / self.l_i:.3f} c/w_pi\n" + f"\tDZ = {self.DZ / self.l_i:.3f} c/w_pi\n", + ) + print( + f"Plasma parameters:\n" + f"\tl_i = {self.l_i:.1e} m\n" + f"\tt_ci = {self.t_ci:.1e} s\n" + f"\tv_ti = {self.vi_th:.1e} m/s\n" + f"\tvA = {self.vA:.1e} m/s\n" + ) + print( + f"Numerical parameters:\n" + f"\tdz = {self.Lz / self.NZ:.1e} m\n" + f"\tdt = {self.dt:.1e} s\n" + f"\tdiag steps = {self.diag_steps:d}\n" + f"\ttotal steps = {self.total_steps:d}\n" + ) + + self.setup_run() + + def get_plasma_quantities(self): + """Calculate various plasma parameters based on the simulation input.""" + + # Ion mass (kg) + self.M = constants.m_p + + # Cyclotron angular frequency (rad/s) and period (s) + self.w_ci = constants.q_e * abs(self.B0) / self.M + self.t_ci = 2.0 * np.pi / self.w_ci + + # Ion plasma frequency (Hz) + self.w_pi = np.sqrt(constants.q_e**2 * self.n0 / (self.M * constants.ep0)) + + # Ion skin depth (m) + self.l_i = constants.c / self.w_pi + + # # Alfven speed (m/s): vA = B / sqrt(mu0 * n * (M + m)) = c * omega_ci / w_pi + self.vA = abs(self.B0) / np.sqrt( + constants.mu0 * self.n0 * (constants.m_e + self.M) + ) + + # calculate thermal speeds + self.vi_th = np.sqrt(self.T_i * constants.q_e / self.M) + + # Ion Larmor radius (m) + self.rho_i = self.vi_th / self.w_ci + + def load_fields(self): + Br = fields.BxFPExternalWrapper(include_ghosts=False) + Bt = fields.ByFPExternalWrapper(include_ghosts=False) + Bz = fields.BzFPExternalWrapper(include_ghosts=False) + + Br[:, :] = 0.0 + Bt[:, :] = 0.0 + + RM, ZM = np.meshgrid(Bz.mesh("r"), Bz.mesh("z"), indexing="ij") + + Bz[:, :] = self.Bz(RM) * (RM <= self.R_c) + comm.Barrier() + + def setup_run(self): + """Setup simulation components.""" + + ####################################################################### + # Set geometry and boundary conditions # + ####################################################################### + + # Create grid + self.grid = picmi.CylindricalGrid( + number_of_cells=[self.NR, self.NZ], + lower_bound=[0.0, -self.Lz / 2.0], + upper_bound=[self.Lr, self.Lz / 2.0], + lower_boundary_conditions=["none", "periodic"], + upper_boundary_conditions=["dirichlet", "periodic"], + lower_boundary_conditions_particles=["none", "periodic"], + upper_boundary_conditions_particles=["absorbing", "periodic"], + warpx_max_grid_size=self.NZ, + ) + simulation.time_step_size = self.dt + simulation.max_steps = self.total_steps + simulation.current_deposition_algo = "direct" + simulation.particle_shape = 1 + simulation.use_filter = True + simulation.verbose = self.verbose + + ####################################################################### + # Field solver and external field # + ####################################################################### + # External Field definition. Sigmoid starting around 2.5 us + A_ext = { + "uniform_file": { + "read_from_file": True, + "path": "Afield.h5", + "A_time_external_function": "1/(1+exp(5*(1-(t-t0_ramp)*sqrt(2)/tau_ramp)))", + }, + "uniform_analytical": { + "Ax_external_function": f"-0.25*y*{self.dB}", + "Ay_external_function": f"0.25*x*{self.dB}", + "Az_external_function": "0", + "A_time_external_function": "1/(1+exp(5*(1-(t-t0_ramp)*sqrt(2)/tau_ramp)))", + }, + } + + self.solver = picmi.HybridPICSolver( + grid=self.grid, + gamma=1.0, + Te=self.T_e, + n0=self.n0, + n_floor=0.05 * self.n0, + plasma_resistivity="if(rho<=rho_floor,eta_v,eta_p)", + plasma_hyper_resistivity=1e-8, + substeps=self.substeps, + A_external=A_ext, + tau_ramp=20e-6, + t0_ramp=5e-6, + rho_floor=0.05 * self.n0 * constants.q_e, + eta_p=1e-8, + eta_v=1e-3, + ) + simulation.solver = self.solver + + # Add field loader callback + B_ext = picmi.LoadInitialFieldFromPython( + load_from_python=self.load_fields, + warpx_do_divb_cleaning_external=True, + load_B=True, + load_E=False, + ) + simulation.add_applied_field(B_ext) + + ####################################################################### + # Particle types setup # + ####################################################################### + r_omega = "(sqrt(x*x+y*y)*q_e*B0/m_p)" + dlnndr = "((-1/delta_p)/(1+exp(-(sqrt(x*x+y*y)-R_p)/delta_p)))" + vth = f"0.5*(-{r_omega}+sqrt({r_omega}*{r_omega}+4*q_e*T_i*{dlnndr}/m_p))" + + momentum_expr = [f"y*{vth}", f"-x*{vth}", "0"] + + self.ions = picmi.Species( + name="ions", + charge="q_e", + mass=self.M, + initial_distribution=picmi.AnalyticDistribution( + density_expression="n0_p/(1+exp((sqrt(x*x+y*y)-R_p)/delta_p))", + momentum_expressions=momentum_expr, + warpx_momentum_spread_expressions=[f"{str(self.vi_th)}"] * 3, + warpx_density_min=0.01 * self.n0, + R_p=self.R_p, + delta_p=self.delta_p, + n0_p=self.n0, + B0=self.B0, + T_i=self.T_i, + ), + ) + simulation.add_species( + self.ions, + layout=picmi.PseudoRandomLayout( + grid=self.grid, n_macroparticles_per_cell=self.NPPC + ), + ) + + ####################################################################### + # Add diagnostics # + ####################################################################### + + if self.test: + particle_diag = picmi.ParticleDiagnostic( + name="diag1", + period=self.diag_steps, + species=[self.ions], + data_list=["ux", "uy", "uz", "x", "z", "weighting"], + write_dir="diags", + warpx_format="plotfile", + ) + simulation.add_diagnostic(particle_diag) + field_diag = picmi.FieldDiagnostic( + name="diag1", + grid=self.grid, + period=self.diag_steps, + data_list=["B", "E", "rho"], + write_dir="diags", + warpx_format="plotfile", + ) + simulation.add_diagnostic(field_diag) + + ####################################################################### + # Initialize # + ####################################################################### + + if comm.rank == 0: + if Path.exists(Path("diags")): + shutil.rmtree("diags") + Path("diags").mkdir(parents=True, exist_ok=True) + + # Initialize inputs and WarpX instance + simulation.initialize_inputs() + simulation.initialize_warpx() + + +########################## +# parse input parameters +########################## + +parser = argparse.ArgumentParser() +parser.add_argument( + "-t", + "--test", + help="toggle whether this script is run as a short CI test", + action="store_true", +) +parser.add_argument( + "-v", + "--verbose", + help="Verbose output", + action="store_true", +) +args, left = parser.parse_known_args() +sys.argv = sys.argv[:1] + left + +run = PlasmaCylinderCompression(test=args.test, verbose=args.verbose) +simulation.step() diff --git a/Examples/Tests/ohm_solver_em_modes/CMakeLists.txt b/Examples/Tests/ohm_solver_em_modes/CMakeLists.txt index a08c321d88d..03843fe29f6 100644 --- a/Examples/Tests/ohm_solver_em_modes/CMakeLists.txt +++ b/Examples/Tests/ohm_solver_em_modes/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs "inputs_test_1d_ohm_solver_em_modes_picmi.py --test --dim 1 --bdir z" # inputs - analysis.py # analysis - diags/field_diag000250 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/field_diag000250" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( RZ # dims 2 # nprocs "inputs_test_rz_ohm_solver_em_modes_picmi.py --test" # inputs - analysis_rz.py # analysis - diags/diag1000100 # output + "analysis_rz.py" # analysis + "analysis_default_regression.py --path diags/diag1000100 --rtol 1e-6" # checksum OFF # dependency ) label_warpx_test(test_rz_ohm_solver_em_modes_picmi slow) diff --git a/Examples/Tests/ohm_solver_em_modes/analysis.py b/Examples/Tests/ohm_solver_em_modes/analysis.py index bee634415d9..e2075944932 100755 --- a/Examples/Tests/ohm_solver_em_modes/analysis.py +++ b/Examples/Tests/ohm_solver_em_modes/analysis.py @@ -347,16 +347,3 @@ def get_analytic_L_mode(w): ) if not sim.test: plt.show() - -if sim.test: - import os - import sys - - sys.path.insert(1, "../../../../warpx/Regression/Checksum/") - from checksumAPI import evaluate_checksum - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) diff --git a/Examples/Tests/ohm_solver_em_modes/analysis_default_regression.py b/Examples/Tests/ohm_solver_em_modes/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ohm_solver_em_modes/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ohm_solver_em_modes/analysis_rz.py b/Examples/Tests/ohm_solver_em_modes/analysis_rz.py index a1eb185bbf6..7cd5086c408 100755 --- a/Examples/Tests/ohm_solver_em_modes/analysis_rz.py +++ b/Examples/Tests/ohm_solver_em_modes/analysis_rz.py @@ -179,19 +179,5 @@ def process(it): amps = np.abs(F_kw[2, 1, len(kz) // 2 - 2 : len(kz) // 2 + 2]) print("Amplitude sample: ", amps) assert np.allclose( - amps, np.array([61.02377286, 19.80026021, 100.47687017, 10.83331295]) - ) - -if sim.test: - import os - import sys - - sys.path.insert(1, "../../../../warpx/Regression/Checksum/") - from checksumAPI import evaluate_checksum - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-6, + amps, np.array([59.23850009, 19.26746169, 92.65794174, 10.83627164]) ) diff --git a/Examples/Tests/ohm_solver_ion_Landau_damping/CMakeLists.txt b/Examples/Tests/ohm_solver_ion_Landau_damping/CMakeLists.txt index 501b1ce2ced..a57ef7bb922 100644 --- a/Examples/Tests/ohm_solver_ion_Landau_damping/CMakeLists.txt +++ b/Examples/Tests/ohm_solver_ion_Landau_damping/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs "inputs_test_2d_ohm_solver_landau_damping_picmi.py --test --dim 2 --temp_ratio 0.1" # inputs - analysis.py # analysis - diags/diag1000100 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) label_warpx_test(test_2d_ohm_solver_landau_damping_picmi slow) diff --git a/Examples/Tests/ohm_solver_ion_Landau_damping/analysis.py b/Examples/Tests/ohm_solver_ion_Landau_damping/analysis.py index 620331cf13f..bd193260f2f 100755 --- a/Examples/Tests/ohm_solver_ion_Landau_damping/analysis.py +++ b/Examples/Tests/ohm_solver_ion_Landau_damping/analysis.py @@ -111,16 +111,3 @@ ax1.set_title(f"Ion Landau damping - {sim.dim}d") plt.tight_layout() plt.savefig(f"diags/ion_Landau_damping_T_ratio_{sim.T_ratio}.png") - -if sim.test: - import os - import sys - - sys.path.insert(1, "../../../../warpx/Regression/Checksum/") - from checksumAPI import evaluate_checksum - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) diff --git a/Examples/Tests/ohm_solver_ion_Landau_damping/analysis_default_regression.py b/Examples/Tests/ohm_solver_ion_Landau_damping/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ohm_solver_ion_Landau_damping/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ohm_solver_ion_Landau_damping/inputs_test_2d_ohm_solver_landau_damping_picmi.py b/Examples/Tests/ohm_solver_ion_Landau_damping/inputs_test_2d_ohm_solver_landau_damping_picmi.py index 7c1709d059f..320d36785db 100644 --- a/Examples/Tests/ohm_solver_ion_Landau_damping/inputs_test_2d_ohm_solver_landau_damping_picmi.py +++ b/Examples/Tests/ohm_solver_ion_Landau_damping/inputs_test_2d_ohm_solver_landau_damping_picmi.py @@ -93,7 +93,7 @@ def __init__(self, test, dim, m, T_ratio, verbose): if comm.rank == 0: print( f"Initializing simulation with input parameters:\n" - f"\tT = {self.T_plasma*1e-3:.1f} keV\n" + f"\tT = {self.T_plasma * 1e-3:.1f} keV\n" f"\tn = {self.n_plasma:.1e} m^-3\n" f"\tB0 = {self.B0:.2f} T\n" f"\tM/m = {self.m_ion:.0f}\n" diff --git a/Examples/Tests/ohm_solver_ion_beam_instability/CMakeLists.txt b/Examples/Tests/ohm_solver_ion_beam_instability/CMakeLists.txt index 81c6b0d41fd..288f8e32e53 100644 --- a/Examples/Tests/ohm_solver_ion_beam_instability/CMakeLists.txt +++ b/Examples/Tests/ohm_solver_ion_beam_instability/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs "inputs_test_1d_ohm_solver_ion_beam_picmi.py --test --dim 1 --resonant" # inputs - analysis.py # analysis - diags/diag1002500 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1002500" # checksum OFF # dependency ) label_warpx_test(test_1d_ohm_solver_ion_beam_picmi slow) diff --git a/Examples/Tests/ohm_solver_ion_beam_instability/analysis.py b/Examples/Tests/ohm_solver_ion_beam_instability/analysis.py index 3b0a18f29d5..978b8b9a731 100755 --- a/Examples/Tests/ohm_solver_ion_beam_instability/analysis.py +++ b/Examples/Tests/ohm_solver_ion_beam_instability/analysis.py @@ -230,16 +230,3 @@ assert np.isclose(m4_rms_error, 1.515, atol=0.01) assert np.isclose(m5_rms_error, 0.718, atol=0.01) assert np.isclose(m6_rms_error, 0.357, atol=0.01) - - # checksum check - import os - import sys - - sys.path.insert(1, "../../../../warpx/Regression/Checksum/") - from checksumAPI import evaluate_checksum - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) diff --git a/Examples/Tests/ohm_solver_ion_beam_instability/analysis_default_regression.py b/Examples/Tests/ohm_solver_ion_beam_instability/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ohm_solver_ion_beam_instability/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ohm_solver_ion_beam_instability/inputs_test_1d_ohm_solver_ion_beam_picmi.py b/Examples/Tests/ohm_solver_ion_beam_instability/inputs_test_1d_ohm_solver_ion_beam_picmi.py index 19569a04e5b..52160038831 100644 --- a/Examples/Tests/ohm_solver_ion_beam_instability/inputs_test_1d_ohm_solver_ion_beam_picmi.py +++ b/Examples/Tests/ohm_solver_ion_beam_instability/inputs_test_1d_ohm_solver_ion_beam_picmi.py @@ -110,7 +110,7 @@ def __init__(self, test, dim, resonant, verbose): if comm.rank == 0: print( f"Initializing simulation with input parameters:\n" - f"\tT = {self.T_plasma*1e-3:.1f} keV\n" + f"\tT = {self.T_plasma * 1e-3:.1f} keV\n" f"\tn = {self.n_plasma:.1e} m^-3\n" f"\tB0 = {self.B0:.2f} T\n" f"\tM/m = {self.m_ion:.0f}\n" diff --git a/Examples/Tests/ohm_solver_magnetic_reconnection/CMakeLists.txt b/Examples/Tests/ohm_solver_magnetic_reconnection/CMakeLists.txt index cef47a7d95e..02b4f5e3cb9 100644 --- a/Examples/Tests/ohm_solver_magnetic_reconnection/CMakeLists.txt +++ b/Examples/Tests/ohm_solver_magnetic_reconnection/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs "inputs_test_2d_ohm_solver_magnetic_reconnection_picmi.py --test" # inputs - analysis.py # analysis - diags/diag1000020 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) diff --git a/Examples/Tests/ohm_solver_magnetic_reconnection/analysis.py b/Examples/Tests/ohm_solver_magnetic_reconnection/analysis.py index e7b41d4fbb4..84ab7140fd4 100755 --- a/Examples/Tests/ohm_solver_magnetic_reconnection/analysis.py +++ b/Examples/Tests/ohm_solver_magnetic_reconnection/analysis.py @@ -184,16 +184,3 @@ def animate(i): writervideo = FFMpegWriter(fps=14) anim.save("diags/mag_reconnection.mp4", writer=writervideo) - -if sim.test: - import os - import sys - - sys.path.insert(1, "../../../../warpx/Regression/Checksum/") - from checksumAPI import evaluate_checksum - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) diff --git a/Examples/Tests/ohm_solver_magnetic_reconnection/analysis_default_regression.py b/Examples/Tests/ohm_solver_magnetic_reconnection/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/ohm_solver_magnetic_reconnection/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/ohm_solver_magnetic_reconnection/inputs_test_2d_ohm_solver_magnetic_reconnection_picmi.py b/Examples/Tests/ohm_solver_magnetic_reconnection/inputs_test_2d_ohm_solver_magnetic_reconnection_picmi.py index f074c81cbb3..2ddbd0df93d 100644 --- a/Examples/Tests/ohm_solver_magnetic_reconnection/inputs_test_2d_ohm_solver_magnetic_reconnection_picmi.py +++ b/Examples/Tests/ohm_solver_magnetic_reconnection/inputs_test_2d_ohm_solver_magnetic_reconnection_picmi.py @@ -83,14 +83,14 @@ def __init__(self, test, verbose): self.Bg *= self.B0 self.dB *= self.B0 self.Bx = ( - f"{self.B0}*tanh(z*{1.0/self.l_i})" - f"+{-self.dB*self.Lx/(2.0*self.Lz)}*cos({2.0*np.pi/self.Lx}*x)" - f"*sin({np.pi/self.Lz}*z)" + f"{self.B0}*tanh(z*{1.0 / self.l_i})" + f"+{-self.dB * self.Lx / (2.0 * self.Lz)}*cos({2.0 * np.pi / self.Lx}*x)" + f"*sin({np.pi / self.Lz}*z)" ) self.By = ( - f"sqrt({self.Bg**2 + self.B0**2}-" f"({self.B0}*tanh(z*{1.0/self.l_i}))**2)" + f"sqrt({self.Bg**2 + self.B0**2}-({self.B0}*tanh(z*{1.0 / self.l_i}))**2)" ) - self.Bz = f"{self.dB}*sin({2.0*np.pi/self.Lx}*x)*cos({np.pi/self.Lz}*z)" + self.Bz = f"{self.dB}*sin({2.0 * np.pi / self.Lx}*x)*cos({np.pi / self.Lz}*z)" self.J0 = self.B0 / constants.mu0 / self.l_i @@ -103,7 +103,7 @@ def __init__(self, test, verbose): if comm.rank == 0: print( f"Initializing simulation with input parameters:\n" - f"\tTi = {self.Ti*1e-3:.1f} keV\n" + f"\tTi = {self.Ti * 1e-3:.1f} keV\n" f"\tn0 = {self.n_plasma:.1e} m^-3\n" f"\tB0 = {self.B0:.2f} T\n" f"\tM/m = {self.m_ion:.0f}\n" @@ -117,7 +117,7 @@ def __init__(self, test, verbose): ) print( f"Numerical parameters:\n" - f"\tdz = {self.Lz/self.NZ:.1e} m\n" + f"\tdz = {self.Lz / self.NZ:.1e} m\n" f"\tdt = {self.dt:.1e} s\n" f"\tdiag steps = {self.diag_steps:d}\n" f"\ttotal steps = {self.total_steps:d}\n" diff --git a/Examples/Tests/open_bc_poisson_solver/CMakeLists.txt b/Examples/Tests/open_bc_poisson_solver/CMakeLists.txt index d6141f0b4ab..94fe240263c 100644 --- a/Examples/Tests/open_bc_poisson_solver/CMakeLists.txt +++ b/Examples/Tests/open_bc_poisson_solver/CMakeLists.txt @@ -7,20 +7,20 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_open_bc_poisson_solver # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000001 --rtol 1e-2" # checksum OFF # dependency ) endif() -if(WarpX_HEFFTE) +if(WarpX_FFT) add_warpx_test( - test_3d_open_bc_poisson_solver_heffte # name + test_3d_open_bc_poisson_solver_sliced # name 3 # dims 2 # nprocs - inputs_test_3d_open_bc_poisson_solver_heffte # inputs - analysis.py # analysis - diags/diag1000001 # output + inputs_test_3d_open_bc_poisson_solver_sliced # inputs + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1000001 --rtol 1e-2" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/open_bc_poisson_solver/analysis.py b/Examples/Tests/open_bc_poisson_solver/analysis.py index 8ffd9ef52e2..fda9da96cf6 100755 --- a/Examples/Tests/open_bc_poisson_solver/analysis.py +++ b/Examples/Tests/open_bc_poisson_solver/analysis.py @@ -1,16 +1,12 @@ #!/usr/bin/env python3 import os -import sys import numpy as np from openpmd_viewer import OpenPMDTimeSeries from scipy.constants import epsilon_0, pi from scipy.special import erf -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - sigmaz = 300e-6 sigmax = 516e-9 sigmay = 7.7e-9 @@ -60,11 +56,3 @@ def evaluate_E(x, y, z): assert np.allclose(Ex_warpx, Ex_theory, rtol=0.032, atol=0) assert np.allclose(Ey_warpx, Ey_theory, rtol=0.029, atol=0) - - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-2, -) diff --git a/Examples/Tests/open_bc_poisson_solver/analysis_default_regression.py b/Examples/Tests/open_bc_poisson_solver/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/open_bc_poisson_solver/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_heffte b/Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_sliced similarity index 55% rename from Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_heffte rename to Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_sliced index 4f0a50df037..e2639c59e74 100644 --- a/Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_heffte +++ b/Examples/Tests/open_bc_poisson_solver/inputs_test_3d_open_bc_poisson_solver_sliced @@ -1 +1,3 @@ FILE = inputs_test_3d_open_bc_poisson_solver + +warpx.use_2d_slices_fft_solver = 1 diff --git a/Examples/Tests/particle_boundary_interaction/CMakeLists.txt b/Examples/Tests/particle_boundary_interaction/CMakeLists.txt index 5bbb34c0d95..56739cf636b 100644 --- a/Examples/Tests/particle_boundary_interaction/CMakeLists.txt +++ b/Examples/Tests/particle_boundary_interaction/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_particle_boundary_interaction_picmi.py # inputs - analysis.py # analysis - diags/diag1/ # output + "analysis.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/particle_boundary_interaction/analysis.py b/Examples/Tests/particle_boundary_interaction/analysis.py index d06200157d2..2e8b57cb1e6 100755 --- a/Examples/Tests/particle_boundary_interaction/analysis.py +++ b/Examples/Tests/particle_boundary_interaction/analysis.py @@ -8,7 +8,6 @@ An input file inputs_test_rz_particle_boundary_interaction_picmi.py is used. """ -import os import sys import numpy as np @@ -16,8 +15,6 @@ from openpmd_viewer import OpenPMDTimeSeries yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Open plotfile specified in command line filename = sys.argv[1] @@ -32,27 +29,20 @@ z_analytic = -0.20531 print("NUMERICAL coordinates of the point of contact:") -print("x=%5.5f, y=%5.5f, z=%5.5f" % (x[0], y[0], z[0])) +print(f"x={x[0]:5.5f}, y={y[0]:5.5f}, z={z[0]:5.5f}") print("\n") print("ANALYTICAL coordinates of the point of contact:") -print("x=%5.5f, y=%5.5f, z=%5.5f" % (x_analytic, y_analytic, z_analytic)) +print(f"x={x_analytic:5.5f}, y={y_analytic:5.5f}, z={z_analytic:5.5f}") tolerance = 1e-5 -diff_x = np.abs((x[0] - x_analytic) / x_analytic) -diff_z = np.abs((z[0] - z_analytic) / z_analytic) +rel_err_x = np.abs((x[0] - x_analytic) / x_analytic) +rel_err_z = np.abs((z[0] - z_analytic) / z_analytic) print("\n") -print("percentage error for x = %5.4f %%" % (diff_x * 100)) -print("percentage error for z = %5.4f %%" % (diff_z * 100)) - -assert ( - (diff_x < tolerance) and (y[0] < 1e-8) and (diff_z < tolerance) -), "Test particle_boundary_interaction did not pass" - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", +print(f"Relative percentage error for x = {rel_err_x * 100:5.4f} %") +print(f"Relative percentage error for z = {rel_err_z * 100:5.4f} %") + +assert (rel_err_x < tolerance) and (y[0] < 1e-8) and (rel_err_z < tolerance), ( + "Test particle_boundary_interaction did not pass" ) diff --git a/Examples/Tests/particle_boundary_interaction/analysis_default_regression.py b/Examples/Tests/particle_boundary_interaction/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particle_boundary_interaction/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particle_boundary_interaction/inputs_test_rz_particle_boundary_interaction_picmi.py b/Examples/Tests/particle_boundary_interaction/inputs_test_rz_particle_boundary_interaction_picmi.py index 4b491ac6873..44eef4df0b9 100644 --- a/Examples/Tests/particle_boundary_interaction/inputs_test_rz_particle_boundary_interaction_picmi.py +++ b/Examples/Tests/particle_boundary_interaction/inputs_test_rz_particle_boundary_interaction_picmi.py @@ -128,20 +128,24 @@ def mirror_reflection(): # STEP 1: extract the different parameters of the boundary buffer (normal, time, position) lev = 0 # level 0 (no mesh refinement here) delta_t = concat( - buffer.get_particle_boundary_buffer("electrons", "eb", "deltaTimeScraped", lev) + buffer.get_particle_scraped_this_step( + "electrons", "eb", "deltaTimeScraped", lev + ) ) - r = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "x", lev)) - theta = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "theta", lev)) - z = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "z", lev)) + r = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "x", lev)) + theta = concat( + buffer.get_particle_scraped_this_step("electrons", "eb", "theta", lev) + ) + z = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "z", lev)) x = r * np.cos(theta) # from RZ coordinates to 3D coordinates y = r * np.sin(theta) - ux = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "ux", lev)) - uy = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "uy", lev)) - uz = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "uz", lev)) - w = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "w", lev)) - nx = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "nx", lev)) - ny = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "ny", lev)) - nz = concat(buffer.get_particle_boundary_buffer("electrons", "eb", "nz", lev)) + ux = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "ux", lev)) + uy = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "uy", lev)) + uz = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "uz", lev)) + w = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "w", lev)) + nx = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "nx", lev)) + ny = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "ny", lev)) + nz = concat(buffer.get_particle_scraped_this_step("electrons", "eb", "nz", lev)) # STEP 2: use these parameters to inject particle from the same position in the plasma elect_pc = particle_containers.ParticleContainerWrapper( @@ -164,8 +168,6 @@ def mirror_reflection(): ) # adds the particle in the general particle container at the next step #### Can be modified depending on the model of interaction. - buffer.clear_buffer() # reinitialise the boundary buffer - callbacks.installafterstep( mirror_reflection diff --git a/Examples/Tests/particle_boundary_process/CMakeLists.txt b/Examples/Tests/particle_boundary_process/CMakeLists.txt index 499cf445da5..d99121afea0 100644 --- a/Examples/Tests/particle_boundary_process/CMakeLists.txt +++ b/Examples/Tests/particle_boundary_process/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_particle_reflection_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -17,8 +17,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_particle_absorption # inputs - analysis_absorption.py # analysis - diags/diag1000060 # output + "analysis_absorption.py diags/diag1000060" # analysis + "analysis_default_regression.py --path diags/diag1000060" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/particle_boundary_process/analysis_absorption.py b/Examples/Tests/particle_boundary_process/analysis_absorption.py index 79e8d0e4bc6..498a456d871 100755 --- a/Examples/Tests/particle_boundary_process/analysis_absorption.py +++ b/Examples/Tests/particle_boundary_process/analysis_absorption.py @@ -6,14 +6,10 @@ # absence of the cube, none of the particles would have had time to exit # the problem domain yet. -import os import sys import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # all particles are still there ds40 = yt.load("diags/diag1000040") np40 = ds40.index.particle_headers["electrons"].num_particles @@ -24,9 +20,3 @@ ds60 = yt.load(filename) np60 = ds60.index.particle_headers["electrons"].num_particles assert np60 == 0 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/particle_boundary_scrape/CMakeLists.txt b/Examples/Tests/particle_boundary_scrape/CMakeLists.txt index 9b303afcc0f..5d2c52f30e0 100644 --- a/Examples/Tests/particle_boundary_scrape/CMakeLists.txt +++ b/Examples/Tests/particle_boundary_scrape/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_particle_scrape # inputs - analysis_scrape.py # analysis - diags/diag1000060 # output + "analysis_scrape.py diags/diag1000060" # analysis + "analysis_default_regression.py --path diags/diag1000060" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_particle_scrape_picmi.py # inputs - analysis_scrape.py # analysis - diags/diag1000060 # output + "analysis_scrape.py diags/diag1000060" # analysis + "analysis_default_regression.py --path diags/diag1000060" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/particle_boundary_scrape/analysis_default_regression.py b/Examples/Tests/particle_boundary_scrape/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particle_boundary_scrape/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particle_data_python/CMakeLists.txt b/Examples/Tests/particle_data_python/CMakeLists.txt index e58fe72670a..6bae89fd41b 100644 --- a/Examples/Tests/particle_data_python/CMakeLists.txt +++ b/Examples/Tests/particle_data_python/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_particle_attr_access_picmi.py # inputs - analysis.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs "inputs_test_2d_particle_attr_access_picmi.py --unique" # inputs - analysis.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_prev_positions_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) diff --git a/Examples/Tests/particle_data_python/analysis.py b/Examples/Tests/particle_data_python/analysis.py deleted file mode 100755 index 0b0cce3295b..00000000000 --- a/Examples/Tests/particle_data_python/analysis.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright 2021 Modern Electron -# -# License: BSD-3-Clause-LBNL - -# This script just checks that the PICMI file executed successfully. -# If it did there will be a plotfile for the final step. - -import sys - -step = int(sys.argv[1][-5:]) - -assert step == 10 diff --git a/Examples/Tests/particle_data_python/inputs_test_2d_particle_attr_access_picmi.py b/Examples/Tests/particle_data_python/inputs_test_2d_particle_attr_access_picmi.py index dbd29a43bc7..0d8c2ac209b 100755 --- a/Examples/Tests/particle_data_python/inputs_test_2d_particle_attr_access_picmi.py +++ b/Examples/Tests/particle_data_python/inputs_test_2d_particle_attr_access_picmi.py @@ -150,8 +150,8 @@ def add_particles(): ########################## assert elec_wrapper.nps == 270 / (2 - args.unique) -assert elec_wrapper.particle_container.get_comp_index("w") == 2 -assert elec_wrapper.particle_container.get_comp_index("newPid") == 6 +assert elec_wrapper.particle_container.get_real_comp_index("w") == 2 +assert elec_wrapper.particle_container.get_real_comp_index("newPid") == 6 new_pid_vals = elec_wrapper.get_particle_real_arrays("newPid", 0) for vals in new_pid_vals: diff --git a/Examples/Tests/particle_data_python/inputs_test_2d_prev_positions_picmi.py b/Examples/Tests/particle_data_python/inputs_test_2d_prev_positions_picmi.py index 2ad86ecea95..c15409edb0c 100755 --- a/Examples/Tests/particle_data_python/inputs_test_2d_prev_positions_picmi.py +++ b/Examples/Tests/particle_data_python/inputs_test_2d_prev_positions_picmi.py @@ -111,8 +111,8 @@ elec_count = elec_wrapper.nps # check that the runtime attributes have the right indices -assert elec_wrapper.particle_container.get_comp_index("prev_x") == 6 -assert elec_wrapper.particle_container.get_comp_index("prev_z") == 7 +assert elec_wrapper.particle_container.get_real_comp_index("prev_x") == 6 +assert elec_wrapper.particle_container.get_real_comp_index("prev_z") == 7 # sanity check that the prev_z values are reasonable and # that the correct number of values are returned diff --git a/Examples/Tests/particle_fields_diags/CMakeLists.txt b/Examples/Tests/particle_fields_diags/CMakeLists.txt index a83818b6966..414d303629a 100644 --- a/Examples/Tests/particle_fields_diags/CMakeLists.txt +++ b/Examples/Tests/particle_fields_diags/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_particle_fields_diags # inputs - analysis_particle_diags.py # analysis - diags/diag1000200 # output + "analysis_particle_diags.py diags/diag1000200" # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( # test_3d_particle_fields_diags_single_precision # name # 3 # dims # 2 # nprocs -## inputs_test_3d_particle_fields_diags # inputs -# analysis_particle_diags_single.py # analysis -# diags/diag1000200 # output +# inputs_test_3d_particle_fields_diags # inputs +# "analysis_particle_diags_single.py diags/diag1000200" # analysis +# "analysis_default_regression.py --path diags/diag1000200 --rtol 1e-3" # checksum # OFF # dependency #) diff --git a/Examples/Tests/particle_fields_diags/analysis_default_regression.py b/Examples/Tests/particle_fields_diags/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particle_fields_diags/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particle_fields_diags/analysis_particle_diags_impl.py b/Examples/Tests/particle_fields_diags/analysis_particle_diags_impl.py index 01a7436a787..f59e0aed8bf 100755 --- a/Examples/Tests/particle_fields_diags/analysis_particle_diags_impl.py +++ b/Examples/Tests/particle_fields_diags/analysis_particle_diags_impl.py @@ -11,7 +11,6 @@ # Various particle and field quantities are written to file using the reduced diagnostics # and compared with the corresponding quantities computed from the data in the plotfiles. -import os import sys import numpy as np @@ -19,9 +18,6 @@ import yt from scipy.constants import c, e, m_e, m_p -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - def do_analysis(single_precision=False): fn = sys.argv[1] @@ -228,8 +224,6 @@ def do_analysis(single_precision=False): error_plt = dict() error_opmd = dict() tolerance = 5e-3 if single_precision else 1e-12 - # if single precision, increase tolerance from default value - check_tolerance = 5e-3 if single_precision else 1e-9 for k in values_yt.keys(): # check that the zeros line up, since we'll be ignoring them in the error calculation @@ -247,10 +241,3 @@ def do_analysis(single_precision=False): ) assert error_opmd[k] < tolerance print(k, "relative error openPMD = ", error_opmd[k]) - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=check_tolerance, - ) diff --git a/Examples/Tests/particle_pusher/CMakeLists.txt b/Examples/Tests/particle_pusher/CMakeLists.txt index 3d8f1496587..cd414316b67 100644 --- a/Examples/Tests/particle_pusher/CMakeLists.txt +++ b/Examples/Tests/particle_pusher/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_particle_pusher # inputs - analysis.py # analysis - diags/diag1010000 # output + "analysis.py diags/diag1010000" # analysis + "analysis_default_regression.py --path diags/diag1010000" # checksum OFF # dependency ) diff --git a/Examples/Tests/particle_pusher/analysis.py b/Examples/Tests/particle_pusher/analysis.py index 9ed92507d4d..ae7b2054c28 100755 --- a/Examples/Tests/particle_pusher/analysis.py +++ b/Examples/Tests/particle_pusher/analysis.py @@ -22,14 +22,10 @@ # tolerance: 0.001 # Possible running time: ~ 4.0 s -import os import sys import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 0.001 filename = sys.argv[1] @@ -40,9 +36,3 @@ print("error = ", abs(x)) print("tolerance = ", tolerance) assert abs(x) < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/particle_pusher/analysis_default_regression.py b/Examples/Tests/particle_pusher/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particle_pusher/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particle_thermal_boundary/CMakeLists.txt b/Examples/Tests/particle_thermal_boundary/CMakeLists.txt index eeae6660e02..2f0cbba4ee6 100644 --- a/Examples/Tests/particle_thermal_boundary/CMakeLists.txt +++ b/Examples/Tests/particle_thermal_boundary/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_particle_thermal_boundary # inputs - analysis.py # analysis - diags/diag1002000 # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1002000" # checksum OFF # dependency ) diff --git a/Examples/Tests/particle_thermal_boundary/analysis.py b/Examples/Tests/particle_thermal_boundary/analysis.py index 621bf2032be..81f8a73b474 100755 --- a/Examples/Tests/particle_thermal_boundary/analysis.py +++ b/Examples/Tests/particle_thermal_boundary/analysis.py @@ -14,14 +14,8 @@ beyond 2% in the time that it takes all particles to cross the domain boundary """ -import os -import sys - import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - FE_rdiag = "./diags/reducedfiles/EF.txt" init_Fenergy = np.loadtxt(FE_rdiag)[1, 2] final_Fenergy = np.loadtxt(FE_rdiag)[-1, 2] @@ -32,9 +26,3 @@ init_Penergy = np.loadtxt(PE_rdiag)[0, 2] final_Penergy = np.loadtxt(PE_rdiag)[-1, 2] assert abs(final_Penergy - init_Penergy) / init_Penergy < 0.02 - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/particle_thermal_boundary/analysis_default_regression.py b/Examples/Tests/particle_thermal_boundary/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particle_thermal_boundary/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particles_in_pml/CMakeLists.txt b/Examples/Tests/particles_in_pml/CMakeLists.txt index fb539461ec2..4f150c6d4e4 100644 --- a/Examples/Tests/particles_in_pml/CMakeLists.txt +++ b/Examples/Tests/particles_in_pml/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_particles_in_pml # inputs - analysis_particles_in_pml.py # analysis - diags/diag1000180 # output + "analysis_particles_in_pml.py diags/diag1000180" # analysis + "analysis_default_regression.py --path diags/diag1000180" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_particles_in_pml_mr # inputs - analysis_particles_in_pml.py # analysis - diags/diag1000300 # output + "analysis_particles_in_pml.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_particles_in_pml # inputs - analysis_particles_in_pml.py # analysis - diags/diag1000120 # output + "analysis_particles_in_pml.py diags/diag1000120" # analysis + "analysis_default_regression.py --path diags/diag1000120" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_particles_in_pml_mr # inputs - analysis_particles_in_pml.py # analysis - diags/diag1000200 # output + "analysis_particles_in_pml.py diags/diag1000200" # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) label_warpx_test(test_3d_particles_in_pml_mr slow) diff --git a/Examples/Tests/particles_in_pml/analysis_default_regression.py b/Examples/Tests/particles_in_pml/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/particles_in_pml/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/particles_in_pml/analysis_particles_in_pml.py b/Examples/Tests/particles_in_pml/analysis_particles_in_pml.py index 8e7d95eda08..63ef4c7d2ff 100755 --- a/Examples/Tests/particles_in_pml/analysis_particles_in_pml.py +++ b/Examples/Tests/particles_in_pml/analysis_particles_in_pml.py @@ -18,14 +18,11 @@ charge, with associated fields, behind them. """ -import os import sys import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Open plotfile specified in command line filename = sys.argv[1] @@ -66,9 +63,3 @@ print("tolerance_abs: " + str(tolerance_abs)) assert max_Efield < tolerance_abs - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pass_mpi_communicator/CMakeLists.txt b/Examples/Tests/pass_mpi_communicator/CMakeLists.txt index ac60636b931..4f5a8b4965c 100644 --- a/Examples/Tests/pass_mpi_communicator/CMakeLists.txt +++ b/Examples/Tests/pass_mpi_communicator/CMakeLists.txt @@ -10,7 +10,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_pass_mpi_comm_picmi.py # inputs - OFF #analysis.py # analysis - OFF # output + OFF # analysis + OFF # checksum OFF # dependency ) diff --git a/Examples/Tests/pass_mpi_communicator/analysis.py b/Examples/Tests/pass_mpi_communicator/analysis.py index 041687c4775..cfac572c1b9 100755 --- a/Examples/Tests/pass_mpi_communicator/analysis.py +++ b/Examples/Tests/pass_mpi_communicator/analysis.py @@ -37,7 +37,7 @@ # Dictionaries have same outer keys (levels, species)? if checksum1.data.keys() != checksum2.data.keys(): - print("ERROR: plotfile 1 and plotfile 2 checksums " "have different outer keys:") + print("ERROR: plotfile 1 and plotfile 2 checksums have different outer keys:") print("Plot1: %s" % checksum1.data.keys()) print("Plot2: %s" % checksum2.data.keys()) sys.exit(1) @@ -45,9 +45,7 @@ # Dictionaries have same inner keys (field and particle quantities)? for key1 in checksum1.data.keys(): if checksum1.data[key1].keys() != checksum2.data[key1].keys(): - print( - "ERROR: plotfile 1 and plotfile 2 checksums have " "different inner keys:" - ) + print("ERROR: plotfile 1 and plotfile 2 checksums have different inner keys:") print("Common outer keys: %s" % checksum2.data.keys()) print("Plotfile 1 inner keys in %s: %s" % (key1, checksum1.data[key1].keys())) print("Plotfile 2 inner keys in %s: %s" % (key1, checksum2.data[key1].keys())) diff --git a/Examples/Tests/pass_mpi_communicator/analysis_default_regression.py b/Examples/Tests/pass_mpi_communicator/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/pass_mpi_communicator/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/pec/CMakeLists.txt b/Examples/Tests/pec/CMakeLists.txt index ec710f7d919..15aa17c2d5f 100644 --- a/Examples/Tests/pec/CMakeLists.txt +++ b/Examples/Tests/pec/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_pec_field # inputs - analysis_pec.py # analysis - diags/diag1000125 # output + "analysis_pec.py diags/diag1000125" # analysis + "analysis_default_regression.py --path diags/diag1000125" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_pec_field_mr # inputs - analysis_pec_mr.py # analysis - diags/diag1000125 # output + "analysis_pec_mr.py diags/diag1000125" # analysis + "analysis_default_regression.py --path diags/diag1000125" # checksum OFF # dependency ) @@ -26,7 +26,47 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_pec_particle # inputs - analysis_default_regression.py # analysis - diags/diag1000020 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum OFF # dependency ) + +add_warpx_test( + test_2d_pec_field_insulator # name + 2 # dims + 2 # nprocs + inputs_test_2d_pec_field_insulator # inputs + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum + OFF # dependency +) + +add_warpx_test( + test_3d_pmc_field # name + 3 # dims + 2 # nprocs + inputs_test_3d_pmc_field # inputs + "analysis_pec.py diags/diag1000134" # analysis + "analysis_default_regression.py --path diags/diag1000134" # checksum + OFF # dependency +) + +add_warpx_test( + test_2d_pec_field_insulator_implicit # name + 2 # dims + 2 # nprocs + inputs_test_2d_pec_field_insulator_implicit # inputs + "analysis_pec_insulator_implicit.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum + OFF # dependency +) + +add_warpx_test( + test_2d_pec_field_insulator_implicit_restart # name + 2 # dims + 2 # nprocs + inputs_test_2d_pec_field_insulator_implicit_restart # inputs + "analysis_pec_insulator_implicit.py diags/diag1000020" # analysis + "analysis_default_regression.py --path diags/diag1000020" # checksum + test_2d_pec_field_insulator_implicit # dependency +) diff --git a/Examples/Tests/pec/analysis_pec.py b/Examples/Tests/pec/analysis_pec.py index 29d9a4e26f4..251a17e017c 100755 --- a/Examples/Tests/pec/analysis_pec.py +++ b/Examples/Tests/pec/analysis_pec.py @@ -11,7 +11,6 @@ # The electric field (Ey) is a standing wave due to the PEC boundary condition, # and as a result, the minimum and maximum value after reflection would be two times the value at initialization due to constructive interference. # Additionally, the value of Ey at the boundary must be equal to zero. -import os import sys import matplotlib @@ -24,9 +23,6 @@ import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -89,9 +85,3 @@ assert max_Ey_error_rel < tolerance_rel assert min_Ey_error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pec/analysis_pec_insulator_implicit.py b/Examples/Tests/pec/analysis_pec_insulator_implicit.py new file mode 100755 index 00000000000..1fdbc2261a8 --- /dev/null +++ b/Examples/Tests/pec/analysis_pec_insulator_implicit.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +# +# +# This file is part of WarpX. +# +# License: BSD-3-Clause-LBNL +# +# This is a script that analyses the simulation results from +# the scripts `inputs_test_2d_pec_field_insulator_implicit` and +# `inputs_test_2d_pec_field_insulator_implicit_restart`. +# The scripts model an insulator boundary condition on part of the +# upper x boundary that pushes B field into the domain. The implicit +# solver is used, converging to machine tolerance. The energy accounting +# should be exact to machine precision, so that the energy is the system +# should be the same as the amount of energy pushed in from the boundary. +# This is checked using the FieldEnergy and FieldPoyntingFlux reduced +# diagnostics. +import sys + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np + +# this will be the name of the plot file +fn = sys.argv[1] + +EE = np.loadtxt(f"{fn}/../reducedfiles/fieldenergy.txt", skiprows=1) +SS = np.loadtxt(f"{fn}/../reducedfiles/poyntingflux.txt", skiprows=1) +SSsum = SS[:, 2:6].sum(1) +EEloss = SS[:, 7:].sum(1) + +dt = EE[1, 1] + +fig, ax = plt.subplots() +ax.plot(EE[:, 0], EE[:, 2], label="field energy") +ax.plot(SS[:, 0], -EEloss, label="-flux*dt") +ax.legend() +ax.set_xlabel("time (s)") +ax.set_ylabel("energy (J)") +fig.savefig("energy_history.png") + +fig, ax = plt.subplots() +ax.plot(EE[:, 0], (EE[:, 2] + EEloss) / EE[:, 2].max()) +ax.set_xlabel("time (s)") +ax.set_ylabel("energy difference/max energy (1)") +fig.savefig("energy_difference.png") + +tolerance_rel = 1.0e-13 + +energy_difference_fraction = np.abs((EE[:, 2] + EEloss) / EE[:, 2].max()).max() +print(f"energy accounting error = {energy_difference_fraction}") +print(f"tolerance_rel = {tolerance_rel}") + +assert energy_difference_fraction < tolerance_rel diff --git a/Examples/Tests/pec/analysis_pec_mr.py b/Examples/Tests/pec/analysis_pec_mr.py index 069a1d01afa..a99c4b0bafb 100755 --- a/Examples/Tests/pec/analysis_pec_mr.py +++ b/Examples/Tests/pec/analysis_pec_mr.py @@ -11,7 +11,6 @@ # The electric field (Ey) is a standing wave due to the PEC boundary condition, # and as a result, the minimum and maximum value after reflection would be two times the value at initialization due to constructive interference. # Additionally, the value of Ey at the boundary must be equal to zero. -import os import sys import matplotlib @@ -24,9 +23,6 @@ import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # this will be the name of the plot file fn = sys.argv[1] @@ -89,9 +85,3 @@ assert max_Ey_error_rel < tolerance_rel assert min_Ey_error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pec/inputs_test_2d_pec_field_insulator b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator new file mode 100644 index 00000000000..912b77efcf6 --- /dev/null +++ b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator @@ -0,0 +1,34 @@ +# Maximum number of time steps +max_step = 10 + +# number of grid points +amr.n_cell = 32 32 +amr.blocking_factor = 16 + +# Maximum level in hierarchy (for now must be 0, i.e., one level in total) +amr.max_level = 0 + +# Geometry +geometry.dims = 2 +geometry.prob_lo = 0. 2.e-2 # physical domain +geometry.prob_hi = 1.e-2 3.e-2 + +# Boundary condition +boundary.field_lo = neumann periodic +boundary.field_hi = pec_insulator periodic + +warpx.serialize_initial_conditions = 1 + +# Verbosity +warpx.verbose = 1 + +# CFL +warpx.cfl = 1.0 + +insulator.area_x_hi(y,z) = (2.25e-2 <= z and z <= 2.75e-2) +insulator.By_x_hi(y,z,t) = min(t/1.0e-12,1)*1.e1*3.3e-4 + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 10 +diag1.diag_type = Full diff --git a/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit new file mode 100644 index 00000000000..ec61e3f8605 --- /dev/null +++ b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit @@ -0,0 +1,73 @@ +# Maximum number of time steps +max_step = 20 + +# number of grid points +amr.n_cell = 32 32 +amr.blocking_factor = 16 + +# Maximum level in hierarchy (for now must be 0, i.e., one level in total) +amr.max_level = 0 + +# Geometry +geometry.dims = 2 +geometry.prob_lo = 0. 2.e-2 # physical domain +geometry.prob_hi = 1.e-2 3.e-2 + +# Boundary condition +boundary.field_lo = neumann periodic +boundary.field_hi = pec_insulator periodic + +insulator.area_x_hi(y,z) = (2.25e-2 <= z and z <= 2.75e-2) +insulator.By_x_hi(y,z,t) = min(t/1.0e-12,1)*1.e1*3.3e-4 + +warpx.serialize_initial_conditions = 1 + +# Implicit setup +# Note that this is the CFL step size for the explicit simulation, over 2. +# This value allows quick convergence of the Picard solver. +warpx.const_dt = 7.37079480234276e-13/2. + +algo.maxwell_solver = Yee +algo.evolve_scheme = "theta_implicit_em" +#algo.evolve_scheme = "semi_implicit_em" + +implicit_evolve.theta = 0.5 +#implicit_evolve.max_particle_iterations = 21 +#implicit_evolve.particle_tolerance = 1.0e-12 + +implicit_evolve.nonlinear_solver = "picard" +picard.verbose = true +picard.max_iterations = 25 +picard.relative_tolerance = 0.0 +picard.absolute_tolerance = 0.0 +picard.require_convergence = false + +#implicit_evolve.nonlinear_solver = "newton" +#newton.verbose = true +#newton.max_iterations = 20 +#newton.relative_tolerance = 1.0e-20 +#newton.absolute_tolerance = 0.0 +#newton.require_convergence = false + +#gmres.verbose_int = 2 +#gmres.max_iterations = 1000 +#gmres.relative_tolerance = 1.0e-20 +#gmres.absolute_tolerance = 0.0 + +# Verbosity +warpx.verbose = 1 + +# Diagnostics +diagnostics.diags_names = diag1 chk +diag1.intervals = 20 +diag1.diag_type = Full + +chk.intervals = 10 +chk.diag_type = Full +chk.format = checkpoint + +warpx.reduced_diags_names = fieldenergy poyntingflux +poyntingflux.type = FieldPoyntingFlux +poyntingflux.intervals = 1 +fieldenergy.type = FieldEnergy +fieldenergy.intervals = 1 diff --git a/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit_restart b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit_restart new file mode 100644 index 00000000000..35b78d01acd --- /dev/null +++ b/Examples/Tests/pec/inputs_test_2d_pec_field_insulator_implicit_restart @@ -0,0 +1,5 @@ +# base input parameters +FILE = inputs_test_2d_pec_field_insulator_implicit + +# test input parameters +amr.restart = "../test_2d_pec_field_insulator_implicit/diags/chk000010" diff --git a/Examples/Tests/pec/inputs_test_3d_pmc_field b/Examples/Tests/pec/inputs_test_3d_pmc_field new file mode 100644 index 00000000000..2fc1cb9e5ab --- /dev/null +++ b/Examples/Tests/pec/inputs_test_3d_pmc_field @@ -0,0 +1,54 @@ +# Set-up to test the PMC Boundary condition for the fields +# Constructive interference between the incident and reflected wave result in a +# standing wave. + +# max step +max_step = 134 + +# number of grid points +amr.n_cell = 32 32 256 + +# Maximum allowable size of each subdomain +amr.max_grid_size = 1024 +amr.blocking_factor = 32 + +amr.max_level = 0 + +# Geometry +geometry.dims = 3 +geometry.prob_lo = -8.e-6 -8.e-6 -4.e-6 +geometry.prob_hi = 8.e-6 8.e-6 4.e-6 + +# Boundary condition +boundary.field_lo = periodic periodic pmc +boundary.field_hi = periodic periodic pmc + +warpx.serialize_initial_conditions = 1 + +# Verbosity +warpx.verbose = 1 + +# Algorithms +algo.current_deposition = esirkepov +# CFL +warpx.cfl = 0.9 + + +my_constants.z1 = -2.e-6 +my_constants.z2 = 2.e-6 +my_constants.wavelength = 1.e-6 +warpx.E_ext_grid_init_style = parse_E_ext_grid_function +warpx.Ez_external_grid_function(x,y,z) = "0." +warpx.Ex_external_grid_function(x,y,z) = "0." +warpx.Ey_external_grid_function(x,y,z) = "((1.e5*sin(2*pi*(z)/wavelength)) * (zz1))" + +warpx.B_ext_grid_init_style = parse_B_ext_grid_function +warpx.Bx_external_grid_function(x,y,z)= "(((-1.e5*sin(2*pi*(z)/wavelength))/clight))*(zz1) " +warpx.By_external_grid_function(x,y,z)= "0." +warpx.Bz_external_grid_function(x,y,z) = "0." + +# Diagnostics +diagnostics.diags_names = diag1 +diag1.intervals = 134 +diag1.diag_type = Full +diag1.fields_to_plot = Ey Bx diff --git a/Examples/Tests/photon_pusher/CMakeLists.txt b/Examples/Tests/photon_pusher/CMakeLists.txt index 7926d8faeaf..78bc1d0b416 100644 --- a/Examples/Tests/photon_pusher/CMakeLists.txt +++ b/Examples/Tests/photon_pusher/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_photon_pusher # inputs - analysis.py # analysis - diags/diag1000050 # output + "analysis.py diags/diag1000050" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) diff --git a/Examples/Tests/photon_pusher/analysis.py b/Examples/Tests/photon_pusher/analysis.py index 2a77e325bc5..e2ccfc42656 100755 --- a/Examples/Tests/photon_pusher/analysis.py +++ b/Examples/Tests/photon_pusher/analysis.py @@ -7,15 +7,11 @@ # # License: BSD-3-Clause-LBNL -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # This script checks if photons initialized with different momenta and # different initial directions propagate along straight lines at the speed of # light. The plotfile to be analyzed is passed as a command line argument. @@ -153,12 +149,6 @@ def check(): assert (max(disc_pos) <= tol_pos) and (max(disc_mom) <= tol_mom) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - # This function generates the input file to test the photon pusher. def generate(): diff --git a/Examples/Tests/photon_pusher/analysis_default_regression.py b/Examples/Tests/photon_pusher/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/photon_pusher/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/plasma_lens/CMakeLists.txt b/Examples/Tests/plasma_lens/CMakeLists.txt index bc13ae433bc..f6d6ea6daeb 100644 --- a/Examples/Tests/plasma_lens/CMakeLists.txt +++ b/Examples/Tests/plasma_lens/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_lens # inputs - analysis.py # analysis - diags/diag1000084 # output + "analysis.py diags/diag1000084" # analysis + "analysis_default_regression.py --path diags/diag1000084" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_lens_boosted # inputs - analysis.py # analysis - diags/diag1000084 # output + "analysis.py diags/diag1000084" # analysis + "analysis_default_regression.py --path diags/diag1000084" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_lens_hard_edged # inputs - analysis.py # analysis - diags/diag1000084 # output + "analysis.py diags/diag1000084" # analysis + "analysis_default_regression.py --path diags/diag1000084" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_lens_picmi.py # inputs - analysis.py # analysis - diags/diag1000084 # output + "analysis.py diags/diag1000084" # analysis + "analysis_default_regression.py --path diags/diag1000084" # checksum OFF # dependency ) @@ -46,7 +46,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_plasma_lens_short # inputs - analysis.py # analysis - diags/diag1000084 # output + "analysis.py diags/diag1000084" # analysis + "analysis_default_regression.py --path diags/diag1000084" # checksum OFF # dependency ) diff --git a/Examples/Tests/plasma_lens/analysis.py b/Examples/Tests/plasma_lens/analysis.py index 46036573940..ed7ee653af6 100755 --- a/Examples/Tests/plasma_lens/analysis.py +++ b/Examples/Tests/plasma_lens/analysis.py @@ -15,8 +15,6 @@ The motion is slow enough that relativistic effects are ignored. """ -import os -import re import sys import numpy as np @@ -24,8 +22,6 @@ from scipy.constants import c, e, m_e yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] ds = yt.load(filename) @@ -164,13 +160,17 @@ def applylens(x0, vx0, vz0, gamma, lens_length, lens_strength): xx = xx + dt0 * vx yy = yy + dt1 * vy -print(f"Error in x position is {abs(np.abs((xx - xx_sim)/xx))}, which should be < 0.02") -print(f"Error in y position is {abs(np.abs((yy - yy_sim)/yy))}, which should be < 0.02") print( - f"Error in x velocity is {abs(np.abs((ux - ux_sim)/ux))}, which should be < 0.002" + f"Error in x position is {abs(np.abs((xx - xx_sim) / xx))}, which should be < 0.02" ) print( - f"Error in y velocity is {abs(np.abs((uy - uy_sim)/uy))}, which should be < 0.002" + f"Error in y position is {abs(np.abs((yy - yy_sim) / yy))}, which should be < 0.02" +) +print( + f"Error in x velocity is {abs(np.abs((ux - ux_sim) / ux))}, which should be < 0.002" +) +print( + f"Error in y velocity is {abs(np.abs((uy - uy_sim) / uy))}, which should be < 0.002" ) if plasma_lens_lengths[0] < 0.01: @@ -194,11 +194,3 @@ def applylens(x0, vx0, vz0, gamma, lens_length, lens_strength): assert abs(np.abs((uy - uy_sim) / uy)) < velocity_tolerance, Exception( "error in y particle velocity" ) - -# compare checksums -test_name = os.path.split(os.getcwd())[1] -test_name = re.sub("_picmi", "", test_name) # same checksums for PICMI test -evaluate_checksum( - test_name=test_name, - output_file=sys.argv[1], -) diff --git a/Examples/Tests/plasma_lens/analysis_default_regression.py b/Examples/Tests/plasma_lens/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/plasma_lens/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/pml/CMakeLists.txt b/Examples/Tests/pml/CMakeLists.txt index c63412dc763..8ba70f77aef 100644 --- a/Examples/Tests/pml/CMakeLists.txt +++ b/Examples/Tests/pml/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_pml_x_ckc # inputs - analysis_pml_ckc.py # analysis - diags/diag1000300 # output + "analysis_pml_ckc.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -17,8 +17,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_pml_x_galilean # inputs - analysis_pml_psatd.py # analysis - diags/diag1000300 # output + "analysis_pml_psatd.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) endif() @@ -29,8 +29,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_pml_x_psatd # inputs - analysis_pml_psatd.py # analysis - diags/diag1000300 # output + "analysis_pml_psatd.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) endif() @@ -41,8 +41,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_pml_x_psatd_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000300 # output + "analysis_default_restart.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum test_2d_pml_x_psatd # dependency ) endif() @@ -52,8 +52,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_pml_x_yee # inputs - analysis_pml_yee.py # analysis - diags/diag1000300 # output + "analysis_pml_yee.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum OFF # dependency ) @@ -62,8 +62,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_pml_x_yee_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000300 # output + "analysis_default_restart.py diags/diag1000300" # analysis + "analysis_default_regression.py --path diags/diag1000300" # checksum test_2d_pml_x_yee # dependency ) @@ -73,8 +73,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_pml_psatd_dive_divb_cleaning # inputs - analysis_default_regression.py # analysis - diags/diag1000100 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) endif() @@ -85,8 +85,8 @@ if(WarpX_FFT) RZ # dims 2 # nprocs inputs_test_rz_pml_psatd # inputs - analysis_pml_psatd_rz.py # analysis - diags/diag1000500 # output + "analysis_pml_psatd_rz.py diags/diag1000500" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/pml/analysis_pml_ckc.py b/Examples/Tests/pml/analysis_pml_ckc.py index f6637e2d47b..b50cbb867e6 100755 --- a/Examples/Tests/pml/analysis_pml_ckc.py +++ b/Examples/Tests/pml/analysis_pml_ckc.py @@ -8,7 +8,6 @@ # License: BSD-3-Clause-LBNL -import os import sys import numpy as np @@ -16,8 +15,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -56,9 +53,3 @@ print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pml/analysis_pml_psatd.py b/Examples/Tests/pml/analysis_pml_psatd.py index 4f44c0f3432..156f58362ce 100755 --- a/Examples/Tests/pml/analysis_pml_psatd.py +++ b/Examples/Tests/pml/analysis_pml_psatd.py @@ -16,8 +16,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -74,9 +72,3 @@ print("reflectivity_max = " + str(reflectivity_max)) assert reflectivity < reflectivity_max - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pml/analysis_pml_psatd_rz.py b/Examples/Tests/pml/analysis_pml_psatd_rz.py index fb662e36d40..f06b7a52c6c 100755 --- a/Examples/Tests/pml/analysis_pml_psatd_rz.py +++ b/Examples/Tests/pml/analysis_pml_psatd_rz.py @@ -16,15 +16,12 @@ the pulse will remain with in the domain. """ -import os import sys import numpy as np import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Open plotfile specified in command line filename = sys.argv[1] @@ -54,9 +51,3 @@ tolerance_abs = 2.0 print("tolerance_abs: " + str(tolerance_abs)) assert max_Efield < tolerance_abs - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/pml/analysis_pml_yee.py b/Examples/Tests/pml/analysis_pml_yee.py index 5f6d21e579c..b6aad4ccb7e 100755 --- a/Examples/Tests/pml/analysis_pml_yee.py +++ b/Examples/Tests/pml/analysis_pml_yee.py @@ -8,7 +8,6 @@ # License: BSD-3-Clause-LBNL -import os import sys import numpy as np @@ -16,8 +15,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -56,9 +53,3 @@ print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/point_of_contact_eb/CMakeLists.txt b/Examples/Tests/point_of_contact_eb/CMakeLists.txt index b8d7ba1131f..700eba6f92f 100644 --- a/Examples/Tests/point_of_contact_eb/CMakeLists.txt +++ b/Examples/Tests/point_of_contact_eb/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 2 # nprocs inputs_test_3d_point_of_contact_eb # inputs - analysis.py # analysis - diags/diag1/ # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_point_of_contact_eb # inputs - analysis.py # analysis - diags/diag1/ # output + "analysis.py" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/point_of_contact_eb/analysis.py b/Examples/Tests/point_of_contact_eb/analysis.py index 1c9dbc85f4c..55a65f2cee3 100755 --- a/Examples/Tests/point_of_contact_eb/analysis.py +++ b/Examples/Tests/point_of_contact_eb/analysis.py @@ -8,16 +8,11 @@ An input file inputs_test_3d_point_of_contact_eb is used. """ -import os -import sys - import numpy as np import yt from openpmd_viewer import OpenPMDTimeSeries yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum ts_scraping = OpenPMDTimeSeries("./diags/diag2/particles_at_eb/") @@ -92,10 +87,3 @@ and (diff_ny < tolerance_n) and (np.abs(nz) < 1e-8) ), "Test point_of_contact did not pass" - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - output_format="openpmd", -) diff --git a/Examples/Tests/point_of_contact_eb/analysis_default_regression.py b/Examples/Tests/point_of_contact_eb/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/point_of_contact_eb/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/projection_divb_cleaner/CMakeLists.txt b/Examples/Tests/projection_divb_cleaner/CMakeLists.txt index 307ae7656c5..40b84bd0397 100644 --- a/Examples/Tests/projection_divb_cleaner/CMakeLists.txt +++ b/Examples/Tests/projection_divb_cleaner/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_projection_divb_cleaner_callback_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 1 # nprocs inputs_test_3d_projection_divb_cleaner_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000001 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( RZ # dims 1 # nprocs inputs_test_rz_projection_divb_cleaner # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/projection_divb_cleaner/analysis.py b/Examples/Tests/projection_divb_cleaner/analysis.py index 2324c370032..5db145eba7e 100755 --- a/Examples/Tests/projection_divb_cleaner/analysis.py +++ b/Examples/Tests/projection_divb_cleaner/analysis.py @@ -16,15 +16,11 @@ # tolerance: 1.0e-8 # Possible running time: 0.327827743 s -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 4e-3 filename = sys.argv[1] @@ -72,9 +68,3 @@ print("error = ", error) print("tolerance = ", tolerance) assert error < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/python_wrappers/CMakeLists.txt b/Examples/Tests/python_wrappers/CMakeLists.txt index 0045a181606..060cdd7c183 100644 --- a/Examples/Tests/python_wrappers/CMakeLists.txt +++ b/Examples/Tests/python_wrappers/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_python_wrappers_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000100 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000100" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/qed/CMakeLists.txt b/Examples/Tests/qed/CMakeLists.txt index 5dd786f26a1..d38c2e4fc69 100644 --- a/Examples/Tests/qed/CMakeLists.txt +++ b/Examples/Tests/qed/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_qed_breit_wheeler # inputs - analysis_breit_wheeler_yt.py # analysis - diags/diag1000002 # output + "analysis_breit_wheeler_yt.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_qed_breit_wheeler_opmd # inputs - analysis_breit_wheeler_opmd.py # analysis - diags/diag1/ # output + "analysis_breit_wheeler_opmd.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_qed_quantum_sync # inputs - analysis_quantum_sync.py # analysis - diags/diag1000002 # output + "analysis_quantum_sync.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_breit_wheeler # inputs - analysis_breit_wheeler_yt.py # analysis - diags/diag1000002 # output + "analysis_breit_wheeler_yt.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -46,8 +46,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_breit_wheeler_opmd # inputs - analysis_breit_wheeler_opmd.py # analysis - diags/diag1/ # output + "analysis_breit_wheeler_opmd.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum OFF # dependency ) @@ -56,8 +56,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_quantum_sync # inputs - analysis_quantum_sync.py # analysis - diags/diag1000002 # output + "analysis_quantum_sync.py diags/diag1000002" # analysis + "analysis_default_regression.py --path diags/diag1000002" # checksum OFF # dependency ) @@ -66,8 +66,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_schwinger_1 # inputs - analysis_schwinger.py # analysis - diags/diag1000001 # output + "analysis_schwinger.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -76,8 +76,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_schwinger_2 # inputs - analysis_schwinger.py # analysis - diags/diag1000001 # output + "analysis_schwinger.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -86,8 +86,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_schwinger_3 # inputs - analysis_schwinger.py # analysis - diags/diag1000001 # output + "analysis_schwinger.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -96,7 +96,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_qed_schwinger_4 # inputs - analysis_schwinger.py # analysis - diags/diag1000001 # output + "analysis_schwinger.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/qed/analysis_breit_wheeler_opmd.py b/Examples/Tests/qed/analysis_breit_wheeler_opmd.py index b88f00a85dc..1803305f008 100755 --- a/Examples/Tests/qed/analysis_breit_wheeler_opmd.py +++ b/Examples/Tests/qed/analysis_breit_wheeler_opmd.py @@ -12,10 +12,6 @@ import analysis_breit_wheeler_core as ac import openpmd_api as io -# sys.path.insert(1, '../../../../warpx/Regression/Checksum/') -# from checksumAPI import evaluate_checksum - - # This script is a frontend for the analysis routines # in analysis_breit_wheeler_core.py (please refer to this file for # a full description). It reads output files in openPMD @@ -72,13 +68,6 @@ def main(): ac.check(dt, particle_data) - # compare checksums - # evaluate_checksum( - # test_name=os.path.split(os.getcwd())[1], - # output_file=sys.argv[1], - # output_format="openpmd", - # ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/qed/analysis_breit_wheeler_yt.py b/Examples/Tests/qed/analysis_breit_wheeler_yt.py index 48c45c990b0..bd8f4454723 100755 --- a/Examples/Tests/qed/analysis_breit_wheeler_yt.py +++ b/Examples/Tests/qed/analysis_breit_wheeler_yt.py @@ -7,14 +7,10 @@ # -*- coding: utf-8 -*- -import os import sys -import yt - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") import analysis_breit_wheeler_core as ac -from checksumAPI import evaluate_checksum +import yt # This script is a frontend for the analysis routines # in analysis_breit_wheeler_core.py (please refer to this file for @@ -58,12 +54,6 @@ def main(): ac.check(dt, particle_data) - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - if __name__ == "__main__": main() diff --git a/Examples/Tests/qed/analysis_default_regression.py b/Examples/Tests/qed/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/qed/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/qed/analysis_quantum_sync.py b/Examples/Tests/qed/analysis_quantum_sync.py index 531a0eac195..e4ede19260c 100755 --- a/Examples/Tests/qed/analysis_quantum_sync.py +++ b/Examples/Tests/qed/analysis_quantum_sync.py @@ -8,19 +8,15 @@ # -*- coding: utf-8 -*- -import os import sys +import matplotlib.pyplot as plt import numpy as np import scipy.integrate as integ import scipy.special as spe import scipy.stats as st import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -import matplotlib.pyplot as plt -from checksumAPI import evaluate_checksum - # This script performs detailed checks of the Quantum Synchrotron photon emission process. # Two electron populations and two positron populations are initialized with different momenta in different # directions in a background EM field (with non-zero components along each direction). @@ -348,12 +344,6 @@ def check(): print("*************\n") - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - def main(): check() diff --git a/Examples/Tests/qed/analysis_schwinger.py b/Examples/Tests/qed/analysis_schwinger.py index 4ad21e3d518..5d1c5485ba3 100755 --- a/Examples/Tests/qed/analysis_schwinger.py +++ b/Examples/Tests/qed/analysis_schwinger.py @@ -18,9 +18,6 @@ import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # define some parameters c = 299792458.0 @@ -160,9 +157,3 @@ def do_analysis(Ex, Ey, Ez, Bx, By, Bz): do_analysis(Ex_test, Ey_test, Ez_test, Bx_test, By_test, Bz_test) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/radiation_reaction/CMakeLists.txt b/Examples/Tests/radiation_reaction/CMakeLists.txt index 8696cf0f9b7..3286f4efd93 100644 --- a/Examples/Tests/radiation_reaction/CMakeLists.txt +++ b/Examples/Tests/radiation_reaction/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_radiation_reaction # inputs - analysis.py # analysis - diags/diag1000064 # output + "analysis.py diags/diag1000064" # analysis + "analysis_default_regression.py --path diags/diag1000064" # checksum OFF # dependency ) diff --git a/Examples/Tests/radiation_reaction/analysis.py b/Examples/Tests/radiation_reaction/analysis.py index 74155a89cb3..0d4fcf12e8e 100755 --- a/Examples/Tests/radiation_reaction/analysis.py +++ b/Examples/Tests/radiation_reaction/analysis.py @@ -30,15 +30,11 @@ # 3) H. Spohn, Dynamics of charged particles and their radiation field # (Cambridge University Press, Cambridge, 2004) -import os import sys import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Input filename inputname = "inputs" # ________________________________________ @@ -163,12 +159,6 @@ def check(): assert error_rel < tolerance_rel - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - ) - def generate(): with open(inputname, "w") as f: diff --git a/Examples/Tests/radiation_reaction/analysis_default_regression.py b/Examples/Tests/radiation_reaction/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/radiation_reaction/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/reduced_diags/CMakeLists.txt b/Examples/Tests/reduced_diags/CMakeLists.txt index cd4f6392892..743afa79df5 100644 --- a/Examples/Tests/reduced_diags/CMakeLists.txt +++ b/Examples/Tests/reduced_diags/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_reduced_diags # inputs - analysis_reduced_diags.py # analysis - diags/diag1000200 # output + "analysis_reduced_diags.py diags/diag1000200" # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_reduced_diags_load_balance_costs_heuristic # inputs - analysis_reduced_diags_load_balance_costs.py # analysis - diags/diag1000003 # output + "analysis_reduced_diags_load_balance_costs.py diags/diag1000003" # analysis + "analysis_default_regression.py --path diags/diag1000003" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_reduced_diags_load_balance_costs_timers # inputs - analysis_reduced_diags_load_balance_costs.py # analysis - diags/diag1000003 # output + "analysis_reduced_diags_load_balance_costs.py diags/diag1000003" # analysis + "analysis_default_regression.py --path diags/diag1000003" # checksum OFF # dependency ) @@ -36,8 +36,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_reduced_diags_load_balance_costs_timers_picmi.py # inputs - analysis_reduced_diags_load_balance_costs.py # analysis - diags/diag1000003 # output + "analysis_reduced_diags_load_balance_costs.py diags/diag1000003" # analysis + "analysis_default_regression.py --path diags/diag1000003" # checksum OFF # dependency ) @@ -47,8 +47,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_reduced_diags_load_balance_costs_timers_psatd # inputs - analysis_reduced_diags_load_balance_costs.py # analysis - diags/diag1000003 # output + "analysis_reduced_diags_load_balance_costs.py diags/diag1000003" # analysis + "analysis_default_regression.py --path diags/diag1000003" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/reduced_diags/analysis_default_regression.py b/Examples/Tests/reduced_diags/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/reduced_diags/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/reduced_diags/analysis_reduced_diags_impl.py b/Examples/Tests/reduced_diags/analysis_reduced_diags_impl.py index 42916d34568..e0c1fe1d1b3 100755 --- a/Examples/Tests/reduced_diags/analysis_reduced_diags_impl.py +++ b/Examples/Tests/reduced_diags/analysis_reduced_diags_impl.py @@ -11,7 +11,6 @@ # Various particle and field quantities are written to file using the reduced diagnostics # and compared with the corresponding quantities computed from the data in the plotfiles. -import os import sys import numpy as np @@ -20,9 +19,6 @@ from scipy.constants import epsilon_0 as eps0 from scipy.constants import mu_0 as mu0 -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # gamma threshold to switch between the relativistic expression of # the kinetic energy and its Taylor expansion. gamma_relativistic_threshold = 1.005 @@ -375,10 +371,3 @@ def do_analysis(single_precision=False): tol = field_energy_tolerance if (k == "field energy") else tolerance assert error[k] < tol print() - - # compare checksums - evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - rtol=1e-9, - ) diff --git a/Examples/Tests/reduced_diags/analysis_reduced_diags_load_balance_costs.py b/Examples/Tests/reduced_diags/analysis_reduced_diags_load_balance_costs.py index 49a0018baa5..978b1fcd4ec 100755 --- a/Examples/Tests/reduced_diags/analysis_reduced_diags_load_balance_costs.py +++ b/Examples/Tests/reduced_diags/analysis_reduced_diags_load_balance_costs.py @@ -17,15 +17,10 @@ # Possible running time: ~ 1 s -import os -import re import sys import numpy as np -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Command line argument fn = sys.argv[1] @@ -76,11 +71,3 @@ def get_efficiency(i): # The load balanced case is expected to be more efficient # than non-load balanced case assert efficiency_before < efficiency_after - -# compare checksums -test_name = os.path.split(os.getcwd())[1] -test_name = re.sub("_picmi", "", test_name) # same checksums for PICMI test -evaluate_checksum( - test_name=test_name, - output_file=sys.argv[1], -) diff --git a/Examples/Tests/reduced_diags/analysis_reduced_diags_single.py b/Examples/Tests/reduced_diags/analysis_reduced_diags_single.py deleted file mode 100755 index d900ec673c1..00000000000 --- a/Examples/Tests/reduced_diags/analysis_reduced_diags_single.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright 2019-2021 Luca Fedeli, Yinjian Zhao -# -# This file is part of WarpX. -# -# License: BSD-3-Clause-LBNL - -# This script tests the reduced diagnostics. -# The setup is a uniform plasma with electrons, protons and photons. -# Various particle and field quantities are written to file using the reduced diagnostics -# and compared with the corresponding quantities computed from the data in the plotfiles. - -import analysis_reduced_diags_impl as an - -an.do_analysis(single_precision=True) diff --git a/Examples/Tests/reduced_diags/inputs_test_3d_reduced_diags b/Examples/Tests/reduced_diags/inputs_test_3d_reduced_diags index dc0c57264ba..cc1b658c27f 100644 --- a/Examples/Tests/reduced_diags/inputs_test_3d_reduced_diags +++ b/Examples/Tests/reduced_diags/inputs_test_3d_reduced_diags @@ -68,7 +68,7 @@ photons.uz_th = 0.2 ################################# ###### REDUCED DIAGS ############ ################################# -warpx.reduced_diags_names = EP NP EF PP PF MF MR FP FP_integrate FP_line FP_plane FR_Max FR_Min FR_Integral Edotj +warpx.reduced_diags_names = EP NP EF PP PF MF PX MR FP FP_integrate FP_line FP_plane FR_Max FR_Min FR_Integral Edotj EP.type = ParticleEnergy EP.intervals = 200 EF.type = FieldEnergy @@ -79,6 +79,8 @@ PF.type = FieldMomentum PF.intervals = 200 MF.type = FieldMaximum MF.intervals = 200 +PX.type = FieldPoyntingFlux +PX.intervals = 200 FP.type = FieldProbe FP.intervals = 200 #The probe is placed at a cell center to match the value in the plotfile diff --git a/Examples/Tests/relativistic_space_charge_initialization/CMakeLists.txt b/Examples/Tests/relativistic_space_charge_initialization/CMakeLists.txt index d89fb8b31b6..df73a264429 100644 --- a/Examples/Tests/relativistic_space_charge_initialization/CMakeLists.txt +++ b/Examples/Tests/relativistic_space_charge_initialization/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_relativistic_space_charge_initialization # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles" # checksum OFF # dependency ) diff --git a/Examples/Tests/relativistic_space_charge_initialization/analysis.py b/Examples/Tests/relativistic_space_charge_initialization/analysis.py index ef0a87dce92..beb2b889ed7 100755 --- a/Examples/Tests/relativistic_space_charge_initialization/analysis.py +++ b/Examples/Tests/relativistic_space_charge_initialization/analysis.py @@ -12,7 +12,6 @@ the expected theoretical field. """ -import os import sys import matplotlib @@ -24,8 +23,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Parameters from the Simulation Qtot = -1.0e-20 @@ -94,10 +91,3 @@ def check(E, E_th, label): check(Ex_array, Ex_th, "Ex") - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/relativistic_space_charge_initialization/analysis_default_regression.py b/Examples/Tests/relativistic_space_charge_initialization/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/relativistic_space_charge_initialization/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/repelling_particles/CMakeLists.txt b/Examples/Tests/repelling_particles/CMakeLists.txt index 056f670a860..e5b64cb9166 100644 --- a/Examples/Tests/repelling_particles/CMakeLists.txt +++ b/Examples/Tests/repelling_particles/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_repelling_particles # inputs - analysis.py # analysis - diags/diag1000200 # output + "analysis.py diags/diag1000200" # analysis + "analysis_default_regression.py --path diags/diag1000200" # checksum OFF # dependency ) diff --git a/Examples/Tests/repelling_particles/analysis.py b/Examples/Tests/repelling_particles/analysis.py index 74bde7b68ca..5f052361fc7 100755 --- a/Examples/Tests/repelling_particles/analysis.py +++ b/Examples/Tests/repelling_particles/analysis.py @@ -24,7 +24,6 @@ """ import glob -import os import re import sys @@ -35,9 +34,6 @@ yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Check plotfile name specified in command line last_filename = sys.argv[1] filename_radical = re.findall(r"(.*?)\d+/*$", last_filename)[0] @@ -78,9 +74,3 @@ # Check that the results are close to the theory assert np.allclose(beta1[1:], beta_th[1:], atol=0.01) assert np.allclose(-beta2[1:], beta_th[1:], atol=0.01) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/repelling_particles/analysis_default_regression.py b/Examples/Tests/repelling_particles/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/repelling_particles/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/resampling/CMakeLists.txt b/Examples/Tests/resampling/CMakeLists.txt index 46e34858014..b6f8c5baecf 100644 --- a/Examples/Tests/resampling/CMakeLists.txt +++ b/Examples/Tests/resampling/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_resample_velocity_coincidence_thinning # inputs - analysis_default_regression.py # analysis - diags/diag1000004 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000004" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_resample_velocity_coincidence_thinning_cartesian # inputs - analysis_default_regression.py # analysis - diags/diag1000004 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000004" # checksum OFF # dependency ) @@ -26,7 +26,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_leveling_thinning # inputs - analysis.py # analysis - diags/diag1000008 # output + "analysis.py diags/diag1000008" # analysis + "analysis_default_regression.py --path diags/diag1000008" # checksum OFF # dependency ) diff --git a/Examples/Tests/resampling/analysis.py b/Examples/Tests/resampling/analysis.py index 40bad24d65e..8fff4a04a9c 100755 --- a/Examples/Tests/resampling/analysis.py +++ b/Examples/Tests/resampling/analysis.py @@ -9,16 +9,12 @@ ## In this test, we check that leveling thinning works as expected on two simple cases. Each case ## corresponds to a different particle species. -import os import sys import numpy as np import yt from scipy.special import erf -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - fn_final = sys.argv[1] fn0 = fn_final[:-4] + "0000" @@ -170,9 +166,3 @@ assert numparts_unaffected == numparts_unaffected_anticipated # Check that particles with weight higher than level weight are unaffected by resampling. assert np.all(w[-numparts_unaffected:] == w0[-numparts_unaffected:]) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/restart/CMakeLists.txt b/Examples/Tests/restart/CMakeLists.txt index df5b1239a01..1be7f2d5fa7 100644 --- a/Examples/Tests/restart/CMakeLists.txt +++ b/Examples/Tests/restart/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_id_cpu_read_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 1 # nprocs inputs_test_2d_runtime_components_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -27,8 +27,8 @@ add_warpx_test( 2 # dims 1 # nprocs "inputs_test_2d_runtime_components_picmi.py amr.restart='../test_2d_runtime_components_picmi/diags/chk000005'" # inputs - OFF #analysis_default_restart.py # analysis - OFF #diags/diag1000010 # output + OFF #"analysis_default_restart.py diags/diag1000010" # analysis + OFF #"analysis_default_regression.py --path diags/diag1000010" # checksum test_2d_runtime_components_picmi # dependency ) @@ -37,8 +37,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_acceleration # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) @@ -47,8 +47,8 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_acceleration_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000010 # output + "analysis_default_restart.py diags/diag1000010" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum test_3d_acceleration # dependency ) @@ -58,8 +58,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_acceleration_psatd # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) endif() @@ -70,8 +70,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_acceleration_psatd_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000010 # output + "analysis_default_restart.py diags/diag1000010" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum test_3d_acceleration_psatd # dependency ) endif() @@ -82,8 +82,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_acceleration_psatd_time_avg # inputs - analysis_default_regression.py # analysis - diags/diag1000010 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum OFF # dependency ) endif() @@ -94,8 +94,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_acceleration_psatd_time_avg_restart # inputs - analysis_default_restart.py # analysis - diags/diag1000010 # output + "analysis_default_restart.py diags/diag1000010" # analysis + "analysis_default_regression.py --path diags/diag1000010" # checksum test_3d_acceleration_psatd_time_avg # dependency ) endif() diff --git a/Examples/Tests/restart/analysis_restart.py b/Examples/Tests/restart/analysis_restart.py deleted file mode 100755 index 26a05da90f2..00000000000 --- a/Examples/Tests/restart/analysis_restart.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -filename = sys.argv[1] - -# Check restart data v. original data -sys.path.insert(0, "../../../../warpx/Examples/") -from analysis_default_restart import check_restart - -check_restart(filename) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/restart/inputs_test_2d_runtime_components_picmi.py b/Examples/Tests/restart/inputs_test_2d_runtime_components_picmi.py index e90bfd266a7..746dff27a42 100755 --- a/Examples/Tests/restart/inputs_test_2d_runtime_components_picmi.py +++ b/Examples/Tests/restart/inputs_test_2d_runtime_components_picmi.py @@ -107,7 +107,8 @@ np.random.seed(30025025) electron_wrapper = particle_containers.ParticleContainerWrapper("electrons") -electron_wrapper.add_real_comp("newPid") +if not sim.amr_restart: + electron_wrapper.add_real_comp("newPid") def add_particles(): @@ -140,8 +141,8 @@ def add_particles(): ########################## assert electron_wrapper.nps == 90 -assert electron_wrapper.particle_container.get_comp_index("w") == 2 -assert electron_wrapper.particle_container.get_comp_index("newPid") == 6 +assert electron_wrapper.particle_container.get_real_comp_index("w") == 2 +assert electron_wrapper.particle_container.get_real_comp_index("newPid") == 6 new_pid_vals = electron_wrapper.get_particle_real_arrays("newPid", 0) for vals in new_pid_vals: diff --git a/Examples/Tests/restart_eb/CMakeLists.txt b/Examples/Tests/restart_eb/CMakeLists.txt index 50f808c3e1f..0c685340c4c 100644 --- a/Examples/Tests/restart_eb/CMakeLists.txt +++ b/Examples/Tests/restart_eb/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) 3 # dims 1 # nprocs inputs_test_3d_eb_picmi.py # inputs - analysis_default_regression.py # analysis - diags/diag1000060 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000060" # checksum OFF # dependency ) endif() @@ -19,9 +19,9 @@ endif() # test_3d_eb_picmi_restart # name # 3 # dims # 1 # nprocs -## "inputs_test_3d_eb_picmi.py amr.restart='../test_3d_eb_picmi/diags/chk000030'" # inputs -# analysis_default_restart.py # analysis -# diags/diag1000060 # output +# "inputs_test_3d_eb_picmi.py amr.restart='../test_3d_eb_picmi/diags/chk000030'" # inputs +# "analysis_default_restart.py diags/diag1000060" # analysis +# "analysis_default_regression.py --path diags/diag1000060" # checksum # test_3d_eb_picmi # dependency # ) #endif() diff --git a/Examples/Tests/rigid_injection/CMakeLists.txt b/Examples/Tests/rigid_injection/CMakeLists.txt index 21004c3248c..ca0a84a87ef 100644 --- a/Examples/Tests/rigid_injection/CMakeLists.txt +++ b/Examples/Tests/rigid_injection/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_rigid_injection_btd # inputs - analysis_rigid_injection_btd.py # analysis - diags/diag1000001 # output + "analysis_rigid_injection_btd.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_rigid_injection_lab # inputs - analysis_rigid_injection_lab.py # analysis - diags/diag1000289 # output + "analysis_rigid_injection_lab.py diags/diag1000289" # analysis + "analysis_default_regression.py --path diags/diag1000289" # checksum OFF # dependency ) diff --git a/Examples/Tests/rigid_injection/analysis_default_regression.py b/Examples/Tests/rigid_injection/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/rigid_injection/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/rigid_injection/analysis_rigid_injection_btd.py b/Examples/Tests/rigid_injection/analysis_rigid_injection_btd.py index 759c211b42d..d87a680a819 100755 --- a/Examples/Tests/rigid_injection/analysis_rigid_injection_btd.py +++ b/Examples/Tests/rigid_injection/analysis_rigid_injection_btd.py @@ -20,7 +20,6 @@ frame, i.e., on the back-transformed diagnostics. """ -import os import sys import numpy as np @@ -29,9 +28,6 @@ yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - filename = sys.argv[1] # Tolerances to check consistency between plotfile BTD and openPMD BTD @@ -80,9 +76,3 @@ print(f"error = {err}") print(f"tolerance = {tol}") assert err < tol - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/rigid_injection/analysis_rigid_injection_lab.py b/Examples/Tests/rigid_injection/analysis_rigid_injection_lab.py index 91e2bed1ed0..69fbe4cc537 100755 --- a/Examples/Tests/rigid_injection/analysis_rigid_injection_lab.py +++ b/Examples/Tests/rigid_injection/analysis_rigid_injection_lab.py @@ -23,15 +23,12 @@ with the gaussian_beam injection style. """ -import os import sys import numpy as np import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -101,9 +98,3 @@ def remove_rigid_lines(plotfile, nlines_if_rigid): center = ad_start["beam", "particle_center"] assert np.array_equal(z, orig_z) assert np.array_equal(1 * (np.abs(x) < 5.0e-7), center) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/scraping/CMakeLists.txt b/Examples/Tests/scraping/CMakeLists.txt index a0fd04b6b3f..71897e85b88 100644 --- a/Examples/Tests/scraping/CMakeLists.txt +++ b/Examples/Tests/scraping/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_scraping # inputs - analysis_rz.py # analysis - diags/diag1000037 # output + "analysis_rz.py diags/diag1000037" # analysis + "analysis_default_regression.py --path diags/diag1000037" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_EB) RZ # dims 2 # nprocs inputs_test_rz_scraping_filter # inputs - analysis_rz_filter.py # analysis - diags/diag1000037 # output + "analysis_rz_filter.py diags/diag1000037" # analysis + "analysis_default_regression.py --path diags/diag1000037" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/scraping/analysis_default_regression.py b/Examples/Tests/scraping/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/scraping/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/scraping/analysis_rz.py b/Examples/Tests/scraping/analysis_rz.py index aa0038dbcf5..c5b60350cb8 100755 --- a/Examples/Tests/scraping/analysis_rz.py +++ b/Examples/Tests/scraping/analysis_rz.py @@ -20,16 +20,12 @@ # tolerance: 0 # Possible running time: < 1 s -import os import sys import numpy as np import yt from openpmd_viewer import OpenPMDTimeSeries -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - tolerance = 0 fn = sys.argv[1] @@ -82,10 +78,3 @@ def n_scraped_particles(iteration): assert np.all( np.sort(id_initial) == np.sort(id_final) ) # Sort because particles may not be in the same order - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/secondary_ion_emission/CMakeLists.txt b/Examples/Tests/secondary_ion_emission/CMakeLists.txt new file mode 100644 index 00000000000..e6e38138a08 --- /dev/null +++ b/Examples/Tests/secondary_ion_emission/CMakeLists.txt @@ -0,0 +1,14 @@ +# Add tests (alphabetical order) ############################################## +# + +if(WarpX_EB) + add_warpx_test( + test_rz_secondary_ion_emission_picmi # name + RZ # dims + 1 # nprocs + inputs_test_rz_secondary_ion_emission_picmi.py # inputs + "analysis.py diags/diag1/" # analysis + "analysis_default_regression.py --path diags/diag1/" # checksum + OFF # dependency + ) +endif() diff --git a/Examples/Tests/secondary_ion_emission/analysis.py b/Examples/Tests/secondary_ion_emission/analysis.py new file mode 100644 index 00000000000..8c2ed5b4af6 --- /dev/null +++ b/Examples/Tests/secondary_ion_emission/analysis.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +""" +This script checks that electron secondary emission (implemented by a callback function) works as intended. + +In this test, four ions hit a spherical embedded boundary, and produce secondary +electrons with a probability of `0.4`. We thus expect ~2 electrons to be produced. +This script tests the number of electrons emitted and checks that their position is +close to the embedded boundary. +""" + +import sys + +import numpy as np +import yt +from openpmd_viewer import OpenPMDTimeSeries + +yt.funcs.mylog.setLevel(0) + +# Open plotfile specified in command line +filename = sys.argv[1] +ts = OpenPMDTimeSeries(filename) + +it = ts.iterations +x, y, z = ts.get_particle(["x", "y", "z"], species="electrons", iteration=it[-1]) + +x_analytic = [-0.091696, 0.011599] +y_analytic = [-0.002282, -0.0111624] +z_analytic = [-0.200242, -0.201728] + +N_sec_e = np.size(z) # number of the secondary electrons + +assert N_sec_e == 2, ( + "Test did not pass: for this set up we expect 2 secondary electrons emitted" +) + +tolerance = 1e-3 + +for i in range(0, N_sec_e): + print("\n") + print(f"Electron # {i}:") + print("NUMERICAL coordinates of the emitted electrons:") + print(f"x={x[i]:5.5f}, y={y[i]:5.5f}, z={z[i]:5.5f}") + print("\n") + print("ANALYTICAL coordinates of the point of contact:") + print(f"x={x_analytic[i]:5.5f}, y={y_analytic[i]:5.5f}, z={z_analytic[i]:5.5f}") + + rel_err_x = np.abs((x[i] - x_analytic[i]) / x_analytic[i]) + rel_err_y = np.abs((y[i] - y_analytic[i]) / y_analytic[i]) + rel_err_z = np.abs((z[i] - z_analytic[i]) / z_analytic[i]) + + print("\n") + print(f"Relative percentage error for x = {rel_err_x * 100:5.4f} %") + print(f"Relative percentage error for y = {rel_err_y * 100:5.4f} %") + print(f"Relative percentage error for z = {rel_err_z * 100:5.4f} %") + + assert ( + (rel_err_x < tolerance) and (rel_err_y < tolerance) and (rel_err_z < tolerance) + ), "Test particle_boundary_interaction did not pass" diff --git a/Examples/Tests/secondary_ion_emission/analysis_default_regression.py b/Examples/Tests/secondary_ion_emission/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/secondary_ion_emission/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/secondary_ion_emission/inputs_test_rz_secondary_ion_emission_picmi.py b/Examples/Tests/secondary_ion_emission/inputs_test_rz_secondary_ion_emission_picmi.py new file mode 100644 index 00000000000..97ad6e09628 --- /dev/null +++ b/Examples/Tests/secondary_ion_emission/inputs_test_rz_secondary_ion_emission_picmi.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +# This is the script that tests secondary ion emission when ions hit an embedded boundary +# with a specified secondary emission yield of delta_H = 0.4. Specifically, a callback +# function at each time step ensures that the correct number of secondary electrons is +# emitted when ions impact the embedded boundary, following the given secondary emission +# model defined in sigma_nescap function. This distribution depends on the ion's energy and +# suggests that for an ion incident with 1 keV energy, an average of 0.4 secondary +# electrons will be emitted. +# Simulation is initialized with four ions with i_dist distribution and spherical +# embedded boundary given by implicit function. +import numpy as np +from scipy.constants import e, elementary_charge, m_e, proton_mass + +from pywarpx import callbacks, particle_containers, picmi + +########################## +# numerics parameters +########################## + +dt = 0.000000075 + +# --- Nb time steps +Te = 0.0259 # in eV +dist_th = np.sqrt(Te * elementary_charge / m_e) + +max_steps = 3 +diagnostic_interval = 1 + +# --- grid +nr = 64 +nz = 64 + +rmin = 0.0 +rmax = 2 +zmin = -2 +zmax = 2 +delta_H = 0.4 +E_HMax = 250 + +np.random.seed(10025015) +########################## +# numerics components +########################## + +grid = picmi.CylindricalGrid( + number_of_cells=[nr, nz], + n_azimuthal_modes=1, + lower_bound=[rmin, zmin], + upper_bound=[rmax, zmax], + lower_boundary_conditions=["none", "dirichlet"], + upper_boundary_conditions=["dirichlet", "dirichlet"], + lower_boundary_conditions_particles=["none", "reflecting"], + upper_boundary_conditions_particles=["absorbing", "reflecting"], +) + +solver = picmi.ElectrostaticSolver( + grid=grid, method="Multigrid", warpx_absolute_tolerance=1e-7 +) + +embedded_boundary = picmi.EmbeddedBoundary( + implicit_function="-(x**2+y**2+z**2-radius**2)", radius=0.2 +) + +########################## +# physics components +########################## +i_dist = picmi.ParticleListDistribution( + x=[ + 0.025, + 0.0, + -0.1, + -0.14, + ], + y=[0.0, 0.0, 0.0, 0], + z=[-0.26, -0.29, -0.25, -0.23], + ux=[0.18e6, 0.1e6, 0.15e6, 0.21e6], + uy=[0.0, 0.0, 0.0, 0.0], + uz=[8.00e5, 7.20e5, 6.40e5, 5.60e5], + weight=[1, 1, 1, 1], +) + +electrons = picmi.Species( + particle_type="electron", # Specify the particle type + name="electrons", # Name of the species +) + +ions = picmi.Species( + name="ions", + particle_type="proton", + charge=e, + initial_distribution=i_dist, + warpx_save_particles_at_eb=1, +) + +########################## +# diagnostics +########################## + +field_diag = picmi.FieldDiagnostic( + name="diag1", + grid=grid, + period=diagnostic_interval, + data_list=["Er", "Ez", "phi", "rho"], + warpx_format="openpmd", +) + +part_diag = picmi.ParticleDiagnostic( + name="diag1", + period=diagnostic_interval, + species=[ions, electrons], + warpx_format="openpmd", +) + +########################## +# simulation setup +########################## + +sim = picmi.Simulation( + solver=solver, + time_step_size=dt, + max_steps=max_steps, + warpx_embedded_boundary=embedded_boundary, + warpx_amrex_the_arena_is_managed=1, +) + +sim.add_species( + electrons, + layout=picmi.GriddedLayout(n_macroparticle_per_cell=[0, 0, 0], grid=grid), +) + +sim.add_species( + ions, + layout=picmi.GriddedLayout(n_macroparticle_per_cell=[10, 1, 1], grid=grid), +) + +sim.add_diagnostic(part_diag) +sim.add_diagnostic(field_diag) + +sim.initialize_inputs() +sim.initialize_warpx() + +########################## +# python particle data access +########################## + + +def concat(list_of_arrays): + if len(list_of_arrays) == 0: + # Return a 1d array of size 0 + return np.empty(0) + else: + return np.concatenate(list_of_arrays) + + +def sigma_nascap(energy_kEv, delta_H, E_HMax): + """ + Compute sigma_nascap for each element in the energy array using a loop. + + Parameters: + - energy: ndarray or list, energy values in KeV + - delta_H: float, parameter for the formula + - E_HMax: float, parameter for the formula in KeV + + Returns: + - numpy array, computed probability sigma_nascap + """ + sigma_nascap = np.array([]) + # Loop through each energy value + for energy in energy_kEv: + if energy > 0.0: + sigma = ( + delta_H + * (E_HMax + 1.0) + / (E_HMax * 1.0 + energy) + * np.sqrt(energy / 1.0) + ) + else: + sigma = 0.0 + sigma_nascap = np.append(sigma_nascap, sigma) + return sigma_nascap + + +def secondary_emission(): + buffer = particle_containers.ParticleBoundaryBufferWrapper() # boundary buffer + # STEP 1: extract the different parameters of the boundary buffer (normal, time, position) + lev = 0 # level 0 (no mesh refinement here) + n = buffer.get_particle_boundary_buffer_size("ions", "eb") + elect_pc = particle_containers.ParticleContainerWrapper("electrons") + + if n != 0: + r = concat(buffer.get_particle_scraped_this_step("ions", "eb", "x", lev)) + theta = concat( + buffer.get_particle_scraped_this_step("ions", "eb", "theta", lev) + ) + z = concat(buffer.get_particle_scraped_this_step("ions", "eb", "z", lev)) + x = r * np.cos(theta) # from RZ coordinates to 3D coordinates + y = r * np.sin(theta) + ux = concat(buffer.get_particle_scraped_this_step("ions", "eb", "ux", lev)) + uy = concat(buffer.get_particle_scraped_this_step("ions", "eb", "uy", lev)) + uz = concat(buffer.get_particle_scraped_this_step("ions", "eb", "uz", lev)) + w = concat(buffer.get_particle_scraped_this_step("ions", "eb", "w", lev)) + nx = concat(buffer.get_particle_scraped_this_step("ions", "eb", "nx", lev)) + ny = concat(buffer.get_particle_scraped_this_step("ions", "eb", "ny", lev)) + nz = concat(buffer.get_particle_scraped_this_step("ions", "eb", "nz", lev)) + delta_t = concat( + buffer.get_particle_scraped_this_step("ions", "eb", "deltaTimeScraped", lev) + ) + + energy_ions = 0.5 * proton_mass * w * (ux**2 + uy**2 + uz**2) + energy_ions_in_kEv = energy_ions / (e * 1000) + sigma_nascap_ions = sigma_nascap(energy_ions_in_kEv, delta_H, E_HMax) + # Loop over all ions that have been scraped in the last timestep + for i in range(0, len(w)): + sigma = sigma_nascap_ions[i] + # Ne_sec is number of the secondary electrons to be emitted + Ne_sec = int(sigma + np.random.uniform()) + for _ in range(Ne_sec): + xe = np.array([]) + ye = np.array([]) + ze = np.array([]) + we = np.array([]) + delta_te = np.array([]) + uxe = np.array([]) + uye = np.array([]) + uze = np.array([]) + + # Random thermal momenta distribution + ux_th = np.random.normal(0, dist_th) + uy_th = np.random.normal(0, dist_th) + uz_th = np.random.normal(0, dist_th) + + un_th = nx[i] * ux_th + ny[i] * uy_th + nz[i] * uz_th + + if un_th < 0: + ux_th_reflect = ( + -2 * un_th * nx[i] + ux_th + ) # for a "mirror reflection" u(sym)=-2(u.n)n+u + uy_th_reflect = -2 * un_th * ny[i] + uy_th + uz_th_reflect = -2 * un_th * nz[i] + uz_th + + uxe = np.append(uxe, ux_th_reflect) + uye = np.append(uye, uy_th_reflect) + uze = np.append(uze, uz_th_reflect) + else: + uxe = np.append(uxe, ux_th) + uye = np.append(uye, uy_th) + uze = np.append(uze, uz_th) + + xe = np.append(xe, x[i]) + ye = np.append(ye, y[i]) + ze = np.append(ze, z[i]) + we = np.append(we, w[i]) + delta_te = np.append(delta_te, delta_t[i]) + + elect_pc.add_particles( + x=xe + (dt - delta_te) * uxe, + y=ye + (dt - delta_te) * uye, + z=ze + (dt - delta_te) * uze, + ux=uxe, + uy=uye, + uz=uze, + w=we, + ) + + +# using the new particle container modified at the last step +callbacks.installafterstep(secondary_emission) +########################## +# simulation run +########################## +sim.step(max_steps) # the whole process is done "max_steps" times diff --git a/Examples/Tests/silver_mueller/CMakeLists.txt b/Examples/Tests/silver_mueller/CMakeLists.txt index 7866d23dc1f..6cdeeffac6f 100644 --- a/Examples/Tests/silver_mueller/CMakeLists.txt +++ b/Examples/Tests/silver_mueller/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 1 # dims 2 # nprocs inputs_test_1d_silver_mueller # inputs - analysis.py # analysis - diags/diag1000500 # output + "analysis.py diags/diag1000500" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) @@ -16,8 +16,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_silver_mueller_x # inputs - analysis.py # analysis - diags/diag1000500 # output + "analysis.py diags/diag1000500" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) @@ -26,8 +26,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_silver_mueller_z # inputs - analysis.py # analysis - diags/diag1000500 # output + "analysis.py diags/diag1000500" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) @@ -36,7 +36,7 @@ add_warpx_test( RZ # dims 2 # nprocs inputs_test_rz_silver_mueller_z # inputs - analysis.py # analysis - diags/diag1000500 # output + "analysis.py diags/diag1000500" # analysis + "analysis_default_regression.py --path diags/diag1000500" # checksum OFF # dependency ) diff --git a/Examples/Tests/silver_mueller/analysis.py b/Examples/Tests/silver_mueller/analysis.py index aee27131bc9..678c5e4186a 100755 --- a/Examples/Tests/silver_mueller/analysis.py +++ b/Examples/Tests/silver_mueller/analysis.py @@ -11,7 +11,6 @@ test check that the reflected field at the boundary is negligible. """ -import os import re import sys @@ -19,8 +18,6 @@ import yt yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum filename = sys.argv[1] @@ -50,9 +47,3 @@ assert np.all(abs(Ex) < max_reflection_amplitude) assert np.all(abs(Ey) < max_reflection_amplitude) assert np.all(abs(Ez) < max_reflection_amplitude) - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/silver_mueller/analysis_default_regression.py b/Examples/Tests/silver_mueller/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/silver_mueller/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/single_particle/CMakeLists.txt b/Examples/Tests/single_particle/CMakeLists.txt index bee870f0b17..fb823b39431 100644 --- a/Examples/Tests/single_particle/CMakeLists.txt +++ b/Examples/Tests/single_particle/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_bilinear_filter # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001" # checksum OFF # dependency ) diff --git a/Examples/Tests/single_particle/analysis.py b/Examples/Tests/single_particle/analysis.py index 4127663e14d..efd3f36cfdf 100755 --- a/Examples/Tests/single_particle/analysis.py +++ b/Examples/Tests/single_particle/analysis.py @@ -7,7 +7,6 @@ # License: BSD-3-Clause-LBNL -import os import sys import numpy as np @@ -15,8 +14,6 @@ from scipy import signal yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Build Jx without filter. This can be obtained by running this test without # a filter, e.g., execute @@ -65,9 +62,3 @@ print("tolerance_rel: " + str(tolerance_rel)) assert error_rel < tolerance_rel - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/single_particle/analysis_default_regression.py b/Examples/Tests/single_particle/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/single_particle/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/space_charge_initialization/CMakeLists.txt b/Examples/Tests/space_charge_initialization/CMakeLists.txt index 6ca1f4ad04c..00f9a5462fd 100644 --- a/Examples/Tests/space_charge_initialization/CMakeLists.txt +++ b/Examples/Tests/space_charge_initialization/CMakeLists.txt @@ -6,8 +6,8 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_space_charge_initialization # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles" # checksum OFF # dependency ) @@ -16,7 +16,7 @@ add_warpx_test( 3 # dims 2 # nprocs inputs_test_3d_space_charge_initialization # inputs - analysis.py # analysis - diags/diag1000001 # output + "analysis.py diags/diag1000001" # analysis + "analysis_default_regression.py --path diags/diag1000001 --skip-particles" # checksum OFF # dependency ) diff --git a/Examples/Tests/space_charge_initialization/analysis.py b/Examples/Tests/space_charge_initialization/analysis.py index d63ba8f7334..b8e5e689a87 100755 --- a/Examples/Tests/space_charge_initialization/analysis.py +++ b/Examples/Tests/space_charge_initialization/analysis.py @@ -12,7 +12,6 @@ the expected theoretical field. """ -import os import sys import matplotlib @@ -25,8 +24,6 @@ from scipy.special import gammainc yt.funcs.mylog.setLevel(0) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum # Parameters from the Simulation Qtot = -1.0e-20 @@ -123,10 +120,3 @@ def check(E, E_th, label): check(Ey_array, Ey_th, "Ey") if ds.dimensionality == 3: check(Ez_array, Ez_th, "Ez") - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], - do_particles=False, -) diff --git a/Examples/Tests/space_charge_initialization/analysis_default_regression.py b/Examples/Tests/space_charge_initialization/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/space_charge_initialization/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/Tests/subcycling/CMakeLists.txt b/Examples/Tests/subcycling/CMakeLists.txt index 688f54ac01c..503c9f24f34 100644 --- a/Examples/Tests/subcycling/CMakeLists.txt +++ b/Examples/Tests/subcycling/CMakeLists.txt @@ -6,7 +6,7 @@ add_warpx_test( 2 # dims 2 # nprocs inputs_test_2d_subcycling_mr # inputs - analysis_default_regression.py # analysis - diags/diag1000250 # output + OFF # analysis + "analysis_default_regression.py --path diags/diag1000250" # checksum OFF # dependency ) diff --git a/Examples/Tests/vay_deposition/CMakeLists.txt b/Examples/Tests/vay_deposition/CMakeLists.txt index ce8d51d3c2a..86108530b1d 100644 --- a/Examples/Tests/vay_deposition/CMakeLists.txt +++ b/Examples/Tests/vay_deposition/CMakeLists.txt @@ -7,8 +7,8 @@ if(WarpX_FFT) 2 # dims 2 # nprocs inputs_test_2d_vay_deposition # inputs - analysis.py # analysis - diags/diag1000050 # output + "analysis.py diags/diag1000050" # analysis + "analysis_default_regression.py --path diags/diag1000050" # checksum OFF # dependency ) endif() @@ -19,8 +19,8 @@ if(WarpX_FFT) 3 # dims 2 # nprocs inputs_test_3d_vay_deposition # inputs - analysis.py # analysis - diags/diag1000025 # output + "analysis.py diags/diag1000025" # analysis + "analysis_default_regression.py --path diags/diag1000025" # checksum OFF # dependency ) endif() diff --git a/Examples/Tests/vay_deposition/analysis.py b/Examples/Tests/vay_deposition/analysis.py index ba428520660..def231538de 100755 --- a/Examples/Tests/vay_deposition/analysis.py +++ b/Examples/Tests/vay_deposition/analysis.py @@ -6,7 +6,6 @@ # # License: BSD-3-Clause-LBNL -import os import sys import numpy as np @@ -15,9 +14,6 @@ yt.funcs.mylog.setLevel(50) -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - # Plotfile data set fn = sys.argv[1] ds = yt.load(fn) @@ -34,9 +30,3 @@ print("error_rel = {}".format(error_rel)) print("tolerance = {}".format(tolerance)) assert error_rel < tolerance - -# compare checksums -evaluate_checksum( - test_name=os.path.split(os.getcwd())[1], - output_file=sys.argv[1], -) diff --git a/Examples/Tests/vay_deposition/analysis_default_regression.py b/Examples/Tests/vay_deposition/analysis_default_regression.py new file mode 120000 index 00000000000..d8ce3fca419 --- /dev/null +++ b/Examples/Tests/vay_deposition/analysis_default_regression.py @@ -0,0 +1 @@ +../../analysis_default_regression.py \ No newline at end of file diff --git a/Examples/analysis_default_openpmd_regression.py b/Examples/analysis_default_openpmd_regression.py deleted file mode 100755 index 6f38693f820..00000000000 --- a/Examples/analysis_default_openpmd_regression.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python3 - -import os -import re -import sys - -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - -test_name = os.path.split(os.getcwd())[1] -output_file = sys.argv[1] - -# Run checksum regression test -if re.search("single_precision", output_file): - evaluate_checksum( - test_name=test_name, - output_file=output_file, - output_format="openpmd", - rtol=2e-6, - ) -else: - evaluate_checksum( - test_name=test_name, - output_file=output_file, - output_format="openpmd", - ) diff --git a/Examples/analysis_default_regression.py b/Examples/analysis_default_regression.py index 7c02f6904b2..e143e396f0c 100755 --- a/Examples/analysis_default_regression.py +++ b/Examples/analysis_default_regression.py @@ -1,25 +1,88 @@ #!/usr/bin/env python3 +import argparse import os -import re import sys +import yt +from openpmd_viewer import OpenPMDTimeSeries + sys.path.insert(1, "../../../../warpx/Regression/Checksum/") from checksumAPI import evaluate_checksum -test_name = os.path.split(os.getcwd())[1] -output_file = sys.argv[1] -# Run checksum regression test -if re.search("single_precision", output_file): +def main(args): + # parse test name from test directory + test_name = os.path.split(os.getcwd())[1] + if "_restart" in test_name: + rtol_restart = 1e-12 + print( + f"Warning: Setting relative tolerance {rtol_restart} for restart checksum analysis" + ) + # use original test's checksums + test_name = test_name.replace("_restart", "") + # reset relative tolerance + args.rtol = rtol_restart + # TODO check environment and reset tolerance (portable, machine precision) + # compare checksums evaluate_checksum( test_name=test_name, - output_file=output_file, - rtol=2e-6, + output_file=args.path, + output_format=args.format, + rtol=args.rtol, + do_fields=args.do_fields, + do_particles=args.do_particles, ) -else: - # using default relative tolerance - evaluate_checksum( - test_name=test_name, - output_file=output_file, + + +if __name__ == "__main__": + # define parser + parser = argparse.ArgumentParser() + # add arguments: output path + parser.add_argument( + "--path", + help="path to output file(s)", + type=str, + ) + # add arguments: relative tolerance + parser.add_argument( + "--rtol", + help="relative tolerance to compare checksums", + type=float, + required=False, + default=1e-9, + ) + # add arguments: skip fields + parser.add_argument( + "--skip-fields", + help="skip fields when comparing checksums", + action="store_true", + dest="skip_fields", + ) + # add arguments: skip particles + parser.add_argument( + "--skip-particles", + help="skip particles when comparing checksums", + action="store_true", + dest="skip_particles", ) + # parse arguments + args = parser.parse_args() + # set args.format automatically + try: + yt.load(args.path) + except Exception: + try: + OpenPMDTimeSeries(args.path) + except Exception: + print("Could not open the file as a plotfile or an openPMD time series") + else: + args.format = "openpmd" + else: + args.format = "plotfile" + # set args.do_fields (not parsed, based on args.skip_fields) + args.do_fields = False if args.skip_fields else True + # set args.do_particles (not parsed, based on args.skip_particles) + args.do_particles = False if args.skip_particles else True + # execute main function + main(args) diff --git a/Examples/analysis_default_restart.py b/Examples/analysis_default_restart.py index c019a0b5945..ad6bc22e60e 100755 --- a/Examples/analysis_default_restart.py +++ b/Examples/analysis_default_restart.py @@ -6,9 +6,6 @@ import numpy as np import yt -sys.path.insert(1, "../../../../warpx/Regression/Checksum/") -from checksumAPI import evaluate_checksum - def check_restart(filename, tolerance=1e-12): """ @@ -67,17 +64,6 @@ def check_restart(filename, tolerance=1e-12): print() -# test name (for checksums, remove "_restart") and output file name -test_name = os.path.split(os.getcwd())[1] -test_name = test_name.replace("_restart", "") -output_file = sys.argv[1] - # compare restart results against original results +output_file = sys.argv[1] check_restart(output_file) - -# compare restart checksums against original checksums -evaluate_checksum( - test_name=test_name, - output_file=output_file, - rtol=1e-12, -) diff --git a/Examples/test_cleanup.cmake b/Examples/test_cleanup.cmake new file mode 100644 index 00000000000..b15e31e1f5d --- /dev/null +++ b/Examples/test_cleanup.cmake @@ -0,0 +1,7 @@ +# delete all test files except backtrace +file(GLOB test_files ${CMAKE_ARGV3}/*) +foreach(file ${test_files}) + if(NOT ${file} MATCHES "Backtrace*") + execute_process(COMMAND ${CMAKE_COMMAND} -E rm -r ${file}) + endif() +endforeach() diff --git a/GNUmakefile b/GNUmakefile index 1cc78403c7b..ef3239e249d 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -38,13 +38,12 @@ USE_OPENPMD = FALSE WarpxBinDir = Bin USE_FFT = FALSE -USE_HEFFTE = FALSE USE_RZ = FALSE USE_EB = FALSE USE_LINEAR_SOLVERS_EM = TRUE -USE_LINEAR_SOLVERS_INCFLO = FALSE +USE_LINEAR_SOLVERS_INCFLO = TRUE WARPX_HOME := . include $(WARPX_HOME)/Source/Make.WarpX diff --git a/GOVERNANCE.rst b/GOVERNANCE.rst index 588e8b2df6e..f0efb350213 100644 --- a/GOVERNANCE.rst +++ b/GOVERNANCE.rst @@ -54,7 +54,9 @@ Technical Committee Current Roster ^^^^^^^^^^^^^^ +- Justin Ray Angus - Luca Fedeli +- Arianna Formenti - Roelof Groenewald - David Grote - Axel Huebl diff --git a/LICENSE.txt b/LICENSE.txt index 2965985ebb1..ba0df767288 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -14,10 +14,11 @@ this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -(3) Neither the name of the University of California, Lawrence Berkeley -National Laboratory, U.S. Dept. of Energy nor the names of its contributors -may be used to endorse or promote products derived from this software -without specific prior written permission. +(3) Neither the name of the University of California, +Lawrence Berkeley National Laboratory, Lawrence Livermore National Security, +Lawrence Livermore National Laboratory, U.S. Dept. of Energy nor the names of +its contributors may be used to endorse or promote products derived from this +software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" diff --git a/Python/pywarpx/HybridPICModel.py b/Python/pywarpx/HybridPICModel.py index 7bd8c961950..f94f44ce931 100644 --- a/Python/pywarpx/HybridPICModel.py +++ b/Python/pywarpx/HybridPICModel.py @@ -9,3 +9,4 @@ from .Bucket import Bucket hybridpicmodel = Bucket("hybrid_pic_model") +external_vector_potential = Bucket("external_vector_potential") diff --git a/Python/pywarpx/WarpX.py b/Python/pywarpx/WarpX.py index 9ef7019cda9..9b0446bcc79 100644 --- a/Python/pywarpx/WarpX.py +++ b/Python/pywarpx/WarpX.py @@ -20,7 +20,7 @@ from .Diagnostics import diagnostics, reduced_diagnostics from .EB2 import eb2 from .Geometry import geometry -from .HybridPICModel import hybridpicmodel +from .HybridPICModel import external_vector_potential, hybridpicmodel from .Interpolation import interpolation from .Lasers import lasers, lasers_list from .Particles import particles, particles_list @@ -46,6 +46,7 @@ def create_argv_list(self, **kw): argv += amrex.attrlist() argv += geometry.attrlist() argv += hybridpicmodel.attrlist() + argv += external_vector_potential.attrlist() argv += boundary.attrlist() argv += algo.attrlist() argv += interpolation.attrlist() diff --git a/Python/pywarpx/__init__.py b/Python/pywarpx/__init__.py index 054ca451756..b8e025342dd 100644 --- a/Python/pywarpx/__init__.py +++ b/Python/pywarpx/__init__.py @@ -33,7 +33,7 @@ from .Diagnostics import diagnostics, reduced_diagnostics # noqa from .EB2 import eb2 # noqa from .Geometry import geometry # noqa -from .HybridPICModel import hybridpicmodel # noqa +from .HybridPICModel import hybridpicmodel, external_vector_potential # noqa from .Interpolation import interpolation # noqa from .Lasers import lasers # noqa from .LoadThirdParty import load_cupy # noqa diff --git a/Python/pywarpx/_libwarpx.py b/Python/pywarpx/_libwarpx.py index 40426104b9f..98c10f7a8c4 100755 --- a/Python/pywarpx/_libwarpx.py +++ b/Python/pywarpx/_libwarpx.py @@ -40,9 +40,14 @@ def __getattr__(self, attribute): # Once loaded, it gets added to the dictionary so this code won't be called again. self.load_library() return self.__dict__[attribute] + elif attribute == "warpx": + # A `warpx` attribute has not yet been assigned, so `initialize_warpx` has not been called. + raise AttributeError( + "Trying to access libwarpx.warpx before initialize_warpx has been called!" + ) else: # For any other attribute, call the built-in routine - this should always - # return an AttributeException. + # return an AttributeError. return self.__getattribute__(attribute) def _get_package_root(self): @@ -143,8 +148,6 @@ def initialize(self, argv=None, mpi_comm=None): self.libwarpx_so.execute_python_callback("afterinit") self.libwarpx_so.execute_python_callback("particleloader") - # self.libwarpx_so.warpx_init() - self.initialized = True def finalize(self, finalize_mpi=1): diff --git a/Python/pywarpx/callbacks.py b/Python/pywarpx/callbacks.py index 45c9b63a082..d12293e699b 100644 --- a/Python/pywarpx/callbacks.py +++ b/Python/pywarpx/callbacks.py @@ -280,6 +280,7 @@ def callfuncsinlist(self, *args, **kw): "loadExternalFields": {}, "beforeInitEsolve": {}, "afterInitEsolve": {}, + "afterInitatRestart": {}, "afterinit": {}, "beforecollisions": {}, "aftercollisions": {}, @@ -406,6 +407,16 @@ def installafterInitEsolve(f): installcallback("afterInitEsolve", f) +# ---------------------------------------------------------------------------- +def callfromafterInitatRestart(f): + installcallback("afterInitatRestart", f) + return f + + +def installafterInitatRestart(f): + installcallback("afterInitatRestart", f) + + # ---------------------------------------------------------------------------- def callfromafterinit(f): installcallback("afterinit", f) diff --git a/Python/pywarpx/fields.py b/Python/pywarpx/fields.py index 5d3b892b543..a81999103d9 100644 --- a/Python/pywarpx/fields.py +++ b/Python/pywarpx/fields.py @@ -284,10 +284,10 @@ def _find_start_stop(self, ii, imin, imax, d): iistart = ii iistop = ii + 1 assert imin <= iistart <= imax, Exception( - f"Dimension {d+1} lower index is out of bounds" + f"Dimension {d + 1} lower index is out of bounds" ) assert imin <= iistop <= imax, Exception( - f"Dimension {d+1} upper index is out of bounds" + f"Dimension {d + 1} upper index is out of bounds" ) return iistart, iistop @@ -578,6 +578,24 @@ def norm0(self, *args): return self.mf.norm0(*args) +def CustomNamedxWrapper(mf_name, level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name=mf_name, idir=0, level=level, include_ghosts=include_ghosts + ) + + +def CustomNamedyWrapper(mf_name, level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name=mf_name, idir=1, level=level, include_ghosts=include_ghosts + ) + + +def CustomNamedzWrapper(mf_name, level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name=mf_name, idir=2, level=level, include_ghosts=include_ghosts + ) + + def ExWrapper(level=0, include_ghosts=False): return _MultiFABWrapper( mf_name="Efield_aux", idir=0, level=level, include_ghosts=include_ghosts @@ -704,6 +722,87 @@ def BzFPExternalWrapper(level=0, include_ghosts=False): ) +def AxHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_A_fp_external", + idir=0, + level=level, + include_ghosts=include_ghosts, + ) + + +def AyHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_A_fp_external", + idir=1, + level=level, + include_ghosts=include_ghosts, + ) + + +def AzHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_A_fp_external", + idir=2, + level=level, + include_ghosts=include_ghosts, + ) + + +def ExHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_E_fp_external", + idir=0, + level=level, + include_ghosts=include_ghosts, + ) + + +def EyHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_E_fp_external", + idir=1, + level=level, + include_ghosts=include_ghosts, + ) + + +def EzHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_E_fp_external", + idir=2, + level=level, + include_ghosts=include_ghosts, + ) + + +def BxHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_B_fp_external", + idir=0, + level=level, + include_ghosts=include_ghosts, + ) + + +def ByHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_B_fp_external", + idir=1, + level=level, + include_ghosts=include_ghosts, + ) + + +def BzHybridExternalWrapper(level=0, include_ghosts=False): + return _MultiFABWrapper( + mf_name="hybrid_B_fp_external", + idir=2, + level=level, + include_ghosts=include_ghosts, + ) + + def JxFPWrapper(level=0, include_ghosts=False): return _MultiFABWrapper( mf_name="current_fp", idir=0, level=level, include_ghosts=include_ghosts diff --git a/Python/pywarpx/particle_containers.py b/Python/pywarpx/particle_containers.py index bc6b2d74106..0488d262fc8 100644 --- a/Python/pywarpx/particle_containers.py +++ b/Python/pywarpx/particle_containers.py @@ -24,10 +24,21 @@ class ParticleContainerWrapper(object): def __init__(self, species_name): self.name = species_name + self._particle_container = None + + @property + def particle_container(self): + if self._particle_container is None: + try: + mypc = libwarpx.warpx.multi_particle_container() + self._particle_container = mypc.get_particle_container_from_name( + self.name + ) + except AttributeError as e: + msg = "You must initialize WarpX before accessing a ParticleContainerWrapper's particle_container." + raise AttributeError(msg) from e - # grab the desired particle container - mypc = libwarpx.warpx.multi_particle_container() - self.particle_container = mypc.get_particle_container_from_name(self.name) + return self._particle_container def add_particles( self, @@ -96,31 +107,31 @@ def add_particles( maxlen = max(maxlen, lenw) # --- Make sure that the lengths of the input parameters are consistent - assert ( - x is None or lenx == maxlen or lenx == 1 - ), "Length of x doesn't match len of others" - assert ( - y is None or leny == maxlen or leny == 1 - ), "Length of y doesn't match len of others" - assert ( - z is None or lenz == maxlen or lenz == 1 - ), "Length of z doesn't match len of others" - assert ( - ux is None or lenux == maxlen or lenux == 1 - ), "Length of ux doesn't match len of others" - assert ( - uy is None or lenuy == maxlen or lenuy == 1 - ), "Length of uy doesn't match len of others" - assert ( - uz is None or lenuz == maxlen or lenuz == 1 - ), "Length of uz doesn't match len of others" - assert ( - w is None or lenw == maxlen or lenw == 1 - ), "Length of w doesn't match len of others" + assert x is None or lenx == maxlen or lenx == 1, ( + "Length of x doesn't match len of others" + ) + assert y is None or leny == maxlen or leny == 1, ( + "Length of y doesn't match len of others" + ) + assert z is None or lenz == maxlen or lenz == 1, ( + "Length of z doesn't match len of others" + ) + assert ux is None or lenux == maxlen or lenux == 1, ( + "Length of ux doesn't match len of others" + ) + assert uy is None or lenuy == maxlen or lenuy == 1, ( + "Length of uy doesn't match len of others" + ) + assert uz is None or lenuz == maxlen or lenuz == 1, ( + "Length of uz doesn't match len of others" + ) + assert w is None or lenw == maxlen or lenw == 1, ( + "Length of w doesn't match len of others" + ) for key, val in kwargs.items(): - assert ( - np.size(val) == 1 or len(val) == maxlen - ), f"Length of {key} doesn't match len of others" + assert np.size(val) == 1 or len(val) == maxlen, ( + f"Length of {key} doesn't match len of others" + ) # --- Broadcast scalars into appropriate length arrays # --- If the parameter was not supplied, use the default value @@ -159,7 +170,9 @@ def add_particles( # --- Note that the velocities are handled separately and not included in attr # --- (even though they are stored as attributes in the C++) for key, vals in kwargs.items(): - attr[:, self.particle_container.get_comp_index(key) - built_in_attrs] = vals + attr[ + :, self.particle_container.get_real_comp_index(key) - built_in_attrs + ] = vals nattr_int = 0 attr_int = np.empty([0], dtype=np.int32) @@ -253,7 +266,7 @@ def get_particle_real_arrays(self, comp_name, level, copy_to_host=False): List of arrays The requested particle array data """ - comp_idx = self.particle_container.get_comp_index(comp_name) + comp_idx = self.particle_container.get_real_comp_index(comp_name) data_array = [] for pti in libwarpx.libwarpx_so.WarpXParIter(self.particle_container, level): @@ -298,7 +311,7 @@ def get_particle_int_arrays(self, comp_name, level, copy_to_host=False): List of arrays The requested particle array data """ - comp_idx = self.particle_container.get_icomp_index(comp_name) + comp_idx = self.particle_container.get_int_comp_index(comp_name) data_array = [] for pti in libwarpx.libwarpx_so.WarpXParIter(self.particle_container, level): @@ -758,7 +771,18 @@ class ParticleBoundaryBufferWrapper(object): """ def __init__(self): - self.particle_buffer = libwarpx.warpx.get_particle_boundary_buffer() + self._particle_buffer = None + + @property + def particle_buffer(self): + if self._particle_buffer is None: + try: + self._particle_buffer = libwarpx.warpx.get_particle_boundary_buffer() + except AttributeError as e: + msg = "You must initialize WarpX before accessing a ParticleBoundaryBufferWrapper's particle_buffer." + raise AttributeError(msg) from e + + return self._particle_buffer def get_particle_boundary_buffer_size(self, species_name, boundary, local=False): """ @@ -820,16 +844,16 @@ def get_particle_boundary_buffer(self, species_name, boundary, comp_name, level) ) data_array = [] # loop over the real attributes - if comp_name in part_container.real_comp_names: - comp_idx = part_container.real_comp_names[comp_name] + if comp_name in part_container.real_soa_names: + comp_idx = part_container.get_real_comp_index(comp_name) for ii, pti in enumerate( libwarpx.libwarpx_so.BoundaryBufferParIter(part_container, level) ): soa = pti.soa() data_array.append(xp.array(soa.get_real_data(comp_idx), copy=False)) # loop over the integer attributes - elif comp_name in part_container.int_comp_names: - comp_idx = part_container.int_comp_names[comp_name] + elif comp_name in part_container.int_soa_names: + comp_idx = part_container.get_int_comp_index(comp_name) for ii, pti in enumerate( libwarpx.libwarpx_so.BoundaryBufferParIter(part_container, level) ): @@ -839,6 +863,51 @@ def get_particle_boundary_buffer(self, species_name, boundary, comp_name, level) raise RuntimeError("Name %s not found" % comp_name) return data_array + def get_particle_scraped_this_step(self, species_name, boundary, comp_name, level): + """ + This returns a list of numpy or cupy arrays containing the particle array data + for particles that have been scraped at the current timestep, + for a specific species and simulation boundary. + + The data for the arrays is a view of the underlying boundary buffer in WarpX ; + writing to these arrays will therefore also modify the underlying boundary buffer. + + Parameters + ---------- + + species_name : str + The species name that the data will be returned for. + + boundary : str + The boundary from which to get the scraped particle data in the + form x/y/z_hi/lo or eb. + + comp_name : str + The component of the array data that will be returned. + "x", "y", "z", "ux", "uy", "uz", "w" + "stepScraped","deltaTimeScraped", + if boundary='eb': "nx", "ny", "nz" + + level : int + Which AMR level to retrieve scraped particle data from. + """ + # Extract the integer number of the current timestep + current_step = libwarpx.libwarpx_so.get_instance().getistep(level) + + # Extract the data requested by the user + data_array = self.get_particle_boundary_buffer( + species_name, boundary, comp_name, level + ) + step_scraped_array = self.get_particle_boundary_buffer( + species_name, boundary, "stepScraped", level + ) + + # Select on the particles from the previous step + data_array_this_step = [] + for data, step in zip(data_array, step_scraped_array): + data_array_this_step.append(data[step == current_step]) + return data_array_this_step + def clear_buffer(self): """ diff --git a/Python/pywarpx/picmi.py b/Python/pywarpx/picmi.py index 08c71ed02de..9606fc70136 100644 --- a/Python/pywarpx/picmi.py +++ b/Python/pywarpx/picmi.py @@ -688,14 +688,34 @@ def setup_parse_momentum_functions( ) -class UniformFluxDistribution( - picmistandard.PICMI_UniformFluxDistribution, DensityDistributionBase +class UniformDistribution( + picmistandard.PICMI_UniformDistribution, DensityDistributionBase ): + def distribution_initialize_inputs( + self, species_number, layout, species, density_scale, source_name + ): + self.set_mangle_dict() + self.set_species_attributes(species, layout, source_name) + + # --- Only constant density is supported by this class + species.add_new_group_attr(source_name, "profile", "constant") + species.add_new_group_attr(source_name, "density", self.density) + if density_scale is not None: + species.add_new_group_attr(source_name, "density", density_scale) + + +class FluxDistributionBase(object): + """This is a base class for both uniform and analytic flux distributions.""" + def init(self, kw): self.inject_from_embedded_boundary = kw.pop( "warpx_inject_from_embedded_boundary", False ) + def initialize_flux_profile_func(self, species, density_scale, source_name): + """Initialize the flux profile and flux function.""" + pass + def distribution_initialize_inputs( self, species_number, layout, species, density_scale, source_name ): @@ -703,10 +723,7 @@ def distribution_initialize_inputs( self.set_mangle_dict() self.set_species_attributes(species, layout, source_name) - species.add_new_group_attr(source_name, "flux_profile", "constant") - species.add_new_group_attr(source_name, "flux", self.flux) - if density_scale is not None: - species.add_new_group_attr(source_name, "flux", density_scale) + self.initialize_flux_profile_func(species, density_scale, source_name) if not self.inject_from_embedded_boundary: species.add_new_group_attr( @@ -737,20 +754,62 @@ def distribution_initialize_inputs( ) -class UniformDistribution( - picmistandard.PICMI_UniformDistribution, DensityDistributionBase +class AnalyticFluxDistribution( + picmistandard.PICMI_AnalyticFluxDistribution, + FluxDistributionBase, + DensityDistributionBase, ): - def distribution_initialize_inputs( - self, species_number, layout, species, density_scale, source_name - ): - self.set_mangle_dict() - self.set_species_attributes(species, layout, source_name) + """ + Parameters + ---------- - # --- Only constant density is supported by this class - species.add_new_group_attr(source_name, "profile", "constant") - species.add_new_group_attr(source_name, "density", self.density) + warpx_inject_from_embedded_boundary: bool + When true, the flux is injected from the embedded boundaries instead + of a plane. + """ + + def init(self, kw): + FluxDistributionBase.init(self, kw) + + def initialize_flux_profile_func(self, species, density_scale, source_name): + species.add_new_group_attr(source_name, "flux_profile", "parse_flux_function") if density_scale is not None: - species.add_new_group_attr(source_name, "density", density_scale) + species.add_new_group_attr(source_name, "flux", density_scale) + expression = pywarpx.my_constants.mangle_expression(self.flux, self.mangle_dict) + if density_scale is None: + species.add_new_group_attr( + source_name, "flux_function(x,y,z,t)", expression + ) + else: + species.add_new_group_attr( + source_name, + "flux_function(x,y,z,t)", + "{}*({})".format(density_scale, expression), + ) + + +class UniformFluxDistribution( + picmistandard.PICMI_UniformFluxDistribution, + FluxDistributionBase, + DensityDistributionBase, +): + """ + Parameters + ---------- + + warpx_inject_from_embedded_boundary: bool + When true, the flux is injected from the embedded boundaries instead + of a plane. + """ + + def init(self, kw): + FluxDistributionBase.init(self, kw) + + def initialize_flux_profile_func(self, species, density_scale, source_name): + species.add_new_group_attr(source_name, "flux_profile", "constant") + species.add_new_group_attr(source_name, "flux", self.flux) + if density_scale is not None: + species.add_new_group_attr(source_name, "flux", density_scale) class AnalyticDistribution( @@ -1794,8 +1853,37 @@ class HybridPICSolver(picmistandard.base._ClassWithInit): substeps: int, default=100 Number of substeps to take when updating the B-field. + holmstrom_vacuum_region: bool, default=False + Flag to determine handling of vacuum region. Setting to True will solve the simplified Generalized Ohm's Law dropping the Hall and pressure terms in the vacuum region. + This flag is useful for suppressing vacuum region fluctuations. A large resistivity value must be used when rho <= rho_floor. + Jx/y/z_external_function: str Function of space and time specifying external (non-plasma) currents. + + A_external: dict + Function of space and time specifying external (non-plasma) vector potential fields. + It is expected that a nested dicitonary will be passed + into picmi for each field that has different timings + e.g. + A_external = { + '': { + 'Ax_external_function': , + 'Ay_external_function': , + 'Az_external_function': , + 'A_time_external_function': + }, + ': {...}' + } + + or if fields are to be loaded from an OpenPMD file + A_external = { + '': { + 'load_from_file': True, + 'path': , + 'A_time_external_function': + }, + ': {...}' + } """ def __init__( @@ -1808,9 +1896,11 @@ def __init__( plasma_resistivity=None, plasma_hyper_resistivity=None, substeps=None, + holmstrom_vacuum_region=None, Jx_external_function=None, Jy_external_function=None, Jz_external_function=None, + A_external=None, **kw, ): self.grid = grid @@ -1825,10 +1915,14 @@ def __init__( self.substeps = substeps + self.holmstrom_vacuum_region = holmstrom_vacuum_region + self.Jx_external_function = Jx_external_function self.Jy_external_function = Jy_external_function self.Jz_external_function = Jz_external_function + self.A_external = A_external + # Handle keyword arguments used in expressions self.user_defined_kw = {} for k in list(kw.keys()): @@ -1857,8 +1951,14 @@ def solver_initialize_inputs(self): self.plasma_resistivity, self.mangle_dict ), ) - pywarpx.hybridpicmodel.plasma_hyper_resistivity = self.plasma_hyper_resistivity + pywarpx.hybridpicmodel.__setattr__( + "plasma_hyper_resistivity(rho,B)", + pywarpx.my_constants.mangle_expression( + self.plasma_hyper_resistivity, self.mangle_dict + ), + ) pywarpx.hybridpicmodel.substeps = self.substeps + pywarpx.hybridpicmodel.holmstrom_vacuum_region = self.holmstrom_vacuum_region pywarpx.hybridpicmodel.__setattr__( "Jx_external_grid_function(x,y,z,t)", pywarpx.my_constants.mangle_expression( @@ -1877,6 +1977,47 @@ def solver_initialize_inputs(self): self.Jz_external_function, self.mangle_dict ), ) + if self.A_external is not None: + pywarpx.hybridpicmodel.add_external_fields = True + pywarpx.external_vector_potential.__setattr__( + "fields", + pywarpx.my_constants.mangle_expression( + list(self.A_external.keys()), self.mangle_dict + ), + ) + for field_name, field_dict in self.A_external.items(): + if field_dict.get("read_from_file", False): + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.read_from_file", field_dict["read_from_file"] + ) + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.path", field_dict["path"] + ) + else: + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.Ax_external_grid_function(x,y,z)", + pywarpx.my_constants.mangle_expression( + field_dict["Ax_external_function"], self.mangle_dict + ), + ) + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.Ay_external_grid_function(x,y,z)", + pywarpx.my_constants.mangle_expression( + field_dict["Ay_external_function"], self.mangle_dict + ), + ) + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.Az_external_grid_function(x,y,z)", + pywarpx.my_constants.mangle_expression( + field_dict["Az_external_function"], self.mangle_dict + ), + ) + pywarpx.external_vector_potential.__setattr__( + f"{field_name}.A_time_external_function(t)", + pywarpx.my_constants.mangle_expression( + field_dict["A_time_external_function"], self.mangle_dict + ), + ) class ElectrostaticSolver(picmistandard.PICMI_ElectrostaticSolver): @@ -1894,14 +2035,24 @@ class ElectrostaticSolver(picmistandard.PICMI_ElectrostaticSolver): warpx_self_fields_verbosity: integer, default=2 Level of verbosity for the lab frame solver - warpx_dt_update_interval: string, optional (default = -1) + warpx_magnetostatic: bool, default=False + Whether to use the magnetostatic solver + + warpx_effective_potential: bool, default=False + Whether to use the effective potential Poisson solver (EP-PIC) + + warpx_effective_potential_factor: float, default=4 + If the effective potential Poisson solver is used, this sets the value + of C_EP (the method is marginally stable at C_EP = 1) + + warpx_dt_update_interval: integer, optional (default = -1) How frequently the timestep is updated. Adaptive timestepping is disabled when this is <= 0. warpx_cfl: float, optional - Fraction of the CFL condition for particle velocity vs grid size, used to set the timestep when `dt_update_interval > 0`. + Fraction of the CFL condition for particle velocity vs grid size, used to set the timestep when `warpx_dt_update_interval > 0`. warpx_max_dt: float, optional - The maximum allowable timestep when `dt_update_interval > 0`. + The maximum allowable timestep when `warpx_dt_update_interval > 0`. """ @@ -1910,8 +2061,12 @@ def init(self, kw): self.absolute_tolerance = kw.pop("warpx_absolute_tolerance", None) self.self_fields_verbosity = kw.pop("warpx_self_fields_verbosity", None) self.magnetostatic = kw.pop("warpx_magnetostatic", False) + self.effective_potential = kw.pop("warpx_effective_potential", False) + self.effective_potential_factor = kw.pop( + "warpx_effective_potential_factor", None + ) self.cfl = kw.pop("warpx_cfl", None) - self.dt_update_interval = kw.pop("dt_update_interval", None) + self.dt_update_interval = kw.pop("warpx_dt_update_interval", None) self.max_dt = kw.pop("warpx_max_dt", None) def solver_initialize_inputs(self): @@ -1930,6 +2085,11 @@ def solver_initialize_inputs(self): else: if self.magnetostatic: pywarpx.warpx.do_electrostatic = "labframe-electromagnetostatic" + elif self.effective_potential: + pywarpx.warpx.do_electrostatic = "labframe-effective-potential" + pywarpx.warpx.effective_potential_factor = ( + self.effective_potential_factor + ) else: pywarpx.warpx.do_electrostatic = "labframe" pywarpx.warpx.self_fields_required_precision = self.required_precision @@ -2478,7 +2638,7 @@ def __init__( **kw, ): assert stl_file is None or implicit_function is None, Exception( - "Only one between implicit_function and " "stl_file can be specified" + "Only one between implicit_function and stl_file can be specified" ) self.implicit_function = implicit_function @@ -2588,9 +2748,9 @@ def __init__( self.strengths_E = strengths_E self.strengths_B = strengths_B - assert (self.strengths_E is not None) or ( - self.strengths_B is not None - ), Exception("One of strengths_E or strengths_B must be supplied") + assert (self.strengths_E is not None) or (self.strengths_B is not None), ( + Exception("One of strengths_E or strengths_B must be supplied") + ) self.handle_init(kw) @@ -2770,6 +2930,21 @@ class Simulation(picmistandard.PICMI_Simulation): warpx_used_inputs_file: string, optional The name of the text file that the used input parameters is written to, + + warpx_reduced_diags_path: string, optional + Sets the default path for reduced diagnostic output files + + warpx_reduced_diags_extension: string, optional + Sets the default extension for reduced diagnostic output files + + warpx_reduced_diags_intervals: string, optional + Sets the default intervals for reduced diagnostic output files + + warpx_reduced_diags_separator: string, optional + Sets the default separator for reduced diagnostic output files + + warpx_reduced_diags_precision: integer, optional + Sets the default precision for reduced diagnostic output files """ # Set the C++ WarpX interface (see _libwarpx.LibWarpX) as an extension to @@ -2836,6 +3011,12 @@ def init(self, kw): self.checkpoint_signals = kw.pop("warpx_checkpoint_signals", None) self.numprocs = kw.pop("warpx_numprocs", None) + self.reduced_diags_path = kw.pop("warpx_reduced_diags_path", None) + self.reduced_diags_extension = kw.pop("warpx_reduced_diags_extension", None) + self.reduced_diags_intervals = kw.pop("warpx_reduced_diags_intervals", None) + self.reduced_diags_separator = kw.pop("warpx_reduced_diags_separator", None) + self.reduced_diags_precision = kw.pop("warpx_reduced_diags_precision", None) + self.inputs_initialized = False self.warpx_initialized = False @@ -2902,12 +3083,19 @@ def initialize_inputs(self): pywarpx.warpx.numprocs = self.numprocs + reduced_diags = pywarpx.warpx.get_bucket("reduced_diags") + reduced_diags.path = self.reduced_diags_path + reduced_diags.extension = self.reduced_diags_extension + reduced_diags.intervals = self.reduced_diags_intervals + reduced_diags.separator = self.reduced_diags_separator + reduced_diags.precision = self.reduced_diags_precision + particle_shape = self.particle_shape for s in self.species: if s.particle_shape is not None: - assert ( - particle_shape is None or particle_shape == s.particle_shape - ), Exception("WarpX only supports one particle shape for all species") + assert particle_shape is None or particle_shape == s.particle_shape, ( + Exception("WarpX only supports one particle shape for all species") + ) # --- If this was set for any species, use that value. particle_shape = s.particle_shape @@ -3878,7 +4066,7 @@ class ReducedDiagnostic(picmistandard.base._ClassWithInit, WarpXDiagnosticBase): species: species instance The name of the species for which to calculate the diagnostic, required for - diagnostic types 'BeamRelevant', 'ParticleHistogram', and 'ParticleExtrema' + diagnostic types 'BeamRelevant', 'ParticleHistogram', 'ParticleHistogram2D', and 'ParticleExtrema' bin_number: integer For diagnostic type 'ParticleHistogram', the number of bins used for the histogram @@ -3896,7 +4084,34 @@ class ReducedDiagnostic(picmistandard.base._ClassWithInit, WarpXDiagnosticBase): For diagnostic type 'ParticleHistogram', the function evaluated to produce the histogram data filter_function: string, optional - For diagnostic type 'ParticleHistogram', the function to filter whether particles are included in the histogram + For diagnostic types 'ParticleHistogram' and 'ParticleHistogram2D', the function to filter whether particles are included in the histogram + + bin_max_abs: float + For diagnostic type 'ParticleHistogram2D', the maximum value of the bins for the abscissa axis. + + bin_max_ord: float + For diagnostic type 'ParticleHistogram2D', the maximum value of the bins for the ordinate axis. + + bin_min_abs: float + For diagnostic type 'ParticleHistogram2D', the minimum value of the bins for the abscissa axis. + + bin_min_ord: float + For diagnostic type 'ParticleHistogram2D', the minimum value of the bins for the ordinate axis. + + bin_number_abs: integer + For diagnostic type 'ParticleHistogram2D', the number of bins used for the histogram for the abscissa axis. + + bin_number_ord: integer + For diagnostic type 'ParticleHistogram2D', the number of bins used for the histogram for the ordinate axis. + + histogram_function_abs: string + For diagnostic type 'ParticleHistogram2D', the histogram function for the abscissa axis. + + histogram_function_ord: string + For diagnostic type 'ParticleHistogram2D', the histogram function for the ordinate axis. + + value_function: string, optional + For diagnostic type 'ParticleHistogram2D', the expression for the weight used to calculate the histogram. reduced_function: string For diagnostic type 'FieldReduction', the function of the fields to evaluate @@ -3943,7 +4158,7 @@ def __init__( self, diag_type, name=None, - period=1, + period=None, path=None, extension=None, separator=None, @@ -3968,6 +4183,7 @@ def __init__( "FieldEnergy", "FieldMomentum", "FieldMaximum", + "FieldPoyntingFlux", "RhoMaximum", "ParticleNumber", "LoadBalanceCosts", @@ -3978,6 +4194,7 @@ def __init__( self._species_reduced_diagnostics = [ "BeamRelevant", "ParticleHistogram", + "ParticleHistogram2D", "ParticleExtrema", ] @@ -3988,6 +4205,8 @@ def __init__( self.species = species.name if self.type == "ParticleHistogram": kw = self._handle_particle_histogram(**kw) + elif self.type == "ParticleHistogram2D": + kw = self._handle_particle_histogram2d(**kw) elif self.type == "FieldProbe": kw = self._handle_field_probe(**kw) elif self.type == "FieldReduction": @@ -3996,7 +4215,7 @@ def __init__( kw = self._handle_charge_on_eb(**kw) else: raise RuntimeError( - f"{self.type} reduced diagnostic is not yet supported " "in pywarpx." + f"{self.type} reduced diagnostic is not yet supported in pywarpx." ) self.handle_init(kw) @@ -4065,6 +4284,44 @@ def _handle_particle_histogram(self, **kw): return kw + def _handle_particle_histogram2d(self, **kw): + self.bin_number_abs = kw.pop("bin_number_abs") + self.bin_number_ord = kw.pop("bin_number_ord") + self.bin_min_abs = kw.pop("bin_min_abs") + self.bin_max_abs = kw.pop("bin_max_abs") + self.bin_min_ord = kw.pop("bin_min_ord") + self.bin_max_ord = kw.pop("bin_max_ord") + histogram_function_abs = kw.pop("histogram_function_abs") + histogram_function_ord = kw.pop("histogram_function_ord") + self.__setattr__( + "histogram_function_abs(t,x,y,z,ux,uy,uz,w)", histogram_function_abs + ) + self.__setattr__( + "histogram_function_ord(t,x,y,z,ux,uy,uz,w)", histogram_function_ord + ) + + filter_function = kw.pop("filter_function", None) + value_function = kw.pop("value_function", None) + + self.__setattr__("filter_function(t,x,y,z,ux,uy,uz,w)", filter_function) + self.__setattr__("value_function(t,x,y,z,ux,uy,uz,w)", value_function) + + # Check the function expressions for constants + for k in list(kw.keys()): + if any( + re.search(r"\b%s\b" % k, expr) + for expr in [ + histogram_function_abs, + histogram_function_ord, + filter_function, + value_function, + ] + if expr is not None + ): + self.user_defined_kw[k] = kw.pop(k) + + return kw + def _handle_field_reduction(self, **kw): self.reduction_type = kw.pop("reduction_type") reduced_function = kw.pop("reduced_function") diff --git a/Python/setup.py b/Python/setup.py index c0e38baced2..e0ec6c98a7d 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -65,12 +65,12 @@ setup( name="pywarpx", - version="24.10", + version="25.02", packages=["pywarpx"], package_dir={"pywarpx": "pywarpx"}, description="""Wrapper of WarpX""", package_data=package_data, - install_requires=["numpy", "picmistandard==0.31.0", "periodictable"], - python_requires=">=3.8", + install_requires=["numpy", "picmistandard==0.33.0", "periodictable"], + python_requires=">=3.8", # left for CI, truly ">=3.9" zip_safe=False, ) diff --git a/Regression/Checksum/benchmarks_json/test_1d_fel.json b/Regression/Checksum/benchmarks_json/test_1d_fel.json index 2bd9c1fad80..ffcc97fa057 100644 --- a/Regression/Checksum/benchmarks_json/test_1d_fel.json +++ b/Regression/Checksum/benchmarks_json/test_1d_fel.json @@ -1,31 +1,31 @@ { "lev=0": { "Bx": 0.0, - "By": 514.5044890273722, + "By": 473.98537926589177, "Bz": 0.0, - "Ex": 154245109024.33972, + "Ex": 142097845843.78326, "Ey": 0.0, "Ez": 0.0, - "jx": 1161126105.5594487, + "jx": 1260205974.7220135, "jy": 0.0, "jz": 0.0 }, "electrons": { "particle_position_x": 0.0, "particle_position_y": 0.0, - "particle_position_z": 13607.569953355982, - "particle_momentum_x": 3.095483353687591e-19, + "particle_position_z": 13607.572916093213, + "particle_momentum_x": 3.2646797960476606e-19, "particle_momentum_y": 0.0, - "particle_momentum_z": 1.5419514460764825e-16, + "particle_momentum_z": 1.541338620507345e-16, "particle_weight": 1349823909946836.0 }, "positrons": { "particle_position_x": 0.0, "particle_position_y": 0.0, - "particle_position_z": 13607.569953355982, - "particle_momentum_x": 3.095483353687591e-19, + "particle_position_z": 13607.572916093213, + "particle_momentum_x": 3.2646797960476606e-19, "particle_momentum_y": 0.0, - "particle_momentum_z": 1.5419514460764825e-16, + "particle_momentum_z": 1.541338620507345e-16, "particle_weight": 1349823909946836.0 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_1d_laser_injection_implicit.json b/Regression/Checksum/benchmarks_json/test_1d_laser_injection_implicit.json new file mode 100644 index 00000000000..a89d6ccc2d4 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_1d_laser_injection_implicit.json @@ -0,0 +1,13 @@ +{ + "lev=0": { + "Bx": 374596.7817425552, + "By": 374596.7817425552, + "Bz": 0.0, + "Ex": 111502789524279.0, + "Ey": 111502789524279.0, + "Ez": 0.0, + "jx": 73098054407.2772, + "jy": 73098054407.2772, + "jz": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_1d_semi_implicit_picard.json b/Regression/Checksum/benchmarks_json/test_1d_semi_implicit_picard.json index 2c9859b037d..758db4355ec 100644 --- a/Regression/Checksum/benchmarks_json/test_1d_semi_implicit_picard.json +++ b/Regression/Checksum/benchmarks_json/test_1d_semi_implicit_picard.json @@ -1,7 +1,7 @@ { "lev=0": { - "Bx": 3559.0541122456157, - "By": 1685.942868827529, + "Bx": 3625.566538877196, + "By": 1684.1769211109035, "Bz": 0.0, "Ex": 796541204346.5195, "Ey": 961740397927.6577, diff --git a/Regression/Checksum/benchmarks_json/test_2d_collision_xz_picmi.json b/Regression/Checksum/benchmarks_json/test_2d_collision_xz_picmi.json new file mode 100644 index 00000000000..5407fe62374 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_collision_xz_picmi.json @@ -0,0 +1,29 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 0.0, + "Bz": 0.0, + "Ex": 0.0, + "Ey": 0.0, + "Ez": 0.0, + "jx": 0.0, + "jy": 0.0, + "jz": 0.0 + }, + "electron": { + "particle_momentum_x": 1.0340540111403247e-19, + "particle_momentum_y": 1.0154008257709287e-19, + "particle_momentum_z": 1.0325278275532687e-19, + "particle_position_x": 2667286.170170416, + "particle_position_y": 2647299.0368030528, + "particle_weight": 1.7256099431746894e+26 + }, + "ion": { + "particle_momentum_x": 2.489595454855792e-19, + "particle_momentum_y": 2.295864697447754e-19, + "particle_momentum_z": 2.2800373850644785e-19, + "particle_position_x": 2657799.867468604, + "particle_position_y": 2664764.1491634008, + "particle_weight": 1.7256099431746894e+26 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_comoving_psatd_hybrid.json b/Regression/Checksum/benchmarks_json/test_2d_comoving_psatd_hybrid.json index 8b03899369b..930d48ed713 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_comoving_psatd_hybrid.json +++ b/Regression/Checksum/benchmarks_json/test_2d_comoving_psatd_hybrid.json @@ -1,38 +1,38 @@ { "lev=0": { - "Bx": 1118808.3686978193, - "By": 3248970.5506422943, - "Bz": 280612.7921641442, - "Ex": 975536649649286.1, - "Ey": 402861835403418.1, - "Ez": 159049265640492.28, - "jx": 2.9996888133195436e+16, - "jy": 8.866654944519546e+16, - "jz": 3.164008885453435e+17, - "rho": 1059988299.6088305 - }, - "ions": { - "particle_momentum_x": 1.6150513873065298e-18, - "particle_momentum_y": 2.233426695677123e-18, - "particle_momentum_z": 4.279249529993671e-13, - "particle_position_x": 1.4883816864183497, - "particle_position_y": 16.452386504127254, - "particle_weight": 1.234867369440658e+18 + "Bx": 1118808.3708538802, + "By": 3248949.0437452313, + "Bz": 280612.7768961371, + "Ex": 975530336896144.1, + "Ey": 402861838033488.6, + "Ez": 159049784131625.12, + "jx": 2.9997142632475216e+16, + "jy": 8.866655055001146e+16, + "jz": 3.163953981093208e+17, + "rho": 1059970922.1974506 }, "electrons": { - "particle_momentum_x": 7.058167362825288e-19, - "particle_momentum_y": 2.204239326446281e-18, - "particle_momentum_z": 2.530521998715408e-16, - "particle_position_x": 1.5006581263609764, - "particle_position_y": 16.454388313398017, + "particle_momentum_x": 7.058252826278211e-19, + "particle_momentum_y": 2.204239315713169e-18, + "particle_momentum_z": 2.530521235191952e-16, + "particle_position_x": 1.5006579649318788, + "particle_position_y": 16.454388304724286, "particle_weight": 1.234867020725368e+18 }, "beam": { - "particle_momentum_x": 6.869222298759882e-19, - "particle_momentum_y": 4.374719809060106e-19, - "particle_momentum_z": 6.4523206583503136e-18, - "particle_position_x": 0.001290816359726098, - "particle_position_y": 0.3586691102823157, + "particle_momentum_x": 6.88879318082965e-19, + "particle_momentum_y": 4.37466174746362e-19, + "particle_momentum_z": 6.4299296650127095e-18, + "particle_position_x": 0.0012936414423443238, + "particle_position_y": 0.3587414953163842, "particle_weight": 3120754537230.3823 + }, + "ions": { + "particle_momentum_x": 1.6150618501530563e-18, + "particle_momentum_y": 2.2334266731098355e-18, + "particle_momentum_z": 4.279249530957972e-13, + "particle_position_x": 1.488381686539698, + "particle_position_y": 16.4523865041322, + "particle_weight": 1.234867369440658e+18 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_dirichlet_bc_picmi.json b/Regression/Checksum/benchmarks_json/test_2d_dirichlet_bc_picmi.json new file mode 100644 index 00000000000..41567dc3bf2 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_dirichlet_bc_picmi.json @@ -0,0 +1,5 @@ +{ + "lev=0": { + "phi": 10817.97280547637 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_dive_cleaning.json b/Regression/Checksum/benchmarks_json/test_2d_dive_cleaning.json index 71e147cb1f7..06216490281 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_dive_cleaning.json +++ b/Regression/Checksum/benchmarks_json/test_2d_dive_cleaning.json @@ -1,27 +1,21 @@ { - "beam": { - "particle_Bx": 0.0, - "particle_By": 1.4229748768905527e-19, - "particle_Bz": 0.0, - "particle_Ex": 210305.84591470752, - "particle_Ey": 0.0, - "particle_Ez": 210741.1714121227, - "particle_momentum_x": 1.111019933689776e-26, - "particle_momentum_y": 0.0, - "particle_momentum_z": 1.113270980745195e-26, - "particle_position_x": 0.03183627816789909, - "particle_position_y": 0.03171922054171794, - "particle_weight": 31207.545372303823 - }, "lev=0": { "Bx": 0.0, - "By": 1.5468538800972258e-20, + "By": 1.2286794953440962e-20, "Bz": 0.0, - "Ex": 8533.638650013556, + "Ex": 8214.62652670017, "Ey": 0.0, - "Ez": 8534.98921988922, + "Ez": 8214.876065863818, "jx": 0.0, "jy": 0.0, "jz": 0.0 + }, + "beam": { + "particle_momentum_x": 1.580805184936455e-26, + "particle_momentum_y": 0.0, + "particle_momentum_z": 1.5759037267515492e-26, + "particle_position_x": 0.0319918174870481, + "particle_position_y": 0.03196785829873647, + "particle_weight": 31207.545372303823 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_cube.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_cube.json index a3e609bd9a9..dbb5ffa39ae 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_cube.json +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_cube.json @@ -3,8 +3,8 @@ "Bx": 9.263694545408503e-05, "By": 0.00031905198933489145, "Bz": 7.328424783762594e-05, - "Ex": 8553.906698053046, + "Ex": 8553.90669811286, "Ey": 60867.04830538045, - "Ez": 8.439422682267567e-07 + "Ez": 4.223902107031194e-06 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_1.json new file mode 100644 index 00000000000..de3d125c744 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_1.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 3.059581906777539e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_2.json new file mode 100644 index 00000000000..481aba1f36b --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_2.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 2.4521053721245334e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_3.json new file mode 100644 index 00000000000..82b6c6849ac --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_em_particle_absorption_sh_factor_3.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 2.2059346534892452e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_1.json new file mode 100644 index 00000000000..632c48df963 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_1.json @@ -0,0 +1,30 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 2.3792992316172512e-15, + "Bz": 0.0 , + "Ex": 6.177046470842443e-07, + "Ey": 0.0, + "Ez": 7.259396011803518e-07, + "divE": 2.809306467366024e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_2.json new file mode 100644 index 00000000000..9112c931b55 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_2.json @@ -0,0 +1,30 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 2.3948084603369097e-15, + "Bz": 0.0, + "Ex": 6.747158562891953e-07, + "Ey": 0.0, + "Ez": 5.541309886315263e-07, + "divE": 2.091715826275267e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_3.json new file mode 100644 index 00000000000..8d6ddf169af --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_embedded_boundary_removal_depth_sh_factor_3.json @@ -0,0 +1,31 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 2.379299231617251e-15, + "Bz": 0.0, + "Ex": 6.177046470842443e-07, + "Ey": 0.0, + "Ez": 7.259396011803522e-07, + "divE": 2.8093064673660275e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } + } + diff --git a/Regression/Checksum/benchmarks_json/test_2d_field_probe.json b/Regression/Checksum/benchmarks_json/test_2d_field_probe.json index cb82acfc067..8aabe6c8301 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_field_probe.json +++ b/Regression/Checksum/benchmarks_json/test_2d_field_probe.json @@ -1,10 +1,10 @@ { "lev=0": { "Bx": 0.0, - "By": 126826.78487921853, + "By": 123510.69657444415, "Bz": 0.0, - "Ex": 32517064310550.266, + "Ex": 31206368949280.34, "Ey": 0.0, - "Ez": 17321323003697.61 + "Ez": 16921005306450.537 } -} +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_flux_injection_from_eb.json b/Regression/Checksum/benchmarks_json/test_2d_flux_injection_from_eb.json index dd489f16e05..d4fe12f759f 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_flux_injection_from_eb.json +++ b/Regression/Checksum/benchmarks_json/test_2d_flux_injection_from_eb.json @@ -1,11 +1,11 @@ { "lev=0": {}, "electron": { - "particle_momentum_x": 6.990772711451971e-19, - "particle_momentum_y": 5.4131306169803364e-20, - "particle_momentum_z": 6.997294931789925e-19, - "particle_position_x": 35518.95120597846, - "particle_position_y": 35517.855675902414, - "particle_weight": 1.25355e-07 + "particle_momentum_x": 1.4013860393698154e-18, + "particle_momentum_y": 1.0934049057929508e-19, + "particle_momentum_z": 1.4066623146535866e-18, + "particle_position_x": 72129.9049362857, + "particle_position_y": 72178.76505490103, + "particle_weight": 6.279375e-08 } } diff --git a/Regression/Checksum/benchmarks_json/test_2d_galilean_psatd_hybrid.json b/Regression/Checksum/benchmarks_json/test_2d_galilean_psatd_hybrid.json index dd56f8170a9..a163d063134 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_galilean_psatd_hybrid.json +++ b/Regression/Checksum/benchmarks_json/test_2d_galilean_psatd_hybrid.json @@ -1,38 +1,38 @@ { "lev=0": { - "Bx": 1086729.9718613266, - "By": 2886554.482275311, - "Bz": 264259.55093734514, - "Ex": 867387781289915.2, - "Ey": 392666724461952.5, - "Ez": 146897592531660.03, - "jx": 2.702866174672266e+16, - "jy": 8.615938361747776e+16, - "jz": 2.7329155817806224e+17, - "rho": 915945723.7934376 + "Bx": 1086729.9879225595, + "By": 2886531.8361456757, + "Bz": 264259.55266959703, + "Ex": 867381192933999.0, + "Ey": 392666738858258.7, + "Ez": 146898030091111.84, + "jx": 2.702892158065604e+16, + "jy": 8.615938867870698e+16, + "jz": 2.7328506574305683e+17, + "rho": 915924567.6956444 + }, + "beam": { + "particle_momentum_x": 7.006049777955171e-19, + "particle_momentum_y": 4.374916846096741e-19, + "particle_momentum_z": 6.173292885825711e-18, + "particle_position_x": 0.0016046573777589298, + "particle_position_y": 0.35899824939059793, + "particle_weight": 3120754537230.3823 }, "ions": { - "particle_momentum_x": 1.4394902513923003e-18, - "particle_momentum_y": 1.5967629157922875e-18, - "particle_momentum_z": 4.287340658051679e-13, - "particle_position_x": 1.4911814217142487, - "particle_position_y": 16.521964978771, + "particle_momentum_x": 1.4395010524514718e-18, + "particle_momentum_y": 1.596762923413923e-18, + "particle_momentum_z": 4.2873406589510426e-13, + "particle_position_x": 1.4911814218338595, + "particle_position_y": 16.52196497877563, "particle_weight": 1.2372405194129536e+18 }, "electrons": { - "particle_momentum_x": 6.240933687389075e-19, - "particle_momentum_y": 1.5790611427694247e-18, - "particle_momentum_z": 2.5064357834741096e-16, - "particle_position_x": 1.501413766926399, - "particle_position_y": 16.523781713952324, + "particle_momentum_x": 6.241019323257125e-19, + "particle_momentum_y": 1.5790611706036782e-18, + "particle_momentum_z": 2.5064350576384073e-16, + "particle_position_x": 1.501413593465263, + "particle_position_y": 16.52378170448397, "particle_weight": 1.2372401466086835e+18 - }, - "beam": { - "particle_momentum_x": 7.000932845220306e-19, - "particle_momentum_y": 4.374936866729326e-19, - "particle_momentum_z": 6.194468548032543e-18, - "particle_position_x": 0.0016030835496557787, - "particle_position_y": 0.3589262705964349, - "particle_weight": 3120754537230.3823 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_laser_acceleration_boosted.json b/Regression/Checksum/benchmarks_json/test_2d_laser_acceleration_boosted.json index dd59536ad37..b8592e87c82 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_laser_acceleration_boosted.json +++ b/Regression/Checksum/benchmarks_json/test_2d_laser_acceleration_boosted.json @@ -1,38 +1,38 @@ { "lev=0": { - "Bx": 4818955.480797943, - "By": 1752.8025638791275, - "Bz": 14516.212782554387, - "Ex": 2366115503598.9224, - "Ey": 1446112025635674.2, - "Ez": 21864189507357.867, - "jx": 1996366349775593.5, - "jy": 5.312583827155926e+16, - "jz": 2.0491352624508764e+16, - "rho": 68443961.71852128 + "Bx": 4818955.485307051, + "By": 1752.8020185365554, + "Bz": 14516.212849649737, + "Ex": 2366115529014.2324, + "Ey": 1446112026998942.5, + "Ez": 21864189485739.55, + "jx": 1996366372981548.5, + "jy": 5.312583836344946e+16, + "jz": 2.049135259966133e+16, + "rho": 68443961.64027263 + }, + "beam": { + "particle_momentum_x": 3.535736052190267e-19, + "particle_momentum_y": 4.363217976210739e-19, + "particle_momentum_z": 5.658515465395611e-17, + "particle_position_x": 0.008314855161869274, + "particle_position_y": 1.170433573157185, + "particle_weight": 62415090744.60765 }, "electrons": { - "particle_momentum_x": 2.2135945391319113e-23, - "particle_momentum_y": 2.8224559499558413e-22, - "particle_momentum_z": 5.260626010214114e-22, - "particle_position_x": 0.010800577787628052, - "particle_position_y": 0.2111506062831815, + "particle_momentum_x": 2.213594541883545e-23, + "particle_momentum_y": 2.8224559261549207e-22, + "particle_momentum_z": 5.260626007410037e-22, + "particle_position_x": 0.010800577787636243, + "particle_position_y": 0.2111506062831794, "particle_weight": 4.121554826246186e+16 }, "ions": { - "particle_momentum_x": 6.248472277246885e-23, - "particle_momentum_y": 4.449097689427654e-22, - "particle_momentum_z": 5.768168724998047e-22, + "particle_momentum_x": 6.24847229412907e-23, + "particle_momentum_y": 4.449097671673176e-22, + "particle_momentum_z": 5.768168722032957e-22, "particle_position_x": 0.010800001678510512, "particle_position_y": 0.21114947608115425, "particle_weight": 4.121554826246186e+16 - }, - "beam": { - "particle_momentum_x": 3.5357456351701565e-19, - "particle_momentum_y": 4.363391839372122e-19, - "particle_momentum_z": 5.658606416951653e-17, - "particle_position_x": 0.008314723025211468, - "particle_position_y": 1.1704335743854242, - "particle_weight": 62415090744.60765 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_2d_laser_injection_implicit.json b/Regression/Checksum/benchmarks_json/test_2d_laser_injection_implicit.json new file mode 100644 index 00000000000..b77b951e92a --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_laser_injection_implicit.json @@ -0,0 +1,13 @@ +{ + "lev=0": { + "Bx": 19699314.38858362, + "By": 101297372.8536657, + "Bz": 39796093.072294116, + "Ex": 1.3881256464656438e+16, + "Ey": 1.322100107139857e+16, + "Ez": 2.6833518029118908e+16, + "jx": 3.669364941403736e+16, + "jy": 3.669364586262695e+16, + "jz": 7.338729883115621e+16 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_maxwell_hybrid_qed_solver.json b/Regression/Checksum/benchmarks_json/test_2d_maxwell_hybrid_qed_solver.json index 9f7b7f64dcd..a5c1c1fd700 100644 --- a/Regression/Checksum/benchmarks_json/test_2d_maxwell_hybrid_qed_solver.json +++ b/Regression/Checksum/benchmarks_json/test_2d_maxwell_hybrid_qed_solver.json @@ -1,13 +1,13 @@ { "lev=0": { - "Bx": 3.543966469013954e-05, + "Bx": 3.5439667773344274e-05, "By": 0.0, - "Bz": 5.103535813972088e-12, + "Bz": 0.0, "Ex": 0.0, - "Ey": 6553600000.005218, + "Ey": 6553599999.996383, "Ez": 0.0, "jx": 0.0, "jy": 0.0, "jz": 0.0 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_picmi.json b/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_picmi.json new file mode 100644 index 00000000000..92a1ccbe638 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_picmi.json @@ -0,0 +1,14 @@ +{ + "lev=0": { + "phi": 0.0023065875621041164 + }, + "electrons": { + "particle_momentum_x": 1.1623026977941542e-25, + "particle_momentum_y": 1.0012020618770149e-25, + "particle_momentum_z": 1.0768794697418634e-25, + "particle_newPid": 750.0, + "particle_position_x": 2.4984316660445582, + "particle_position_y": 2.498475649375752, + "particle_weight": 300.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_unique_picmi.json b/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_unique_picmi.json new file mode 100644 index 00000000000..d1630437fe0 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_particle_attr_access_unique_picmi.json @@ -0,0 +1,14 @@ +{ + "lev=0": { + "phi": 0.004613047318603685 + }, + "electrons": { + "particle_momentum_x": 2.285288009419423e-25, + "particle_momentum_y": 2.0816449298979767e-25, + "particle_momentum_z": 2.0646896248001752e-25, + "particle_newPid": 1500.0, + "particle_position_x": 4.499791671680002, + "particle_position_y": 4.499957554820931, + "particle_weight": 600.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator.json b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator.json new file mode 100644 index 00000000000..b389856e66b --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator.json @@ -0,0 +1,13 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 0.3605690508580849, + "Bz": 0.0, + "Ex": 37101418.32484252, + "Ey": 0.0, + "Ez": 108228802.9434361, + "jx": 0.0, + "jy": 0.0, + "jz": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit.json b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit.json new file mode 100644 index 00000000000..fcb3081f6ae --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit.json @@ -0,0 +1,14 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 0.35907571934346943, + "Bz": 0.0, + "Ex": 36840284.366667606, + "Ey": 0.0, + "Ez": 107777138.0847348, + "jx": 0.0, + "jy": 0.0, + "jz": 0.0 + } +} + diff --git a/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit_restart.json b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit_restart.json new file mode 100644 index 00000000000..fcb3081f6ae --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_pec_field_insulator_implicit_restart.json @@ -0,0 +1,14 @@ +{ + "lev=0": { + "Bx": 0.0, + "By": 0.35907571934346943, + "Bz": 0.0, + "Ex": 36840284.366667606, + "Ey": 0.0, + "Ez": 107777138.0847348, + "jx": 0.0, + "jy": 0.0, + "jz": 0.0 + } +} + diff --git a/Regression/Checksum/benchmarks_json/test_2d_qed_breit_wheeler_opmd.json b/Regression/Checksum/benchmarks_json/test_2d_qed_breit_wheeler_opmd.json new file mode 100644 index 00000000000..fdfddfcbf2d --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_qed_breit_wheeler_opmd.json @@ -0,0 +1,134 @@ +{ + "lev=0": { + "Ex": 0.0 + }, + "dummy_phot": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "ele1": { + "particle_opticalDepthQSR": 94805.7653371546, + "particle_position_x": 0.02366929620831116, + "particle_position_y": 0.0, + "particle_position_z": 0.023729402832031253, + "particle_momentum_x": 2.6017428344962994e-14, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 904932.0220947266 + }, + "ele2": { + "particle_opticalDepthQSR": 11848.411715651348, + "particle_position_x": 0.00294089697265625, + "particle_position_y": 0.0, + "particle_position_z": 0.00291261572265625, + "particle_momentum_x": 0.0, + "particle_momentum_y": 8.023686137822937e-15, + "particle_momentum_z": 0.0, + "particle_weight": 112028.12194824219 + }, + "ele3": { + "particle_opticalDepthQSR": 126169.82836793675, + "particle_position_x": 0.03160814697265625, + "particle_position_y": 0.0, + "particle_position_z": 0.03157382483413338, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 1.7279204307644868e-13, + "particle_weight": 1203489.3035888672 + }, + "ele4": { + "particle_opticalDepthQSR": 49124.07007571301, + "particle_position_x": 0.012249532599865704, + "particle_position_y": 0.0, + "particle_position_z": 0.012296328078458279, + "particle_momentum_x": 3.86289566432756e-13, + "particle_momentum_y": 3.86289566432756e-13, + "particle_momentum_z": 3.86289566432756e-13, + "particle_weight": 467967.9870605469 + }, + "p1": { + "particle_opticalDepthBW": 871455.4785435478, + "particle_position_x": 0.2384708675227609, + "particle_position_y": 0.0, + "particle_position_z": 0.23841459716796876, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 9095067.977905273 + }, + "p2": { + "particle_opticalDepthBW": 1026305.8359152814, + "particle_position_x": 0.25920310302734373, + "particle_position_y": 0.0, + "particle_position_z": 0.25923138427734393, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 9887971.878051758 + }, + "p3": { + "particle_opticalDepthBW": 819556.3040882011, + "particle_position_x": 0.23053585302734383, + "particle_position_y": 0.0, + "particle_position_z": 0.230565112772128, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 8796510.696411133 + }, + "p4": { + "particle_opticalDepthBW": 953481.8671852223, + "particle_position_x": 0.24989221486908522, + "particle_position_y": 0.0, + "particle_position_z": 0.24984575334030557, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 9532032.012939453 + }, + "pos1": { + "particle_opticalDepthQSR": 95351.53381764909, + "particle_position_x": 0.02366929620831116, + "particle_position_y": 0.0, + "particle_position_z": 0.023729402832031253, + "particle_momentum_x": 2.580947118885758e-14, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 904932.0220947266 + }, + "pos2": { + "particle_opticalDepthQSR": 11715.614695181783, + "particle_position_x": 0.00294089697265625, + "particle_position_y": 0.0, + "particle_position_z": 0.00291261572265625, + "particle_momentum_x": 0.0, + "particle_momentum_y": 8.016397398195943e-15, + "particle_momentum_z": 0.0, + "particle_weight": 112028.12194824219 + }, + "pos3": { + "particle_opticalDepthQSR": 126049.551252123, + "particle_position_x": 0.03160814697265625, + "particle_position_y": 0.0, + "particle_position_z": 0.03157382483413338, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 1.718369575300312e-13, + "particle_weight": 1203489.3035888672 + }, + "pos4": { + "particle_opticalDepthQSR": 48953.578114257085, + "particle_position_x": 0.012249532599865704, + "particle_position_y": 0.0, + "particle_position_z": 0.012296328078458279, + "particle_momentum_x": 3.873971285219934e-13, + "particle_momentum_y": 3.873971285219934e-13, + "particle_momentum_z": 3.873971285219934e-13, + "particle_weight": 467967.9870605469 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_jfnk_vandb_filtered.json b/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_jfnk_vandb_filtered.json new file mode 100644 index 00000000000..d342c49e2fd --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_jfnk_vandb_filtered.json @@ -0,0 +1,31 @@ +{ + "lev=0": { + "Bx": 65625.24877705125, + "By": 71913.65275407257, + "Bz": 59768.79247890749, + "Ex": 56341360261928.086, + "Ey": 13926508614721.855, + "Ez": 56508162715968.17, + "divE": 5.5816922509658905e+22, + "jx": 1.8114330881270456e+19, + "jy": 2.0727708668063334e+19, + "jz": 1.7843765469944717e+19, + "rho": 494213515033.04443 + }, + "electrons": { + "particle_momentum_x": 4.888781979240524e-19, + "particle_momentum_y": 4.879904653089102e-19, + "particle_momentum_z": 4.878388335258947e-19, + "particle_position_x": 0.0042514822919144084, + "particle_position_y": 0.0042515394083575886, + "particle_weight": 2823958719279159.5 + }, + "protons": { + "particle_momentum_x": 2.0873319751377048e-17, + "particle_momentum_y": 2.0858882863041667e-17, + "particle_momentum_z": 2.0877426824914187e-17, + "particle_position_x": 0.004251275869325256, + "particle_position_y": 0.0042512738905204584, + "particle_weight": 2823958719279159.5 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_strang_psatd.json b/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_strang_psatd.json new file mode 100644 index 00000000000..5281804abba --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_2d_theta_implicit_strang_psatd.json @@ -0,0 +1,31 @@ +{ + "lev=0": { + "Bx": 60642.062637340816, + "By": 89855.09371265332, + "Bz": 54561.47120738846, + "Ex": 81536346169528.28, + "Ey": 13888711042388.54, + "Ez": 86853122458391.0, + "divE": 9.492653438830812e+22, + "jx": 2.5941826848709296e+19, + "jy": 2.9929071160915993e+19, + "jz": 2.692985701872205e+19, + "rho": 851978517887.51 + }, + "electrons": { + "particle_momentum_x": 4.864385990952573e-19, + "particle_momentum_y": 4.879723483907468e-19, + "particle_momentum_z": 4.865564630727981e-19, + "particle_position_x": 0.004250851253052539, + "particle_position_y": 0.0042513622554793, + "particle_weight": 2823958719279159.5 + }, + "protons": { + "particle_momentum_x": 2.0934469726422704e-17, + "particle_momentum_y": 2.0929630794865952e-17, + "particle_momentum_z": 2.093085625201003e-17, + "particle_position_x": 0.004251276208274589, + "particle_position_y": 0.004251274670600805, + "particle_weight": 2823958719279159.5 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_diff_lumi_diag_photons.json b/Regression/Checksum/benchmarks_json/test_3d_diff_lumi_diag_photons.json index 09b2031cdd2..86659bafd79 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_diff_lumi_diag_photons.json +++ b/Regression/Checksum/benchmarks_json/test_3d_diff_lumi_diag_photons.json @@ -1,24 +1,25 @@ { "lev=0": { - "rho_beam1": 656097367.2335038, - "rho_beam2": 656097367.2335038 + "rho_beam1": 0.0, + "rho_beam2": 0.0 }, - "beam1": { + "beam2": { "particle_momentum_x": 0.0, "particle_momentum_y": 0.0, - "particle_momentum_z": 1.7512476113279403e-11, + "particle_momentum_z": 1.7511853009715152e-11, "particle_position_x": 0.2621440000000001, - "particle_position_y": 0.005242880000000001, - "particle_position_z": 314572.79999473685, - "particle_weight": 11997744756.90957 + "particle_position_y": 0.005242880000000004, + "particle_position_z": 314572.8000000002, + "particle_weight": 11997744756.909575 }, - "beam2": { + "beam1": { "particle_momentum_x": 0.0, "particle_momentum_y": 0.0, - "particle_momentum_z": 1.7513431895752007e-11, + "particle_momentum_z": 1.75121641230803e-11, "particle_position_x": 0.2621440000000001, - "particle_position_y": 0.005242880000000001, - "particle_position_z": 314572.79999472946, + "particle_position_y": 0.005242880000000004, + "particle_position_z": 314572.8000000004, "particle_weight": 11997744756.909573 } -} \ No newline at end of file +} + diff --git a/Regression/Checksum/benchmarks_json/test_3d_dive_cleaning.json b/Regression/Checksum/benchmarks_json/test_3d_dive_cleaning.json index db23c26f9a7..b8206240500 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_dive_cleaning.json +++ b/Regression/Checksum/benchmarks_json/test_3d_dive_cleaning.json @@ -1,28 +1,22 @@ { - "beam": { - "particle_Bx": 1.6547943661629038e-20, - "particle_By": 1.7166945226626064e-20, - "particle_Bz": 1.851357799836734e-20, - "particle_Ex": 39363.91309372786, - "particle_Ey": 39331.17437154593, - "particle_Ez": 39396.18209787599, - "particle_momentum_x": 1.700384472207379e-27, - "particle_momentum_y": 1.69889110346099e-27, - "particle_momentum_z": 1.7017928140329036e-27, - "particle_position_x": 0.031880969779242374, - "particle_position_y": 0.03175704658379704, - "particle_position_z": 0.03183674192208247, - "particle_weight": 0.06241509074460764 - }, "lev=0": { - "Bx": 2.2090009624207165e-20, - "By": 2.2307246822783936e-20, - "Bz": 2.1967888687392684e-20, - "Ex": 8888.956516621029, - "Ey": 8838.45337149105, - "Ez": 8837.421045658291, + "Bx": 1.9159134471952935e-20, + "By": 1.8827238279614072e-20, + "Bz": 1.8885687211875642e-20, + "Ex": 8648.536817097653, + "Ey": 8613.089981021956, + "Ez": 8626.889465408336, "jx": 0.0, "jy": 0.0, "jz": 0.0 + }, + "beam": { + "particle_momentum_x": 2.3895400750846334e-27, + "particle_momentum_y": 2.3729444184823814e-27, + "particle_momentum_z": 2.390801909783316e-27, + "particle_position_x": 0.031866021988156114, + "particle_position_y": 0.032281276107277185, + "particle_position_z": 0.03185444043880588, + "particle_weight": 0.06241509074460764 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_eb_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_eb_picmi.json index ad0d2cee5a3..1f9f0a77b5a 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_eb_picmi.json +++ b/Regression/Checksum/benchmarks_json/test_3d_eb_picmi.json @@ -1,10 +1,10 @@ { "lev=0": { - "Bx": 148673.005859208, - "By": 148673.00585920806, - "Bz": 3371.758117878558, - "Ex": 55378581103426.71, - "Ey": 55378581103426.72, - "Ez": 68412803445328.25 + "Bx": 144495.08082507108, + "By": 144495.08082507114, + "Bz": 8481.958724628861, + "Ex": 54500496182517.92, + "Ey": 54500496182517.91, + "Ez": 70231240245509.39 } -} +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_effective_potential_electrostatic_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_effective_potential_electrostatic_picmi.json new file mode 100644 index 00000000000..b61da644114 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_effective_potential_electrostatic_picmi.json @@ -0,0 +1,15 @@ +{ + "lev=0": { + "Ex": 148992.08170563323, + "Ey": 148964.62980386653, + "Ez": 149085.76473996745, + "T_electrons": 279.2796849134268, + "T_ions": 32.09677271761641, + "jx": 31.077856013948246, + "jy": 31.425549493321245, + "jz": 31.424168300110658, + "phi": 2002.2518068289028, + "rho_electrons": 0.007909027251581852, + "rho_ions": 0.008266762306092332 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube.json index 58ee8806540..9563c52adbe 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube.json +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube.json @@ -1,10 +1,10 @@ { "lev=0": { - "Bx": 4.060477854092961e-18, + "Bx": 4.166971025838921e-18, "By": 0.006628374119786834, "Bz": 0.006628374119786834, - "Ex": 5102618.4711524295, - "Ey": 6.323754160591239e-05, - "Ez": 6.323754160591239e-05 + "Ex": 5102618.471153786, + "Ey": 1.4283859321773714e-05, + "Ez": 1.4283859321773714e-05 } -} +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube_macroscopic.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube_macroscopic.json index 8cc6af7cb93..67bdbea18ca 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube_macroscopic.json +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_cube_macroscopic.json @@ -1,10 +1,10 @@ { "lev=0": { - "Bx": 4.20930075273562e-18, + "Bx": 4.228863291892693e-18, "By": 0.005101824310293573, "Bz": 0.005101824310293573, - "Ex": 4414725.184731115, - "Ey": 6.32375413967707e-05, - "Ez": 6.32375413967707e-05 + "Ex": 4414725.184732471, + "Ey": 1.4283895626502055e-05, + "Ez": 1.4283895626502055e-05 } -} +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_1.json new file mode 100644 index 00000000000..d3e08d9723e --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_1.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 4.928354322096152e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_2.json new file mode 100644 index 00000000000..d3e08d9723e --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_2.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 4.928354322096152e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_3.json new file mode 100644 index 00000000000..23c03c7e7bc --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_em_particle_absorption_sh_factor_3.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 4.3355127342920327e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_1.json new file mode 100644 index 00000000000..109f5fb4d35 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_1.json @@ -0,0 +1,30 @@ +{ + "lev=0": { + "Bx": 3.835377401535272e-15, + "By": 7.634560527952392e-15, + "Bz": 7.670097149513554e-15, + "Ex": 1.837433604148419e-06, + "Ey": 1.4507850267928362e-06, + "Ez": 1.4325637523931794e-06, + "divE": 7.330866223540695e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_2.json new file mode 100644 index 00000000000..9ff91af6550 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_2.json @@ -0,0 +1,30 @@ +{ + "lev=0": { + "Bx": 2.3948084603369097e-15, + "By": 0.0, + "Bz": 6.747158562891953e-07, + "Ex": 0.0, + "Ey": 5.541309886315263e-07, + "Ez": 0.0, + "divE": 2.091715826275267e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_3.json new file mode 100644 index 00000000000..0e0cdf5eb0f --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_removal_depth_sh_factor_3.json @@ -0,0 +1,31 @@ +{ + "lev=0": { + "Bx": 2.9100687916345874e-15, + "By": 6.121275580503632e-15, + "Bz": 5.9043095451081354e-15, + "Ex": 1.4574231057224582e-06, + "Ey": 1.1648744803916206e-06, + "Ez": 1.16164257835401e-06, + "divE": 6.781029990295743e-07, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } + } + diff --git a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_rotated_cube.json b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_rotated_cube.json index b2b4aa569c1..118214948a5 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_rotated_cube.json +++ b/Regression/Checksum/benchmarks_json/test_3d_embedded_boundary_rotated_cube.json @@ -7,5 +7,4 @@ "Ey": 1.042254197269831e+04, "Ez": 1.040011664019071e+04 } -} - +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_flux_injection_from_eb.json b/Regression/Checksum/benchmarks_json/test_3d_flux_injection_from_eb.json index e947a8af07b..c1c888ff808 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_flux_injection_from_eb.json +++ b/Regression/Checksum/benchmarks_json/test_3d_flux_injection_from_eb.json @@ -1,12 +1,12 @@ { "lev=0": {}, "electron": { - "particle_momentum_x": 4.371688233196277e-18, - "particle_momentum_y": 4.368885079657374e-18, - "particle_momentum_z": 4.367429424105371e-18, - "particle_position_x": 219746.94401890738, - "particle_position_y": 219690.7015248918, - "particle_position_z": 219689.45580938633, - "particle_weight": 4.954974999999999e-07 + "particle_momentum_x": 1.7587772989573373e-17, + "particle_momentum_y": 1.7608560965806728e-17, + "particle_momentum_z": 1.7596701993624562e-17, + "particle_position_x": 902783.9285213391, + "particle_position_y": 902981.7980528818, + "particle_position_z": 902777.1246066706, + "particle_weight": 2.503818749999996e-07 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb.json b/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb.json index a1ec0b4c831..6415fc3e930 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb.json +++ b/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb.json @@ -1,21 +1,21 @@ { "lev=0": { - "Az": 11.358663326449284, - "Bx": 111.55929407644248, - "By": 111.55929407644244, - "Ex": 31257180402.55472, - "Ey": 31257180402.55473, - "jz": 1034841325.9848926, - "phi": 3143521213.0157924, - "rho": 3.449203918900721 + "Az": 11.358663299932457, + "Bx": 111.55929615203162, + "By": 111.55929615203165, + "Ex": 31463410849.74626, + "Ey": 31463410849.746258, + "jz": 1034841323.6861029, + "phi": 3164328318.15416, + "rho": 3.4565836983918676 }, "beam": { - "particle_momentum_x": 1.3604657334742729e-21, - "particle_momentum_y": 1.3604657334742772e-21, - "particle_momentum_z": 7.150873450281544e-16, - "particle_position_x": 11163.99997371537, - "particle_position_y": 11163.999973715368, - "particle_position_z": 131662.50031035842, + "particle_momentum_x": 1.3829464728617761e-21, + "particle_momentum_y": 1.3829464728617792e-21, + "particle_momentum_z": 7.150871807235339e-16, + "particle_position_x": 11163.99997715059, + "particle_position_y": 11163.999977150592, + "particle_position_z": 131662.5003102683, "particle_weight": 20895107655113.465 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb_picmi.json index abe91ac9e9d..2c99a4218c2 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb_picmi.json +++ b/Regression/Checksum/benchmarks_json/test_3d_magnetostatic_eb_picmi.json @@ -1,27 +1,27 @@ { + "lev=0": { + "Ax": 1.40889223759456e-05, + "Ay": 1.4088922375945606e-05, + "Az": 11.423480450267745, + "Bx": 112.23826705481486, + "By": 112.23826705481484, + "Bz": 0.00019199345672949735, + "Ex": 31557746267.686367, + "Ey": 31557746267.686363, + "Ez": 3339526660.3539834, + "jx": 1980.6549408566577, + "jy": 1980.6549408566577, + "jz": 1038931605.1197203, + "phi": 3171976204.251914, + "rho": 3.4840085919357926 + }, "beam": { - "particle_momentum_x": 1.3878812158350944e-21, - "particle_momentum_y": 1.387881215835094e-21, - "particle_momentum_z": 7.150872953138685e-16, - "particle_position_x": 11163.999973134894, - "particle_position_y": 11163.999973134896, - "particle_position_z": 131662.5003103311, + "particle_momentum_x": 1.4011190163358655e-21, + "particle_momentum_y": 1.401119016335865e-21, + "particle_momentum_z": 7.15087179293042e-16, + "particle_position_x": 11163.99997543546, + "particle_position_y": 11163.999975435456, + "particle_position_z": 131662.50031026747, "particle_weight": 20895107655113.465 - }, - "lev=0": { - "Ax": 1.408892468360627e-05, - "Ay": 1.4088924683606269e-05, - "Az": 11.423480469161868, - "Bx": 112.23826555908032, - "By": 112.2382655590803, - "Bz": 0.00019186770330025167, - "Ex": 31418238386.183773, - "Ey": 31418238386.183773, - "Ez": 3461330433.5026026, - "jx": 1961.0003914783667, - "jy": 1961.0003914783663, - "jz": 1038931606.7573991, - "phi": 3157908107.1102533, - "rho": 3.46977258905983 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_ohm_solver_cylinder_compression_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_ohm_solver_cylinder_compression_picmi.json new file mode 100644 index 00000000000..c61354de5a3 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_ohm_solver_cylinder_compression_picmi.json @@ -0,0 +1,20 @@ +{ + "lev=0": { + "Bx": 0.5334251406746063, + "By": 0.5318559382056761, + "Bz": 2252.108858363565, + "Ex": 10509826.248254433, + "Ey": 10512665.210439455, + "Ez": 8848.110632517377, + "rho": 384112.2912140535 + }, + "ions": { + "particle_momentum_x": 2.1612944051250247e-16, + "particle_momentum_y": 2.1618707843260381e-16, + "particle_momentum_z": 2.0513400435259629e-16, + "particle_position_x": 769864.2025705199, + "particle_position_y": 769908.6569665589, + "particle_position_z": 620721.1900338195, + "particle_weight": 1.008292384042714e+19 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver.json b/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver.json index af9ab3a0bdd..80561aaa4e1 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver.json +++ b/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver.json @@ -1,19 +1,19 @@ { "lev=0": { - "Bx": 100915933.446046, + "Bx": 100915933.44604117, "By": 157610622.18548763, - "Bz": 2.76973993530483e-13, - "Ex": 4.725065270619211e+16, - "Ey": 3.0253948989388292e+16, + "Bz": 9.614441087794229e-14, + "Ex": 4.725065270619209e+16, + "Ey": 3.025394898938681e+16, "Ez": 3276573.9514776673, "rho": 10994013582437.193 }, "electron": { - "particle_momentum_x": 5.701277606055763e-19, - "particle_momentum_y": 3.6504516636842883e-19, + "particle_momentum_x": 5.7012776060557455e-19, + "particle_momentum_y": 3.650451663685222e-19, "particle_momentum_z": 1.145432768297242e-10, "particle_position_x": 17.314086912497864, - "particle_position_y": 0.25836912671877965, + "particle_position_y": 0.25836912671877954, "particle_position_z": 10066.329600000008, "particle_weight": 19969036501.910976 } diff --git a/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver_sliced.json b/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver_sliced.json new file mode 100644 index 00000000000..fd4a9afbc29 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_open_bc_poisson_solver_sliced.json @@ -0,0 +1,21 @@ +{ + "lev=0": { + "Bx": 100915933.44551668, + "By": 157610622.18551716, + "Bz": 2.598515299403035e-15, + "Ex": 4.725065270620093e+16, + "Ey": 3.0253948989229424e+16, + "Ez": 2787743.3330717986, + "rho": 10994013582437.193 + }, + "electron": { + "particle_momentum_x": 5.701277606056779e-19, + "particle_momentum_y": 3.650451663675671e-19, + "particle_momentum_z": 1.145432768297242e-10, + "particle_position_x": 17.314086912497864, + "particle_position_y": 0.25836912671877954, + "particle_position_z": 10066.329600000008, + "particle_weight": 19969036501.910976 + } +} + diff --git a/Regression/Checksum/benchmarks_json/test_3d_particle_absorption.json b/Regression/Checksum/benchmarks_json/test_3d_particle_absorption.json index ce6e2fcf79b..3dc9d956b79 100644 --- a/Regression/Checksum/benchmarks_json/test_3d_particle_absorption.json +++ b/Regression/Checksum/benchmarks_json/test_3d_particle_absorption.json @@ -1,10 +1,10 @@ { "lev=0": { - "Bx": 202106.71291347666, - "By": 202106.71291347663, - "Bz": 3371.897999274175, - "Ex": 38304043178806.11, - "Ey": 38304043178806.11, - "Ez": 83057027925874.84 + "Bx": 198610.0530604908, + "By": 198610.0530604909, + "Bz": 8482.656173586969, + "Ex": 37232105734622.53, + "Ey": 37232105734622.54, + "Ez": 85094015810307.19 } -} +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_particle_scrape.json b/Regression/Checksum/benchmarks_json/test_3d_particle_scrape.json new file mode 100644 index 00000000000..9437ebed275 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_particle_scrape.json @@ -0,0 +1,10 @@ +{ + "lev=0": { + "Bx": 144495.08082507108, + "By": 144495.0808250711, + "Bz": 8481.95872462886, + "Ex": 54500496182517.914, + "Ey": 54500496182517.914, + "Ez": 70231240245509.4 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_particle_scrape_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_particle_scrape_picmi.json new file mode 100644 index 00000000000..1f9f0a77b5a --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_particle_scrape_picmi.json @@ -0,0 +1,10 @@ +{ + "lev=0": { + "Bx": 144495.08082507108, + "By": 144495.08082507114, + "Bz": 8481.958724628861, + "Ex": 54500496182517.92, + "Ey": 54500496182517.91, + "Ez": 70231240245509.39 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_plasma_lens_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_plasma_lens_picmi.json new file mode 100644 index 00000000000..205bf8204dd --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_plasma_lens_picmi.json @@ -0,0 +1,21 @@ +{ + "lev=0": { + "Bx": 3.742282886653039e-14, + "By": 3.733653562337366e-14, + "Bz": 3.159003724979974e-16, + "Ex": 4.413173824952238e-06, + "Ey": 4.440807110847932e-06, + "Ez": 8.994610621212147e-06, + "jx": 2.294712258669695e-10, + "jy": 1.8314117733996873e-10, + "jz": 2.1990787829485306e-08 + }, + "electrons": { + "particle_momentum_x": 7.424668333878816e-24, + "particle_momentum_y": 5.9396389377972404e-24, + "particle_momentum_z": 2.730924530737562e-22, + "particle_position_x": 0.03608389438974155, + "particle_position_y": 0.028872102262786022, + "particle_position_z": 3.894799963324232 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_pmc_field.json b/Regression/Checksum/benchmarks_json/test_3d_pmc_field.json new file mode 100644 index 00000000000..486f8bb965d --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_pmc_field.json @@ -0,0 +1,6 @@ +{ + "lev=0": { + "Bx": 4.1354151621557795, + "Ey": 8373879983.480644 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_qed_breit_wheeler_opmd.json b/Regression/Checksum/benchmarks_json/test_3d_qed_breit_wheeler_opmd.json new file mode 100644 index 00000000000..bf98f8bd963 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_qed_breit_wheeler_opmd.json @@ -0,0 +1,134 @@ +{ + "lev=0": { + "Ex": 0.0 + }, + "dummy_phot": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "ele1": { + "particle_opticalDepthQSR": 150084.76186868473, + "particle_position_x": 0.037522814130005, + "particle_position_y": 0.0375364375, + "particle_position_z": 0.0375473125, + "particle_momentum_x": 4.111367826819435e-14, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 1.4303398132324217 + }, + "ele2": { + "particle_opticalDepthQSR": 19166.68554224755, + "particle_position_x": 0.0047233984375, + "particle_position_y": 0.004773031169456623, + "particle_position_z": 0.004769421875, + "particle_momentum_x": 0.0, + "particle_momentum_y": 1.3120815641048112e-14, + "particle_momentum_z": 0.0, + "particle_weight": 0.18199920654296872 + }, + "ele3": { + "particle_opticalDepthQSR": 197996.95086384623, + "particle_position_x": 0.049603601562499995, + "particle_position_y": 0.049503953125, + "particle_position_z": 0.049484700428793646, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 2.703275178685535e-13, + "particle_weight": 1.8893241882324217 + }, + "ele4": { + "particle_opticalDepthQSR": 79277.54339646622, + "particle_position_x": 0.019832326822916666, + "particle_position_y": 0.019875475260416667, + "particle_position_z": 0.019791898437499997, + "particle_momentum_x": 6.270940742446365e-13, + "particle_momentum_y": 6.270940742446365e-13, + "particle_momentum_z": 6.270940742446365e-13, + "particle_weight": 0.7561206817626952 + }, + "p1": { + "particle_opticalDepthBW": 779753.6899265796, + "particle_position_x": 0.22462570742050836, + "particle_position_y": 0.22460756249999997, + "particle_position_z": 0.22459668749999998, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 8.569660186767576 + }, + "p2": { + "particle_opticalDepthBW": 1011632.5072099702, + "particle_position_x": 0.2574206015625001, + "particle_position_y": 0.25736832040839486, + "particle_position_z": 0.2573745781250001, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 9.81800079345703 + }, + "p3": { + "particle_opticalDepthBW": 707943.7338077008, + "particle_position_x": 0.2125403984375, + "particle_position_y": 0.21264004687499996, + "particle_position_z": 0.21265919757150045, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 8.110675811767576 + }, + "p4": { + "particle_opticalDepthBW": 899116.8515237333, + "particle_position_x": 0.24232183723958334, + "particle_position_y": 0.24226657421875006, + "particle_position_z": 0.24235025781250008, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 9.243879318237303 + }, + "pos1": { + "particle_opticalDepthQSR": 150411.2911918669, + "particle_position_x": 0.037522814130005, + "particle_position_y": 0.0375364375, + "particle_position_z": 0.0375473125, + "particle_momentum_x": 4.0804162983963274e-14, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 1.4303398132324217 + }, + "pos2": { + "particle_opticalDepthQSR": 19071.695614845616, + "particle_position_x": 0.0047233984375, + "particle_position_y": 0.004773031169456623, + "particle_position_z": 0.004769421875, + "particle_momentum_x": 0.0, + "particle_momentum_y": 1.2937663481149343e-14, + "particle_momentum_z": 0.0, + "particle_weight": 0.18199920654296872 + }, + "pos3": { + "particle_opticalDepthQSR": 197682.0402897762, + "particle_position_x": 0.049603601562499995, + "particle_position_y": 0.049503953125, + "particle_position_z": 0.049484700428793646, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 2.7069590910941717e-13, + "particle_weight": 1.8893241882324217 + }, + "pos4": { + "particle_opticalDepthQSR": 79817.78242989839, + "particle_position_x": 0.019832326822916666, + "particle_position_y": 0.019875475260416667, + "particle_position_z": 0.019791898437499997, + "particle_momentum_x": 6.229925285542024e-13, + "particle_momentum_y": 6.229925285542024e-13, + "particle_momentum_z": 6.229925285542024e-13, + "particle_weight": 0.7561206817626952 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_3d_reduced_diags_load_balance_costs_timers_picmi.json b/Regression/Checksum/benchmarks_json/test_3d_reduced_diags_load_balance_costs_timers_picmi.json new file mode 100644 index 00000000000..a77d93b9621 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_reduced_diags_load_balance_costs_timers_picmi.json @@ -0,0 +1,22 @@ +{ + "electrons": { + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_position_x": 262144.0, + "particle_position_y": 262144.0, + "particle_position_z": 65536.0, + "particle_weight": 1600000000000000.0 + }, + "lev=0": { + "Bx": 0.0, + "By": 0.0, + "Bz": 0.0, + "Ex": 0.0, + "Ey": 0.0, + "Ez": 0.0, + "jx": 0.0, + "jy": 0.0, + "jz": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_3d_thomson_parabola_spectrometer.json b/Regression/Checksum/benchmarks_json/test_3d_thomson_parabola_spectrometer.json new file mode 100644 index 00000000000..2346ffd8124 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_3d_thomson_parabola_spectrometer.json @@ -0,0 +1,35 @@ +{ + "lev=0": { + "rho_carbon12_4": 8.391105120785595e-13, + "rho_carbon12_6": 1.2586657681178396e-12, + "rho_hydrogen1_1": 0.0 + }, + "carbon12_4": { + "particle_position_x": 0.24746482639048117, + "particle_position_y": 0.3712831550411343, + "particle_position_z": 291.92951822527056, + "particle_momentum_x": 7.446857998192906e-19, + "particle_momentum_y": 6.58876061665569e-18, + "particle_momentum_z": 3.0678537977188415e-16, + "particle_weight": 1000.0 + }, + "carbon12_6": { + "particle_position_x": 0.3706220153511513, + "particle_position_y": 0.5770046251488395, + "particle_position_z": 291.70616446343365, + "particle_momentum_x": 1.1143091694186902e-18, + "particle_momentum_y": 1.015840779649768e-17, + "particle_momentum_z": 3.063311157322583e-16, + "particle_weight": 1000.0 + }, + "hydrogen1_1": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} + diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_diffraction.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_diffraction.json index 0e5fad8db8a..e4b9d9c07ff 100644 --- a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_diffraction.json +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_diffraction.json @@ -1,10 +1,10 @@ { "lev=0": { - "Br": 6.821267675779345e-19, - "Bt": 5.564905732478707e-05, - "Bz": 2.368259586613272e-19, - "Er": 16503.98082446463, - "Et": 1.5299584682447838e-10, - "Ez": 1466.854467399728 + "Br": 6.7914286131989935e-19, + "Bt": 5.4557350206853276e-05, + "Bz": 2.357229221622199e-19, + "Er": 16481.39008058988, + "Et": 1.5258937379236053e-10, + "Ez": 1508.1064116028576 } } \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_1.json new file mode 100644 index 00000000000..30d7d0ba081 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_1.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 1.4599714697029335e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_2.json new file mode 100644 index 00000000000..30d7d0ba081 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_2.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 1.4599714697029335e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_3.json new file mode 100644 index 00000000000..76baf73cc3a --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_em_particle_absorption_sh_factor_3.json @@ -0,0 +1,24 @@ +{ + "lev=0": { + "divE": 1.3292471881599093e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_1.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_1.json new file mode 100644 index 00000000000..0376427a4f0 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_1.json @@ -0,0 +1,28 @@ +{ + "lev=0": { + "Br": 0.0, + "Bz": 0.0, + "Er": 1.6208621785146114e-07, + "Ez": 2.805848027148827e-07, + "divE": 5.118824286040605e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_2.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_2.json new file mode 100644 index 00000000000..0376427a4f0 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_2.json @@ -0,0 +1,28 @@ +{ + "lev=0": { + "Br": 0.0, + "Bz": 0.0, + "Er": 1.6208621785146114e-07, + "Ez": 2.805848027148827e-07, + "divE": 5.118824286040605e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_3.json b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_3.json new file mode 100644 index 00000000000..0376427a4f0 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_embedded_boundary_removal_depth_sh_factor_3.json @@ -0,0 +1,28 @@ +{ + "lev=0": { + "Br": 0.0, + "Bz": 0.0, + "Er": 1.6208621785146114e-07, + "Ez": 2.805848027148827e-07, + "divE": 5.118824286040605e-08, + "rho": 0.0 + }, + "electron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + }, + "positron": { + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_weight": 0.0 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_rz_flux_injection_from_eb.json b/Regression/Checksum/benchmarks_json/test_rz_flux_injection_from_eb.json index 23884de9725..f8043c5c3e2 100644 --- a/Regression/Checksum/benchmarks_json/test_rz_flux_injection_from_eb.json +++ b/Regression/Checksum/benchmarks_json/test_rz_flux_injection_from_eb.json @@ -1,12 +1,12 @@ { "lev=0": {}, "electron": { - "particle_momentum_x": 6.734984863106283e-19, - "particle_momentum_y": 6.786279785869023e-19, - "particle_momentum_z": 1.0527983828124758e-18, - "particle_position_x": 53309.270966506396, - "particle_position_y": 53302.3776094842, - "particle_theta": 58707.74469425615, - "particle_weight": 4.991396867417661e-07 + "particle_momentum_x": 1.3547613622259754e-18, + "particle_momentum_y": 1.3539614160696825e-18, + "particle_momentum_z": 2.102305484242805e-18, + "particle_position_x": 108281.74349700565, + "particle_position_y": 108222.91506078152, + "particle_theta": 118597.06004310239, + "particle_weight": 2.5087578786544294e-07 } -} \ No newline at end of file +} diff --git a/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_cylinder_compression_picmi.json b/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_cylinder_compression_picmi.json new file mode 100644 index 00000000000..ae86b3d4168 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_cylinder_compression_picmi.json @@ -0,0 +1,20 @@ +{ + "lev=0": { + "Br": 0.011900125915334049, + "Bt": 0.011313482081775999, + "Bz": 11.684907956225278, + "Er": 154581.64325434464, + "Et": 4797.794963571249, + "Ez": 193.22336541793413, + "rho": 7968.182346878508 + }, + "ions": { + "particle_momentum_x": 3.112515238421571e-18, + "particle_momentum_y": 3.1193860531312334e-18, + "particle_momentum_z": 3.0289560038609835e-18, + "particle_position_x": 13628.662686094893, + "particle_position_y": 2285.6952310456554, + "particle_theta": 115055.48935714104, + "particle_weight": 2.525423582445981e+18 + } +} \ No newline at end of file diff --git a/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_em_modes_picmi.json b/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_em_modes_picmi.json index ec1b6272092..feca88922e2 100644 --- a/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_em_modes_picmi.json +++ b/Regression/Checksum/benchmarks_json/test_rz_ohm_solver_em_modes_picmi.json @@ -1,12 +1,12 @@ { "lev=0": {}, "ions": { - "particle_momentum_x": 5.0438993756415296e-17, - "particle_momentum_y": 5.0444406612873916e-17, - "particle_momentum_z": 5.0519292431385393e-17, - "particle_position_x": 143164.41713467025, - "particle_position_y": 143166.51845281923, - "particle_theta": 2573261.8729711357, - "particle_weight": 8.128680645366887e+18 + "particle_momentum_x": 5.043784704795177e-17, + "particle_momentum_y": 5.0444695502620235e-17, + "particle_momentum_z": 5.05193106847111e-17, + "particle_position_x": 143164.53685279266, + "particle_position_y": 143166.5185853012, + "particle_theta": 2573262.446840369, + "particle_weight": 8.128680645366886e+18 } } diff --git a/Regression/Checksum/benchmarks_json/test_rz_scraping.json b/Regression/Checksum/benchmarks_json/test_rz_scraping.json index 8f85b956b26..3a97a2dc651 100644 --- a/Regression/Checksum/benchmarks_json/test_rz_scraping.json +++ b/Regression/Checksum/benchmarks_json/test_rz_scraping.json @@ -4,5 +4,14 @@ }, "lev=1": { "Er": 0.0 + }, + "electron": { + "particle_momentum_x": 8.802233511708275e-20, + "particle_momentum_y": 8.865573181381068e-20, + "particle_momentum_z": 0.0, + "particle_position_x": 52.1624916491251, + "particle_position_y": 128.0, + "particle_theta": 776.9665451756912, + "particle_weight": 4.841626861764053e+18 } } diff --git a/Regression/Checksum/benchmarks_json/test_rz_scraping_filter.json b/Regression/Checksum/benchmarks_json/test_rz_scraping_filter.json new file mode 100644 index 00000000000..3a97a2dc651 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_scraping_filter.json @@ -0,0 +1,17 @@ +{ + "lev=0": { + "Er": 0.0 + }, + "lev=1": { + "Er": 0.0 + }, + "electron": { + "particle_momentum_x": 8.802233511708275e-20, + "particle_momentum_y": 8.865573181381068e-20, + "particle_momentum_z": 0.0, + "particle_position_x": 52.1624916491251, + "particle_position_y": 128.0, + "particle_theta": 776.9665451756912, + "particle_weight": 4.841626861764053e+18 + } +} diff --git a/Regression/Checksum/benchmarks_json/test_rz_secondary_ion_emission_picmi.json b/Regression/Checksum/benchmarks_json/test_rz_secondary_ion_emission_picmi.json new file mode 100644 index 00000000000..cfc84819e97 --- /dev/null +++ b/Regression/Checksum/benchmarks_json/test_rz_secondary_ion_emission_picmi.json @@ -0,0 +1,26 @@ +{ + "electrons": { + "particle_momentum_x": 5.621885683102775e-26, + "particle_momentum_y": 1.2079178196118306e-25, + "particle_momentum_z": 1.2496342823828099e-25, + "particle_position_x": 0.10329568998704057, + "particle_position_y": 0.013444257249267193, + "particle_position_z": 0.4019696082583948, + "particle_weight": 2.0 + }, + "ions": { + "particle_momentum_x": 0.0, + "particle_momentum_y": 0.0, + "particle_momentum_z": 0.0, + "particle_position_x": 0.0, + "particle_position_y": 0.0, + "particle_position_z": 0.0, + "particle_weight": 0.0 + }, + "lev=0": { + "Er": 1.772547702166409e-06, + "Ez": 2.2824957684716966e-06, + "phi": 4.338168233265556e-07, + "rho": 1.933391680367631e-15 + } +} \ No newline at end of file diff --git a/Regression/Checksum/checksum.py b/Regression/Checksum/checksum.py index b2f327e36e3..8c93f4ea6ea 100644 --- a/Regression/Checksum/checksum.py +++ b/Regression/Checksum/checksum.py @@ -238,8 +238,7 @@ def evaluate(self, rtol=1.0e-9, atol=1.0e-40): # Dictionaries have same outer keys (levels, species)? if self.data.keys() != ref_benchmark.data.keys(): print( - "ERROR: Benchmark and output file checksum " - "have different outer keys:" + "ERROR: Benchmark and output file checksum have different outer keys:" ) print("Benchmark: %s" % ref_benchmark.data.keys()) print("Test file: %s" % self.data.keys()) diff --git a/Regression/PostProcessingUtils/post_processing_utils.py b/Regression/PostProcessingUtils/post_processing_utils.py index 55bc357c28b..cbd55c433d3 100644 --- a/Regression/PostProcessingUtils/post_processing_utils.py +++ b/Regression/PostProcessingUtils/post_processing_utils.py @@ -164,6 +164,6 @@ def check_random_filter(fn, filtered_fn, random_fraction, dim, species_name): ## Dirty trick to find particles with the same ID + same CPU (does not work with more than 10 ## MPI ranks) random_filter_expression = ( - "np.isin(ids + 0.1*cpus," "ids_filtered_warpx + 0.1*cpus_filtered_warpx)" + "np.isin(ids + 0.1*cpus,ids_filtered_warpx + 0.1*cpus_filtered_warpx)" ) check_particle_filter(fn, filtered_fn, random_filter_expression, dim, species_name) diff --git a/Source/AcceleratorLattice/AcceleratorLattice.H b/Source/AcceleratorLattice/AcceleratorLattice.H index 4b3eff46094..e8acc2c8743 100644 --- a/Source/AcceleratorLattice/AcceleratorLattice.H +++ b/Source/AcceleratorLattice/AcceleratorLattice.H @@ -42,10 +42,15 @@ public: * \brief Initialize the element finder instance at the given level of refinement * * @param[in] lev the level of refinement + * @param[in] gamma_boost the Lorentz factor of the boosted frame * @param[in] ba the box array at the level of refinement * @param[in] dm the distribution map at the level of refinement */ - void InitElementFinder (int lev, amrex::BoxArray const & ba, amrex::DistributionMapping const & dm); + void InitElementFinder ( + int lev, + amrex::Real gamma_boost, + amrex::BoxArray const & ba, + amrex::DistributionMapping const & dm); /** * \brief Update the element finder, needed when the simulation frame has moved relative to the lab frame diff --git a/Source/AcceleratorLattice/AcceleratorLattice.cpp b/Source/AcceleratorLattice/AcceleratorLattice.cpp index edccae9374a..b0513f767a0 100644 --- a/Source/AcceleratorLattice/AcceleratorLattice.cpp +++ b/Source/AcceleratorLattice/AcceleratorLattice.cpp @@ -76,13 +76,15 @@ AcceleratorLattice::ReadLattice (std::string const & root_name, amrex::ParticleR } void -AcceleratorLattice::InitElementFinder (int const lev, amrex::BoxArray const & ba, amrex::DistributionMapping const & dm) +AcceleratorLattice::InitElementFinder ( + int const lev, amrex::Real const gamma_boost, + amrex::BoxArray const & ba, amrex::DistributionMapping const & dm) { if (m_lattice_defined) { m_element_finder = std::make_unique>(ba, dm); for (amrex::MFIter mfi(*m_element_finder); mfi.isValid(); ++mfi) { - (*m_element_finder)[mfi].InitElementFinder(lev, mfi, *this); + (*m_element_finder)[mfi].InitElementFinder(lev, gamma_boost, mfi, *this); } } } diff --git a/Source/AcceleratorLattice/LatticeElementFinder.H b/Source/AcceleratorLattice/LatticeElementFinder.H index 6773ed56a65..68a90906dbc 100644 --- a/Source/AcceleratorLattice/LatticeElementFinder.H +++ b/Source/AcceleratorLattice/LatticeElementFinder.H @@ -30,10 +30,12 @@ struct LatticeElementFinder * \brief Initialize the element finder at the level and grid * * @param[in] lev the refinement level + * @param[in] gamma_boost the Lorentz factor of the boosted frame * @param[in] a_mfi specifies the grid where the finder is defined * @param[in] accelerator_lattice a reference to the accelerator lattice at the refinement level */ - void InitElementFinder (int lev, amrex::MFIter const& a_mfi, + void InitElementFinder (int lev, amrex::Real gamma_boost, + amrex::MFIter const& a_mfi, AcceleratorLattice const& accelerator_lattice); /** @@ -112,6 +114,9 @@ struct LatticeElementFinderDevice AcceleratorLattice const& accelerator_lattice, LatticeElementFinder const & h_finder); + /* Whether the class has been initialized */ + bool m_initialized = false; + /* Size and location of the index lookup table */ amrex::Real m_zmin; amrex::Real m_dz; diff --git a/Source/AcceleratorLattice/LatticeElementFinder.cpp b/Source/AcceleratorLattice/LatticeElementFinder.cpp index ec784049760..93aa70e4242 100644 --- a/Source/AcceleratorLattice/LatticeElementFinder.cpp +++ b/Source/AcceleratorLattice/LatticeElementFinder.cpp @@ -15,7 +15,8 @@ using namespace amrex::literals; void -LatticeElementFinder::InitElementFinder (int const lev, amrex::MFIter const& a_mfi, +LatticeElementFinder::InitElementFinder (int const lev, const amrex::Real gamma_boost, + amrex::MFIter const& a_mfi, AcceleratorLattice const& accelerator_lattice) { @@ -26,8 +27,8 @@ LatticeElementFinder::InitElementFinder (int const lev, amrex::MFIter const& a_m m_dz = WarpX::CellSize(lev)[2]; - m_gamma_boost = WarpX::gamma_boost; - m_uz_boost = std::sqrt(WarpX::gamma_boost*WarpX::gamma_boost - 1._prt)*PhysConst::c; + m_gamma_boost = gamma_boost; + m_uz_boost = std::sqrt(m_gamma_boost*m_gamma_boost - 1._prt)*PhysConst::c; AllocateIndices(accelerator_lattice); @@ -91,6 +92,8 @@ LatticeElementFinderDevice::InitLatticeElementFinderDevice (WarpXParIter const& LatticeElementFinder const & h_finder) { + m_initialized = true; + auto& warpx = WarpX::GetInstance(); int const lev = a_pti.GetLevel(); diff --git a/Source/BoundaryConditions/CMakeLists.txt b/Source/BoundaryConditions/CMakeLists.txt index 751e52abdd9..c560d121385 100644 --- a/Source/BoundaryConditions/CMakeLists.txt +++ b/Source/BoundaryConditions/CMakeLists.txt @@ -2,6 +2,7 @@ foreach(D IN LISTS WarpX_DIMS) warpx_set_suffix_dims(SD ${D}) target_sources(lib_${SD} PRIVATE + PEC_Insulator.cpp PML.cpp WarpXEvolvePML.cpp WarpXFieldBoundaries.cpp diff --git a/Source/BoundaryConditions/Make.package b/Source/BoundaryConditions/Make.package index 43d18425ffc..452c9c18b7e 100644 --- a/Source/BoundaryConditions/Make.package +++ b/Source/BoundaryConditions/Make.package @@ -1,3 +1,4 @@ +CEXE_sources += PEC_Insulator.cpp CEXE_sources += PML.cpp WarpXEvolvePML.cpp CEXE_sources += WarpXFieldBoundaries.cpp WarpX_PEC.cpp diff --git a/Source/BoundaryConditions/PEC_Insulator.H b/Source/BoundaryConditions/PEC_Insulator.H new file mode 100644 index 00000000000..5cfdf6488f0 --- /dev/null +++ b/Source/BoundaryConditions/PEC_Insulator.H @@ -0,0 +1,180 @@ +#ifndef PEC_INSULATOR_H_ +#define PEC_INSULATOR_H_ + +#include "Utils/WarpXAlgorithmSelection.H" + +#include +#include +#include + +#include + +#include +#include + +class PEC_Insulator +{ +public: + + PEC_Insulator(); + + /** + * \brief Apply either the PEC or insulator boundary condition on the boundary and in the + * guard cells. + * In the PEC, the nodal fields (in a Yee mesh) are made even relative to the boundary, + * the non-nodal fields are made odd. + * In the insulator, the tangential fields are set to the value if specified, otherwise unchanged, + * and the normal fields extrapolated from the valid cells. + * + * \param[in,out] Efield + * \param[in] field_boundary_lo lower field boundary conditions + * \param[in] field_boundary_hi upper field boundary conditions + * \param[in] ng_fieldgather number of guard cells used by field gather + * \param[in] geom geometry object of level "lev" + * \param[in] lev level of the Multifab + * \param[in] patch_type coarse or fine + * \param[in] ref_ratios vector containing the refinement ratios of the refinement levels + * \param[in] time current time of the simulation + * \param[in] split_pml_field whether pml the multifab is the regular Efield or + * split pml field + */ + void ApplyPEC_InsulatortoEfield (std::array Efield, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time, + bool split_pml_field = false); + /** + * \brief Apply either the PEC or insulator boundary condition on the boundary and in the + * guard cells. + * In the PEC, the nodal fields (in a Yee mesh) are made even relative to the boundary, + * the non-nodal fields are made odd. + * In the insulator, the tangential fields are set to the value if specified, otherwise unchanged, + * and the normal fields extrapolated from the valid cells. + * + * \param[in,out] Bfield + * \param[in] field_boundary_lo lower field boundary conditions + * \param[in] field_boundary_hi upper field boundary conditions + * \param[in] ng_fieldgather number of guard cells used by field gather + * \param[in] geom geometry object of level "lev" + * \param[in] lev level of the Multifab + * \param[in] patch_type coarse or fine + * \param[in] ref_ratios vector containing the refinement ratios of the refinement levels + * \param[in] time current time of the simulation + */ + void ApplyPEC_InsulatortoBfield (std::array Bfield, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time); + + /** + * \brief The work routine applying the boundary condition + * + * \param[in,out] field + * \param[in] field_boundary_lo lower field boundary conditions + * \param[in] field_boundary_hi upper field boundary conditions + * \param[in] ng_fieldgather number of guard cells used by field gather + * \param[in] geom geometry object of level "lev" + * \param[in] lev level of the Multifab + * \param[in] patch_type coarse or fine + * \param[in] ref_ratios vector containing the refinement ratios of the refinement levels + * \param[in] time current time of the simulation + * \param[in] split_pml_field whether pml the multifab is the regular Efield or + * split pml field + * \param[in] E_like whether the field is E like or B like + * \param[in] set_F_x_lo whether the tangential field at the boundary was specified + * \param[in] set_F_x_hi whether the tangential field at the boundary was specified + * \param[in] a_Fy_x_lo the parser for the tangential field at the boundary + * \param[in] a_Fz_x_lo the parser for the tangential field at the boundary + * \param[in] a_Fy_x_hi the parser for the tangential field at the boundary + * \param[in] a_Fz_x_hi the parser for the tangential field at the boundary + * \param[in] set_F_y_lo whether the tangential field at the boundary was specified + * \param[in] set_F_y_hi whether the tangential field at the boundary was specified + * \param[in] a_Fx_y_lo the parser for the tangential field at the boundary + * \param[in] a_Fz_y_lo the parser for the tangential field at the boundary + * \param[in] a_Fx_y_hi the parser for the tangential field at the boundary + * \param[in] a_Fz_y_hi the parser for the tangential field at the boundary + * \param[in] set_F_z_lo whether the tangential field at the boundary was specified + * \param[in] set_F_z_hi whether the tangential field at the boundary was specified + * \param[in] a_Fx_z_lo the parser for the tangential field at the boundary + * \param[in] a_Fy_z_lo the parser for the tangential field at the boundary + * \param[in] a_Fx_z_hi the parser for the tangential field at the boundary + * \param[in] a_Fy_z_hi the parser for the tangential field at the boundary + */ + void + ApplyPEC_InsulatortoField (std::array field, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time, + bool split_pml_field, + bool E_like, +#if (AMREX_SPACEDIM > 1) + bool set_F_x_lo, bool set_F_x_hi, + std::unique_ptr const & a_Fy_x_lo, std::unique_ptr const & a_Fz_x_lo, + std::unique_ptr const & a_Fy_x_hi, std::unique_ptr const & a_Fz_x_hi, +#endif +#if defined(WARPX_DIM_3D) + bool set_F_y_lo, bool set_F_y_hi, + std::unique_ptr const & a_Fx_y_lo, std::unique_ptr const & a_Fz_y_lo, + std::unique_ptr const & a_Fx_y_hi, std::unique_ptr const & a_Fz_y_hi, +#endif + bool set_F_z_lo, bool set_F_z_hi, + std::unique_ptr const & a_Fx_z_lo, std::unique_ptr const & a_Fy_z_lo, + std::unique_ptr const & a_Fx_z_hi, std::unique_ptr const & a_Fy_z_hi); + +private: + + /* \brief Reads in the parsers for the tangential fields, returning whether + * the input parameter was specified. + * \param[in] pp_insulator ParmParse instance + * \param[out] parser the parser generated from the input + * \param[in] input_name the name of the input parameter + * \param[in] coord1 the first coordinate in the plane + * \param[in] coord2 the second coordinate in the plane + */ + bool ReadTangentialFieldParser (amrex::ParmParse const & pp_insulator, + std::unique_ptr & parser, + std::string const & input_name, + std::string const & coord1, + std::string const & coord2); + + std::vector> m_insulator_area_lo; + std::vector> m_insulator_area_hi; + +#if (AMREX_SPACEDIM > 1) + bool m_set_B_x_lo = false, m_set_B_x_hi = false; + std::unique_ptr m_By_x_lo, m_Bz_x_lo; + std::unique_ptr m_By_x_hi, m_Bz_x_hi; +#endif +#if defined(WARPX_DIM_3D) + bool m_set_B_y_lo = false, m_set_B_y_hi = false; + std::unique_ptr m_Bx_y_lo, m_Bz_y_lo; + std::unique_ptr m_Bx_y_hi, m_Bz_y_hi; +#endif + bool m_set_B_z_lo = false, m_set_B_z_hi = false; + std::unique_ptr m_Bx_z_lo, m_By_z_lo; + std::unique_ptr m_Bx_z_hi, m_By_z_hi; + + +#if (AMREX_SPACEDIM > 1) + bool m_set_E_x_lo = false, m_set_E_x_hi = false; + std::unique_ptr m_Ey_x_lo, m_Ez_x_lo; + std::unique_ptr m_Ey_x_hi, m_Ez_x_hi; +#endif +#if defined(WARPX_DIM_3D) + bool m_set_E_y_lo = false, m_set_E_y_hi = false; + std::unique_ptr m_Ex_y_lo, m_Ez_y_lo; + std::unique_ptr m_Ex_y_hi, m_Ez_y_hi; +#endif + bool m_set_E_z_lo = false, m_set_E_z_hi = false; + std::unique_ptr m_Ex_z_lo, m_Ey_z_lo; + std::unique_ptr m_Ex_z_hi, m_Ey_z_hi; + + +}; +#endif // PEC_INSULATOR_H_ diff --git a/Source/BoundaryConditions/PEC_Insulator.cpp b/Source/BoundaryConditions/PEC_Insulator.cpp new file mode 100644 index 00000000000..b6b6bcf08ea --- /dev/null +++ b/Source/BoundaryConditions/PEC_Insulator.cpp @@ -0,0 +1,573 @@ +#include "BoundaryConditions/PEC_Insulator.H" +#include "Utils/Parser/ParserUtils.H" +#include "WarpX.H" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + /** + * \brief At the specified grid location, apply either the PEC or insulator boundary condition if + * the cell is on the boundary or in the guard cells. + * + * \param[in] icomp component of the field being updated + * (0=x, 1=y, 2=z in Cartesian) + * (0=r, 1=theta, 2=z in RZ) + * \param[in] dom_lo index value of the lower domain boundary (cell-centered) + * \param[in] dom_hi index value of the higher domain boundary (cell-centered) + * \param[in] ijk_vec indices along the x(i), y(j), z(k) of field Array4 + * \param[in] n index of the MultiFab component being updated + * \param[in] field field data to be updated if (ijk) is at the boundary + * or a guard cell + * \param[in] E_like whether the field behaves like E field or B field + * \param[in] is_nodal staggering of the field data being updated. + * \param[in] is_insulator_lo Specifies whether lower boundaries are insulators + * \param[in] is_insulator_hi Specifies whether upper boundaries are insulators + * \param[in] field_lo the values of the field for the lower insulator boundary cell + * \param[in] field_hi the values of the field for the upper insulator boundary cell + * \param[in] set_field_lo whether to set the field for the direction on the lower boundary + * \param[in] set_field_hi whether to set the field for the direction on the upper boundary + * \param[in] fbndry_lo specified values of the field at the lower boundaries in the insulator + * \param[in] fbndry_hi specified values of the field at the upper boundaries in the insulator + */ + AMREX_GPU_DEVICE AMREX_FORCE_INLINE + void SetFieldOnPEC_Insulator (int icomp, + amrex::IntVect const & dom_lo, + amrex::IntVect const & dom_hi, + amrex::IntVect const & ijk_vec, int n, + amrex::Array4 const & field, + bool const E_like, + amrex::IntVect const & is_nodal, + amrex::IntVect const & is_insulator_lo, + amrex::IntVect const & is_insulator_hi, + amrex::RealVect const & field_lo, + amrex::RealVect const & field_hi, + amrex::IntVect const & set_field_lo, + amrex::IntVect const & set_field_hi, + amrex::GpuArray const fbndry_lo, + amrex::GpuArray const fbndry_hi) + { + using namespace amrex::literals; + amrex::IntVect ijk_next = ijk_vec; + amrex::IntVect ijk_nextp1 = ijk_vec; + amrex::IntVect ijk_mirror = ijk_vec; + bool OnBoundary = false; + bool GuardCell = false; + bool isInsulatorBoundary = false; + amrex::Real sign = +1._rt; + bool is_normal_to_boundary = false; + amrex::Real field_value = 0._rt; + bool set_field = false; + // Loop over all dimensions + for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { + // Loop over sides, iside = -1 (lo), iside = +1 (hi) + for (int iside = -1; iside <= +1; iside += 2) { + bool const isPEC_InsulatorBoundary = ( (iside == -1) + ? fbndry_lo[idim] == FieldBoundaryType::PECInsulator + : fbndry_hi[idim] == FieldBoundaryType::PECInsulator ); + if (isPEC_InsulatorBoundary) { + isInsulatorBoundary = ( (iside == -1) + ? is_insulator_lo[idim] == 1 + : is_insulator_hi[idim] == 1 ); + } + if (isPEC_InsulatorBoundary) { + // Calculates the number of grid points ijk_vec is beyond the + // domain boundary i.e. a value of +1 means the current cell is + // outside of the simulation domain by 1 cell. Note that the high + // side domain boundary is between cell dom_hi and dom_hi+1 for cell + // centered grids and on cell dom_hi+1 for nodal grid. This is why + // (dom_hi[idim] + is_nodal[idim]) is used. + int const ig = ((iside == -1) ? (dom_lo[idim] - ijk_vec[idim]) + : (ijk_vec[idim] - (dom_hi[idim] + is_nodal[idim]))); + +#if (defined WARPX_DIM_XZ) || (defined WARPX_DIM_RZ) + // For 2D : for icomp==1, (Fy in XZ, Ftheta in RZ), + // icomp=1 is not normal to x or z boundary + // The logic below ensures that the flags are set right for 2D + is_normal_to_boundary = (icomp == (2*idim)); +#elif (defined WARPX_DIM_1D_Z) + // For 1D : icomp=0 and icomp=1 (Fx and Fy are not normal to the z boundary) + // The logic below ensures that the flags are set right for 1D + is_normal_to_boundary = (icomp == 2); +#else + is_normal_to_boundary = (icomp == idim); +#endif + + if (ig == 0) { + // Check if field is on the boundary + if (is_nodal[idim] == 1) { + OnBoundary = true; + } + } else if (ig > 0) { + GuardCell = true; + + // Location of the next cells inward + ijk_next[idim] = ijk_vec[idim] - ig*iside; + ijk_nextp1[idim] = ijk_next[idim] - ig*iside; + + // Mirror location inside the domain by "ig" number of cells + ijk_mirror[idim] = ( (iside == -1) + ? (dom_lo[idim] + ig - (1 - is_nodal[idim])) + : (dom_hi[idim] - ig + 1)); + + // Check for components with even symmetry. + // True for E_like and tangential, and B_like and normal + if (E_like ^ is_normal_to_boundary) { sign *= -1._rt; } + + field_value = ( (iside == -1) ? field_lo[idim] : field_hi[idim] ); + set_field = ( (iside == -1) ? set_field_lo[idim]==1 : set_field_hi[idim]==1 ); + +#if (defined WARPX_DIM_RZ) + if (idim == 0 && iside == +1) { + // Upper radial boundary + amrex::Real const rguard = ijk_vec[idim] + 0.5_rt*(1._rt - is_nodal[idim]); + if (icomp == 0) { + // Add radial scale so that the divergence, drFr/dr, is 0. + // This only works for the first guard cell and with + // Fr cell centered in r. + amrex::Real const rmirror = ijk_mirror[idim] + 0.5_rt*(1._rt - is_nodal[idim]); + // Calculate radial scale factor + sign *= rmirror/rguard; + } + if (isInsulatorBoundary) { + // Apply radial scale factor + field_value *= dom_hi[idim]/rguard; + } + } +#endif + } + } // is pec_insulator boundary + } // loop over iside + } // loop over dimensions + + if (isInsulatorBoundary) { + if (is_normal_to_boundary) { + // The value on the boundary is left unmodified + // The values in the guard cells are extrapolated + if (GuardCell) { + field(ijk_vec, n) = 2._rt*field(ijk_next, n) - field(ijk_nextp1, n); + } + } else if ((OnBoundary || GuardCell) && set_field) { + field(ijk_vec, n) = field_value; + } else if (GuardCell) { + field(ijk_vec, n) = 2._rt*field(ijk_next, n) - field(ijk_nextp1, n); + } + } else { + if (OnBoundary && (E_like ^ is_normal_to_boundary)) { + // If ijk_vec is on a boundary, set to zero if + // E_like and tangential or B_like and normal + field(ijk_vec,n) = 0._rt; + } else if (GuardCell) { + // Fnormal and Ftangential is set opposite and equal to the value + // in the mirror location, respectively. + field(ijk_vec,n) = sign * field(ijk_mirror,n); + } + } + } +} + + +bool +PEC_Insulator::ReadTangentialFieldParser (amrex::ParmParse const & pp_insulator, + std::unique_ptr & parser, + std::string const & input_name, + std::string const & coord1, + std::string const & coord2) +{ + std::string str = "0"; + bool const specified = utils::parser::Query_parserString(pp_insulator, input_name, str); + parser = std::make_unique(utils::parser::makeParser(str, {coord1, coord2, "t"})); + return specified; +} + +PEC_Insulator::PEC_Insulator () +{ + + amrex::ParmParse const pp_insulator("insulator"); + +#if (AMREX_SPACEDIM > 1) + std::string str_area_x_lo = "0"; + std::string str_area_x_hi = "0"; + utils::parser::Query_parserString( pp_insulator, "area_x_lo(y,z)", str_area_x_lo); + utils::parser::Query_parserString( pp_insulator, "area_x_hi(y,z)", str_area_x_hi); + m_insulator_area_lo.push_back( + std::make_unique(utils::parser::makeParser(str_area_x_lo, {"y", "z"}))); + m_insulator_area_hi.push_back( + std::make_unique(utils::parser::makeParser(str_area_x_hi, {"y", "z"}))); + + m_set_B_x_lo |= ReadTangentialFieldParser(pp_insulator, m_By_x_lo, "By_x_lo(y,z,t)", "y", "z"); + m_set_B_x_lo |= ReadTangentialFieldParser(pp_insulator, m_Bz_x_lo, "Bz_x_lo(y,z,t)", "y", "z"); + m_set_B_x_hi |= ReadTangentialFieldParser(pp_insulator, m_By_x_hi, "By_x_hi(y,z,t)", "y", "z"); + m_set_B_x_hi |= ReadTangentialFieldParser(pp_insulator, m_Bz_x_hi, "Bz_x_hi(y,z,t)", "y", "z"); + + m_set_E_x_lo |= ReadTangentialFieldParser(pp_insulator, m_Ey_x_lo, "Ey_x_lo(y,z,t)", "y", "z"); + m_set_E_x_lo |= ReadTangentialFieldParser(pp_insulator, m_Ez_x_lo, "Ez_x_lo(y,z,t)", "y", "z"); + m_set_E_x_hi |= ReadTangentialFieldParser(pp_insulator, m_Ey_x_hi, "Ey_x_hi(y,z,t)", "y", "z"); + m_set_E_x_hi |= ReadTangentialFieldParser(pp_insulator, m_Ez_x_hi, "Ez_x_hi(y,z,t)", "y", "z"); +#endif +#if defined(WARPX_DIM_3D) + std::string str_area_y_lo = "0"; + std::string str_area_y_hi = "0"; + utils::parser::Query_parserString( pp_insulator, "area_y_lo(x,z)", str_area_y_lo); + utils::parser::Query_parserString( pp_insulator, "area_y_hi(x,z)", str_area_y_hi); + m_insulator_area_lo.push_back( + std::make_unique(utils::parser::makeParser(str_area_y_lo, {"x", "z"}))); + m_insulator_area_hi.push_back( + std::make_unique(utils::parser::makeParser(str_area_y_hi, {"x", "z"}))); + + m_set_B_y_lo |= ReadTangentialFieldParser(pp_insulator, m_Bx_y_lo, "Bx_y_lo(x,z,t)", "x", "z"); + m_set_B_y_lo |= ReadTangentialFieldParser(pp_insulator, m_Bz_y_lo, "Bz_y_lo(x,z,t)", "x", "z"); + m_set_B_y_hi |= ReadTangentialFieldParser(pp_insulator, m_Bx_y_hi, "Bx_y_hi(x,z,t)", "x", "z"); + m_set_B_y_hi |= ReadTangentialFieldParser(pp_insulator, m_Bz_y_hi, "Bz_y_hi(x,z,t)", "x", "z"); + + m_set_E_y_lo |= ReadTangentialFieldParser(pp_insulator, m_Ex_y_lo, "Ex_y_lo(x,z,t)", "x", "z"); + m_set_E_y_lo |= ReadTangentialFieldParser(pp_insulator, m_Ez_y_lo, "Ez_y_lo(x,z,t)", "x", "z"); + m_set_E_y_hi |= ReadTangentialFieldParser(pp_insulator, m_Ex_y_hi, "Ex_y_hi(x,z,t)", "x", "z"); + m_set_E_y_hi |= ReadTangentialFieldParser(pp_insulator, m_Ez_y_hi, "Ez_y_hi(x,z,t)", "x", "z"); +#endif + + std::string str_area_z_lo = "0"; + std::string str_area_z_hi = "0"; + utils::parser::Query_parserString( pp_insulator, "area_z_lo(x,y)", str_area_z_lo); + utils::parser::Query_parserString( pp_insulator, "area_z_hi(x,y)", str_area_z_hi); + m_insulator_area_lo.push_back( + std::make_unique(utils::parser::makeParser(str_area_z_lo, {"x", "y"}))); + m_insulator_area_hi.push_back( + std::make_unique(utils::parser::makeParser(str_area_z_hi, {"x", "y"}))); + + m_set_B_z_lo |= ReadTangentialFieldParser(pp_insulator, m_Bx_z_lo, "Bx_z_lo(x,y,t)", "x", "y"); + m_set_B_z_lo |= ReadTangentialFieldParser(pp_insulator, m_By_z_lo, "By_z_lo(x,y,t)", "x", "y"); + m_set_B_z_hi |= ReadTangentialFieldParser(pp_insulator, m_Bx_z_hi, "Bx_z_hi(x,y,t)", "x", "y"); + m_set_B_z_hi |= ReadTangentialFieldParser(pp_insulator, m_By_z_hi, "By_z_hi(x,y,t)", "x", "y"); + + m_set_E_z_lo |= ReadTangentialFieldParser(pp_insulator, m_Ex_z_lo, "Ex_z_lo(x,y,t)", "x", "y"); + m_set_E_z_lo |= ReadTangentialFieldParser(pp_insulator, m_Ey_z_lo, "Ey_z_lo(x,y,t)", "x", "y"); + m_set_E_z_hi |= ReadTangentialFieldParser(pp_insulator, m_Ex_z_hi, "Ex_z_hi(x,y,t)", "x", "y"); + m_set_E_z_hi |= ReadTangentialFieldParser(pp_insulator, m_Ey_z_hi, "Ey_z_hi(x,y,t)", "x", "y"); + +} + +void +PEC_Insulator::ApplyPEC_InsulatortoEfield ( + std::array Efield, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time, + bool split_pml_field) +{ + bool const E_like = true; + ApplyPEC_InsulatortoField(Efield, field_boundary_lo, field_boundary_hi, ng_fieldgather, geom, + lev, patch_type, ref_ratios, time, split_pml_field, + E_like, +#if (AMREX_SPACEDIM > 1) + m_set_E_x_lo, m_set_E_x_hi, + m_Ey_x_lo, m_Ez_x_lo, m_Ey_x_hi, m_Ez_x_hi, +#endif +#if defined(WARPX_DIM_3D) + m_set_E_y_lo, m_set_E_y_hi, + m_Ex_y_lo, m_Ez_y_lo, m_Ex_y_hi, m_Ez_y_hi, +#endif + m_set_E_z_lo, m_set_E_z_hi, + m_Ex_z_lo, m_Ey_z_lo, m_Ex_z_hi, m_Ey_z_hi); +} + + +void +PEC_Insulator::ApplyPEC_InsulatortoBfield ( + std::array Bfield, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time) +{ + bool const E_like = false; + bool const split_pml_field = false; + ApplyPEC_InsulatortoField(Bfield, field_boundary_lo, field_boundary_hi, ng_fieldgather, geom, + lev, patch_type, ref_ratios, time, split_pml_field, + E_like, +#if (AMREX_SPACEDIM > 1) + m_set_B_x_lo, m_set_B_x_hi, + m_By_x_lo, m_Bz_x_lo, m_By_x_hi, m_Bz_x_hi, +#endif +#if defined(WARPX_DIM_3D) + m_set_B_y_lo, m_set_B_y_hi, + m_Bx_y_lo, m_Bz_y_lo, m_Bx_y_hi, m_Bz_y_hi, +#endif + m_set_B_z_lo, m_set_B_z_hi, + m_Bx_z_lo, m_By_z_lo, m_Bx_z_hi, m_By_z_hi); +} + + +void +PEC_Insulator::ApplyPEC_InsulatortoField ( + std::array field, + amrex::Array const & field_boundary_lo, + amrex::Array const & field_boundary_hi, + amrex::IntVect const & ng_fieldgather, amrex::Geometry const & geom, + int lev, PatchType patch_type, amrex::Vector const & ref_ratios, + amrex::Real time, + bool split_pml_field, + bool E_like, +#if (AMREX_SPACEDIM > 1) + bool set_F_x_lo, bool set_F_x_hi, + std::unique_ptr const & a_Fy_x_lo, std::unique_ptr const & a_Fz_x_lo, + std::unique_ptr const & a_Fy_x_hi, std::unique_ptr const & a_Fz_x_hi, +#endif +#if defined(WARPX_DIM_3D) + bool set_F_y_lo, bool set_F_y_hi, + std::unique_ptr const & a_Fx_y_lo, std::unique_ptr const & a_Fz_y_lo, + std::unique_ptr const & a_Fx_y_hi, std::unique_ptr const & a_Fz_y_hi, +#endif + bool set_F_z_lo, bool set_F_z_hi, + std::unique_ptr const & a_Fx_z_lo, std::unique_ptr const & a_Fy_z_lo, + std::unique_ptr const & a_Fx_z_hi, std::unique_ptr const & a_Fy_z_hi) +{ + using namespace amrex::literals; + amrex::Box domain_box = geom.Domain(); + if (patch_type == PatchType::coarse && (lev > 0)) { + domain_box.coarsen(ref_ratios[lev-1]); + } + amrex::IntVect const domain_lo = domain_box.smallEnd(); + amrex::IntVect const domain_hi = domain_box.bigEnd(); + amrex::GpuArray fbndry_lo; + amrex::GpuArray fbndry_hi; + for (int idim=0; idim < AMREX_SPACEDIM; ++idim) { + fbndry_lo[idim] = field_boundary_lo[idim]; + fbndry_hi[idim] = field_boundary_hi[idim]; + } + +#if (AMREX_SPACEDIM > 1) + amrex::ParserExecutor<2> const area_parsers_x_lo = m_insulator_area_lo[0]->compile<2>(); + amrex::ParserExecutor<2> const area_parsers_x_hi = m_insulator_area_hi[0]->compile<2>(); +#endif +#if defined(WARPX_DIM_3D) + amrex::ParserExecutor<2> const area_parsers_y_lo = m_insulator_area_lo[1]->compile<2>(); + amrex::ParserExecutor<2> const area_parsers_y_hi = m_insulator_area_hi[1]->compile<2>(); +#endif + amrex::ParserExecutor<2> const area_parsers_z_lo = m_insulator_area_lo[WARPX_ZINDEX]->compile<2>(); + amrex::ParserExecutor<2> const area_parsers_z_hi = m_insulator_area_hi[WARPX_ZINDEX]->compile<2>(); + +#if (AMREX_SPACEDIM > 1) + amrex::ParserExecutor<3> const Fy_x_lo_parser = a_Fy_x_lo->compile<3>(); + amrex::ParserExecutor<3> const Fz_x_lo_parser = a_Fz_x_lo->compile<3>(); + amrex::ParserExecutor<3> const Fy_x_hi_parser = a_Fy_x_hi->compile<3>(); + amrex::ParserExecutor<3> const Fz_x_hi_parser = a_Fz_x_hi->compile<3>(); +#endif +#if defined(WARPX_DIM_3D) + amrex::ParserExecutor<3> const Fx_y_lo_parser = a_Fx_y_lo->compile<3>(); + amrex::ParserExecutor<3> const Fz_y_lo_parser = a_Fz_y_lo->compile<3>(); + amrex::ParserExecutor<3> const Fx_y_hi_parser = a_Fx_y_hi->compile<3>(); + amrex::ParserExecutor<3> const Fz_y_hi_parser = a_Fz_y_hi->compile<3>(); +#endif + amrex::ParserExecutor<3> const Fx_z_lo_parser = a_Fx_z_lo->compile<3>(); + amrex::ParserExecutor<3> const Fy_z_lo_parser = a_Fy_z_lo->compile<3>(); + amrex::ParserExecutor<3> const Fx_z_hi_parser = a_Fx_z_hi->compile<3>(); + amrex::ParserExecutor<3> const Fy_z_hi_parser = a_Fy_z_hi->compile<3>(); + + amrex::IntVect const Fx_nodal = field[0]->ixType().toIntVect(); + amrex::IntVect const Fy_nodal = field[1]->ixType().toIntVect(); + amrex::IntVect const Fz_nodal = field[2]->ixType().toIntVect(); + // For each field multifab, apply boundary condition to ncomponents + // If not split field, the boundary condition is applied to the regular field used in Maxwell's eq. + // If split_pml_field is true, then boundary condition is applied to all the split field components. + int const nComp_x = field[0]->nComp(); + int const nComp_y = field[1]->nComp(); + int const nComp_z = field[2]->nComp(); + + std::array const & dx = WarpX::CellSize(lev); + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for (amrex::MFIter mfi(*field[0], amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) { + // Extract field data + amrex::Array4 const & Fx = field[0]->array(mfi); + amrex::Array4 const & Fy = field[1]->array(mfi); + amrex::Array4 const & Fz = field[2]->array(mfi); + + // Extract tileboxes for which to loop + // if split field, the box includes nodal flag + // For E-field used in Maxwell's update, nodal flag plus cells that particles + // gather fields from in the guard-cell region are included. + // Note that for simulations without particles or laser, ng_field_gather is 0 + // and the guard-cell values of the E-field multifab will not be modified. + amrex::Box const & tex = (split_pml_field) ? mfi.tilebox(field[0]->ixType().toIntVect()) + : mfi.tilebox(field[0]->ixType().toIntVect(), ng_fieldgather); + amrex::Box const & tey = (split_pml_field) ? mfi.tilebox(field[1]->ixType().toIntVect()) + : mfi.tilebox(field[1]->ixType().toIntVect(), ng_fieldgather); + amrex::Box const & tez = (split_pml_field) ? mfi.tilebox(field[2]->ixType().toIntVect()) + : mfi.tilebox(field[2]->ixType().toIntVect(), ng_fieldgather); + + const amrex::XDim3 xyzmin_x = WarpX::LowerCorner(tex, lev, 0._rt); + const amrex::XDim3 xyzmin_y = WarpX::LowerCorner(tey, lev, 0._rt); + const amrex::XDim3 xyzmin_z = WarpX::LowerCorner(tez, lev, 0._rt); + amrex::IntVect const lo_x = tex.smallEnd(); + amrex::IntVect const lo_y = tey.smallEnd(); + amrex::IntVect const lo_z = tez.smallEnd(); + + // loop over cells and update fields + amrex::ParallelFor( + tex, nComp_x, + [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { + amrex::ignore_unused(j, k); + + amrex::IntVect const iv(AMREX_D_DECL(i, j, k)); + amrex::Real const shiftx = (Fx_nodal[0] ? 0._rt : 0.5_rt); + amrex::Real const x = (AMREX_SPACEDIM > 1 ? xyzmin_x.x + (iv[0] - lo_x[0] + shiftx)*dx[0] : 0._rt); + amrex::Real const shifty = (AMREX_SPACEDIM == 3 ? (Fx_nodal[1] ? 0._rt : 0.5_rt) : 0._rt); + amrex::Real const y = (AMREX_SPACEDIM == 3 ? xyzmin_x.y + (iv[1] - lo_x[1] + shifty)*dx[1] : 0._rt); +#if (AMREX_SPACEDIM > 1) + amrex::Real const shiftz = (Fx_nodal[WARPX_ZINDEX] ? 0._rt : 0.5_rt); + amrex::Real const z = xyzmin_x.z + (iv[WARPX_ZINDEX] - lo_x[WARPX_ZINDEX] + shiftz)*dx[2]; +#endif + + amrex::IntVect is_insulator_lo; + amrex::IntVect is_insulator_hi; + amrex::RealVect F_lo, F_hi; + amrex::IntVect set_field_lo; + amrex::IntVect set_field_hi; +#if (AMREX_SPACEDIM > 1) + is_insulator_lo[0] = (area_parsers_x_lo(y, z) > 0._rt); + is_insulator_hi[0] = (area_parsers_x_hi(y, z) > 0._rt); + F_lo[0] = 0._rt; // Will be unused + F_hi[0] = 0._rt; // Will be unused + set_field_lo[0] = 0; // Will be unused + set_field_hi[0] = 0; // Will be unused +#endif +#if defined(WARPX_DIM_3D) + is_insulator_lo[1] = (area_parsers_y_lo(x, z) > 0._rt); + is_insulator_hi[1] = (area_parsers_y_hi(x, z) > 0._rt); + F_lo[1] = (set_F_y_lo ? Fx_y_lo_parser(x, z, time) : 0._rt); + F_hi[1] = (set_F_y_hi ? Fx_y_hi_parser(x, z, time) : 0._rt); + set_field_lo[1] = set_F_y_lo; + set_field_hi[1] = set_F_y_hi; +#endif + is_insulator_lo[WARPX_ZINDEX] = (area_parsers_z_lo(x, y) > 0._rt); + is_insulator_hi[WARPX_ZINDEX] = (area_parsers_z_hi(x, y) > 0._rt); + F_lo[WARPX_ZINDEX] = (set_F_z_lo ? Fx_z_lo_parser(x, y, time) : 0._rt); + F_hi[WARPX_ZINDEX] = (set_F_z_hi ? Fx_z_hi_parser(x, y, time) : 0._rt); + set_field_lo[WARPX_ZINDEX] = set_F_z_lo; + set_field_hi[WARPX_ZINDEX] = set_F_z_hi; + + int const icomp = 0; + ::SetFieldOnPEC_Insulator(icomp, domain_lo, domain_hi, iv, n, + Fx, E_like, Fx_nodal, is_insulator_lo, is_insulator_hi, + F_lo, F_hi, set_field_lo, set_field_hi, + fbndry_lo, fbndry_hi); + }, + tey, nComp_y, + [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { + amrex::ignore_unused(j, k); + + amrex::IntVect const iv(AMREX_D_DECL(i, j, k)); + amrex::Real const shiftx = (Fy_nodal[0] ? 0._rt : 0.5_rt); + amrex::Real const x = (AMREX_SPACEDIM > 1 ? xyzmin_y.x + (iv[0] - lo_y[0] + shiftx)*dx[0] : 0._rt); + amrex::Real const shifty = (AMREX_SPACEDIM == 3 ? (Fy_nodal[1] ? 0._rt : 0.5_rt) : 0._rt); + amrex::Real const y = (AMREX_SPACEDIM == 3 ? xyzmin_y.y + (iv[1] - lo_y[1] + shifty)*dx[1] : 0._rt); +#if (AMREX_SPACEDIM > 1) + amrex::Real const shiftz = (Fy_nodal[WARPX_ZINDEX] ? 0._rt : 0.5_rt); + amrex::Real const z = xyzmin_y.z + (iv[WARPX_ZINDEX] - lo_y[WARPX_ZINDEX] + shiftz)*dx[2]; +#endif + + amrex::IntVect is_insulator_lo; + amrex::IntVect is_insulator_hi; + amrex::RealVect F_lo, F_hi; + amrex::IntVect set_field_lo; + amrex::IntVect set_field_hi; +#if (AMREX_SPACEDIM > 1) + is_insulator_lo[0] = (area_parsers_x_lo(y, z) > 0._rt); + is_insulator_hi[0] = (area_parsers_x_hi(y, z) > 0._rt); + F_lo[0] = (set_F_x_lo ? Fy_x_lo_parser(y, z, time) : 0._rt); + F_hi[0] = (set_F_x_hi ? Fy_x_hi_parser(y, z, time) : 0._rt); + set_field_lo[0] = set_F_x_lo; + set_field_hi[0] = set_F_x_hi; +#endif +#if defined(WARPX_DIM_3D) + is_insulator_lo[1] = (area_parsers_y_lo(x, z) > 0._rt); + is_insulator_hi[1] = (area_parsers_y_hi(x, z) > 0._rt); + F_lo[1] = 0._rt; // Will be unused + F_hi[1] = 0._rt; // Will be unused + set_field_lo[1] = 0; // Will be unused + set_field_hi[1] = 0; // Will be unused +#endif + is_insulator_lo[WARPX_ZINDEX] = (area_parsers_z_lo(x, y) > 0._rt); + is_insulator_hi[WARPX_ZINDEX] = (area_parsers_z_hi(x, y) > 0._rt); + F_lo[WARPX_ZINDEX] = (set_F_z_lo ? Fy_z_lo_parser(x, y, time) : 0._rt); + F_hi[WARPX_ZINDEX] = (set_F_z_hi ? Fy_z_hi_parser(x, y, time) : 0._rt); + set_field_lo[WARPX_ZINDEX] = set_F_z_lo; + set_field_hi[WARPX_ZINDEX] = set_F_z_hi; + + int const icomp = 1; + ::SetFieldOnPEC_Insulator(icomp, domain_lo, domain_hi, iv, n, + Fy, E_like, Fy_nodal, is_insulator_lo, is_insulator_hi, + F_lo, F_hi, set_field_lo, set_field_hi, + fbndry_lo, fbndry_hi); + }, + tez, nComp_z, + [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { + amrex::ignore_unused(j, k); + + amrex::IntVect const iv(AMREX_D_DECL(i, j, k)); + amrex::Real const shiftx = (Fz_nodal[0] ? 0._rt : 0.5_rt); + amrex::Real const x = (AMREX_SPACEDIM > 1 ? xyzmin_z.x + (iv[0] - lo_z[0] + shiftx)*dx[0] : 0._rt); + amrex::Real const shifty = (AMREX_SPACEDIM == 3 ? (Fz_nodal[1] ? 0._rt : 0.5_rt) : 0._rt); + amrex::Real const y = (AMREX_SPACEDIM == 3 ? xyzmin_z.y + (iv[1] - lo_z[1] + shifty)*dx[1] : 0._rt); +#if (AMREX_SPACEDIM > 1) + amrex::Real const shiftz = (Fz_nodal[WARPX_ZINDEX] ? 0._rt : 0.5_rt); + amrex::Real const z = xyzmin_z.z + (iv[WARPX_ZINDEX] - lo_z[WARPX_ZINDEX] + shiftz)*dx[2]; +#endif + + amrex::IntVect is_insulator_lo; + amrex::IntVect is_insulator_hi; + amrex::RealVect F_lo, F_hi; + amrex::IntVect set_field_lo; + amrex::IntVect set_field_hi; +#if (AMREX_SPACEDIM > 1) + is_insulator_lo[0] = (area_parsers_x_lo(y, z) > 0._rt); + is_insulator_hi[0] = (area_parsers_x_hi(y, z) > 0._rt); + F_lo[0] = (set_F_x_lo ? Fz_x_lo_parser(y, z, time) : 0._rt); + F_hi[0] = (set_F_x_hi ? Fz_x_hi_parser(y, z, time) : 0._rt); + set_field_lo[0] = set_F_x_lo; + set_field_hi[0] = set_F_x_hi; +#endif +#if defined(WARPX_DIM_3D) + is_insulator_lo[1] = (area_parsers_y_lo(x, z) > 0._rt); + is_insulator_hi[1] = (area_parsers_y_hi(x, z) > 0._rt); + F_lo[1] = (set_F_y_lo ? Fz_y_lo_parser(x, z, time) : 0._rt); + F_hi[1] = (set_F_y_hi ? Fz_y_hi_parser(x, z, time) : 0._rt); + set_field_lo[1] = set_F_y_lo; + set_field_hi[1] = set_F_y_hi; +#endif + is_insulator_lo[WARPX_ZINDEX] = (area_parsers_z_lo(x, y) > 0._rt); + is_insulator_hi[WARPX_ZINDEX] = (area_parsers_z_hi(x, y) > 0._rt); + F_lo[WARPX_ZINDEX] = 0._rt; // Will be unused + F_hi[WARPX_ZINDEX] = 0._rt; // Will be unused + set_field_lo[WARPX_ZINDEX] = 0; // Will be unused + set_field_hi[WARPX_ZINDEX] = 0; // Will be unused + + int const icomp = 2; + ::SetFieldOnPEC_Insulator(icomp, domain_lo, domain_hi, iv, n, + Fz, E_like, Fz_nodal, is_insulator_lo, is_insulator_hi, + F_lo, F_hi, set_field_lo, set_field_hi, + fbndry_lo, fbndry_hi); + } + ); + } +} diff --git a/Source/BoundaryConditions/PEC_Insulator_fwd.H b/Source/BoundaryConditions/PEC_Insulator_fwd.H new file mode 100644 index 00000000000..9b2c1b05307 --- /dev/null +++ b/Source/BoundaryConditions/PEC_Insulator_fwd.H @@ -0,0 +1,13 @@ +/* Copyright 2024 David Grote + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#ifndef PEC_INSULATOR_FWD_H +#define PEC_INSULATOR_FWD_H + +class PEC_Insulator; + +#endif /* PEC_INSULATOR_FWD_H */ diff --git a/Source/BoundaryConditions/PML.H b/Source/BoundaryConditions/PML.H index 9e7dbc0034c..6be9600b9d9 100644 --- a/Source/BoundaryConditions/PML.H +++ b/Source/BoundaryConditions/PML.H @@ -81,10 +81,10 @@ class SigmaBoxFactory : public amrex::FabFactory { public: - SigmaBoxFactory (const amrex::BoxArray& grid_ba, const amrex::Real* dx, + SigmaBoxFactory (const amrex::BoxArray* grid_ba, const amrex::Real* dx, const amrex::IntVect& ncell, const amrex::IntVect& delta, const amrex::Box& regular_domain, const amrex::Real v_sigma_sb) - : m_grids(grid_ba), m_dx(dx), m_ncell(ncell), m_delta(delta), m_regdomain(regular_domain), m_v_sigma_sb(v_sigma_sb) {} + : m_grids{grid_ba}, m_dx(dx), m_ncell(ncell), m_delta(delta), m_regdomain(regular_domain), m_v_sigma_sb(v_sigma_sb) {} ~SigmaBoxFactory () override = default; SigmaBoxFactory (const SigmaBoxFactory&) = default; @@ -97,7 +97,7 @@ public: [[nodiscard]] SigmaBox* create (const amrex::Box& box, int /*ncomps*/, const amrex::FabInfo& /*info*/, int /*box_index*/) const final { - return new SigmaBox(box, m_grids, m_dx, m_ncell, m_delta, m_regdomain, m_v_sigma_sb); + return new SigmaBox(box, *m_grids, m_dx, m_ncell, m_delta, m_regdomain, m_v_sigma_sb); } void destroy (SigmaBox* fab) const final @@ -112,7 +112,7 @@ public: } private: - const amrex::BoxArray& m_grids; + const amrex::BoxArray* m_grids; const amrex::Real* m_dx; amrex::IntVect m_ncell; amrex::IntVect m_delta; @@ -125,7 +125,7 @@ class MultiSigmaBox { public: MultiSigmaBox(const amrex::BoxArray& ba, const amrex::DistributionMapping& dm, - const amrex::BoxArray& grid_ba, const amrex::Real* dx, + const amrex::BoxArray* grid_ba, const amrex::Real* dx, const amrex::IntVect& ncell, const amrex::IntVect& delta, const amrex::Box& regular_domain, amrex::Real v_sigma_sb); void ComputePMLFactorsB (const amrex::Real* dx, amrex::Real dt); @@ -204,8 +204,8 @@ private: bool m_dive_cleaning; bool m_divb_cleaning; - const amrex::IntVect m_fill_guards_fields; - const amrex::IntVect m_fill_guards_current; + amrex::IntVect m_fill_guards_fields; + amrex::IntVect m_fill_guards_current; const amrex::Geometry* m_geom; const amrex::Geometry* m_cgeom; diff --git a/Source/BoundaryConditions/PML.cpp b/Source/BoundaryConditions/PML.cpp index f45ca222e69..195642ade2c 100644 --- a/Source/BoundaryConditions/PML.cpp +++ b/Source/BoundaryConditions/PML.cpp @@ -11,6 +11,9 @@ #include "BoundaryConditions/PML.H" #include "BoundaryConditions/PMLComponent.H" #include "Fields.H" +#ifdef AMREX_USE_EB +# include "EmbeddedBoundary/EmbeddedBoundaryInit.H" +#endif #ifdef WARPX_USE_FFT # include "FieldSolver/SpectralSolver/SpectralFieldData.H" #endif @@ -506,7 +509,7 @@ SigmaBox::ComputePMLFactorsE (const Real* a_dx, Real dt) } MultiSigmaBox::MultiSigmaBox (const BoxArray& ba, const DistributionMapping& dm, - const BoxArray& grid_ba, const Real* dx, + const BoxArray* grid_ba, const Real* dx, const IntVect& ncell, const IntVect& delta, const amrex::Box& regular_domain, const amrex::Real v_sigma_sb) : FabArray(ba,dm,1,0,MFInfo(), @@ -738,8 +741,8 @@ PML::PML (const int lev, const BoxArray& grid_ba, auto const eb_fact = fieldEBFactory(); ablastr::fields::VectorField t_pml_edge_lengths = warpx.m_fields.get_alldirs(FieldType::pml_edge_lengths, lev); - WarpX::ComputeEdgeLengths(t_pml_edge_lengths, eb_fact); - WarpX::ScaleEdges(t_pml_edge_lengths, WarpX::CellSize(lev)); + warpx::embedded_boundary::ComputeEdgeLengths(t_pml_edge_lengths, eb_fact); + warpx::embedded_boundary::ScaleEdges(t_pml_edge_lengths, WarpX::CellSize(lev)); } } @@ -764,7 +767,7 @@ PML::PML (const int lev, const BoxArray& grid_ba, Box single_domain_box = is_single_box_domain ? domain0 : Box(); // Empty box (i.e., Box()) means it's not a single box domain. - sigba_fp = std::make_unique(ba, dm, grid_ba_reduced, geom->CellSize(), + sigba_fp = std::make_unique(ba, dm, &grid_ba_reduced, geom->CellSize(), IntVect(ncell), IntVect(delta), single_domain_box, v_sigma_sb); if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD) { @@ -879,7 +882,7 @@ PML::PML (const int lev, const BoxArray& grid_ba, warpx.m_fields.alloc_init(FieldType::pml_j_cp, Direction{2}, lev, cba_jz, cdm, 1, ngb, 0.0_rt, false, false); single_domain_box = is_single_box_domain ? cdomain : Box(); - sigba_cp = std::make_unique(cba, cdm, grid_cba_reduced, cgeom->CellSize(), + sigba_cp = std::make_unique(cba, cdm, &grid_cba_reduced, cgeom->CellSize(), cncells, cdelta, single_domain_box, v_sigma_sb); if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD) { @@ -1298,16 +1301,16 @@ PML::PushPSATD (ablastr::fields::MultiFabRegister& fields, const int lev) { ablastr::fields::VectorField pml_E_fp = fields.get_alldirs(FieldType::pml_E_fp, lev); ablastr::fields::VectorField pml_B_fp = fields.get_alldirs(FieldType::pml_B_fp, lev); - ablastr::fields::ScalarField pml_F_fp = fields.get(FieldType::pml_F_fp, lev); - ablastr::fields::ScalarField pml_G_fp = fields.get(FieldType::pml_G_fp, lev); + ablastr::fields::ScalarField pml_F_fp = (fields.has(FieldType::pml_F_fp, lev)) ? fields.get(FieldType::pml_F_fp, lev) : nullptr; + ablastr::fields::ScalarField pml_G_fp = (fields.has(FieldType::pml_G_fp, lev)) ? fields.get(FieldType::pml_G_fp, lev) : nullptr; // Update the fields on the fine and coarse patch PushPMLPSATDSinglePatch(lev, *spectral_solver_fp, pml_E_fp, pml_B_fp, pml_F_fp, pml_G_fp, m_fill_guards_fields); if (spectral_solver_cp) { ablastr::fields::VectorField pml_E_cp = fields.get_alldirs(FieldType::pml_E_cp, lev); ablastr::fields::VectorField pml_B_cp = fields.get_alldirs(FieldType::pml_B_cp, lev); - ablastr::fields::ScalarField pml_F_cp = fields.get(FieldType::pml_F_cp, lev); - ablastr::fields::ScalarField pml_G_cp = fields.get(FieldType::pml_G_cp, lev); + ablastr::fields::ScalarField pml_F_cp = (fields.has(FieldType::pml_F_cp, lev)) ? fields.get(FieldType::pml_F_cp, lev) : nullptr; + ablastr::fields::ScalarField pml_G_cp = (fields.has(FieldType::pml_G_cp, lev)) ? fields.get(FieldType::pml_G_cp, lev) : nullptr; PushPMLPSATDSinglePatch(lev, *spectral_solver_cp, pml_E_cp, pml_B_cp, pml_F_cp, pml_G_cp, m_fill_guards_fields); } } diff --git a/Source/BoundaryConditions/PML_RZ.H b/Source/BoundaryConditions/PML_RZ.H index 20c7d360fc7..5508836a171 100644 --- a/Source/BoundaryConditions/PML_RZ.H +++ b/Source/BoundaryConditions/PML_RZ.H @@ -53,8 +53,8 @@ public: private: - const int m_ncell; - const int m_do_pml_in_domain; + int m_ncell; + int m_do_pml_in_domain; const amrex::Geometry* m_geom; // The MultiFabs pml_E_fp and pml_B_fp are setup using the registry. diff --git a/Source/BoundaryConditions/WarpXFieldBoundaries.cpp b/Source/BoundaryConditions/WarpXFieldBoundaries.cpp index dc41e95f40f..6217eb04a33 100644 --- a/Source/BoundaryConditions/WarpXFieldBoundaries.cpp +++ b/Source/BoundaryConditions/WarpXFieldBoundaries.cpp @@ -1,4 +1,5 @@ #include "WarpX.H" +#include "BoundaryConditions/PEC_Insulator.H" #include "BoundaryConditions/PML.H" #include "FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H" #include "FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H" @@ -48,17 +49,15 @@ namespace } -void WarpX::ApplyEfieldBoundary(const int lev, PatchType patch_type) +void WarpX::ApplyEfieldBoundary(const int lev, PatchType patch_type, amrex::Real time) { using ablastr::fields::Direction; if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { if (patch_type == PatchType::fine) { PEC::ApplyPECtoEfield( - {m_fields.get(FieldType::Efield_fp, Direction{0}, lev), - m_fields.get(FieldType::Efield_fp, Direction{1}, lev), - m_fields.get(FieldType::Efield_fp, Direction{2}, lev)}, - field_boundary_lo, field_boundary_hi, + m_fields.get_alldirs(FieldType::Efield_fp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, get_ng_fieldgather(), Geom(lev), lev, patch_type, ref_ratio); if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { @@ -66,27 +65,101 @@ void WarpX::ApplyEfieldBoundary(const int lev, PatchType patch_type) const bool split_pml_field = true; PEC::ApplyPECtoEfield( m_fields.get_alldirs(FieldType::pml_E_fp, lev), - field_boundary_lo, field_boundary_hi, + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, get_ng_fieldgather(), Geom(lev), lev, patch_type, ref_ratio, split_pml_field); } } else { PEC::ApplyPECtoEfield( + m_fields.get_alldirs(FieldType::Efield_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio); + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + // apply pec on split E-fields in PML region + const bool split_pml_field = true; + PEC::ApplyPECtoEfield( + m_fields.get_alldirs(FieldType::pml_E_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, + split_pml_field); + } + } + } + + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + if (patch_type == PatchType::fine) { + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::Efield_fp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio); + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + // apply pec on split E-fields in PML region + const bool split_pml_field = true; + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::pml_E_fp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, + split_pml_field); + } + } else { + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::Efield_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio); + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + // apply pec on split E-fields in PML region + const bool split_pml_field = true; + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::pml_E_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, + split_pml_field); + } + } + } + + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + if (patch_type == PatchType::fine) { + pec_insulator_boundary->ApplyPEC_InsulatortoEfield( + {m_fields.get(FieldType::Efield_fp,Direction{0},lev), + m_fields.get(FieldType::Efield_fp,Direction{1},lev), + m_fields.get(FieldType::Efield_fp,Direction{2},lev)}, + field_boundary_lo, field_boundary_hi, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, time); + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + // apply pec on split E-fields in PML region + const bool split_pml_field = true; + pec_insulator_boundary->ApplyPEC_InsulatortoEfield( + m_fields.get_alldirs(FieldType::pml_E_fp, lev), + field_boundary_lo, field_boundary_hi, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, time, + split_pml_field); + } + } else { + pec_insulator_boundary->ApplyPEC_InsulatortoEfield( {m_fields.get(FieldType::Efield_cp,Direction{0},lev), m_fields.get(FieldType::Efield_cp,Direction{1},lev), m_fields.get(FieldType::Efield_cp,Direction{2},lev)}, field_boundary_lo, field_boundary_hi, get_ng_fieldgather(), Geom(lev), - lev, patch_type, ref_ratio); + lev, patch_type, ref_ratio, time); if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { // apply pec on split E-fields in PML region const bool split_pml_field = true; - PEC::ApplyPECtoEfield( + pec_insulator_boundary->ApplyPEC_InsulatortoEfield( m_fields.get_alldirs(FieldType::pml_E_cp, lev), field_boundary_lo, field_boundary_hi, get_ng_fieldgather(), Geom(lev), - lev, patch_type, ref_ratio, + lev, patch_type, ref_ratio, time, split_pml_field); } } @@ -105,30 +178,62 @@ void WarpX::ApplyEfieldBoundary(const int lev, PatchType patch_type) #endif } -void WarpX::ApplyBfieldBoundary (const int lev, PatchType patch_type, DtType a_dt_type) +void WarpX::ApplyBfieldBoundary (const int lev, PatchType patch_type, DtType a_dt_type, amrex::Real time) { using ablastr::fields::Direction; if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { if (patch_type == PatchType::fine) { - PEC::ApplyPECtoBfield( { - m_fields.get(FieldType::Bfield_fp,Direction{0},lev), - m_fields.get(FieldType::Bfield_fp,Direction{1},lev), - m_fields.get(FieldType::Bfield_fp,Direction{2},lev) }, - field_boundary_lo, field_boundary_hi, + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::Bfield_fp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, get_ng_fieldgather(), Geom(lev), lev, patch_type, ref_ratio); } else { - PEC::ApplyPECtoBfield( { - m_fields.get(FieldType::Bfield_cp,Direction{0},lev), - m_fields.get(FieldType::Bfield_cp,Direction{1},lev), - m_fields.get(FieldType::Bfield_cp,Direction{2},lev) }, - field_boundary_lo, field_boundary_hi, + PEC::ApplyPECtoBfield( + m_fields.get_alldirs(FieldType::Bfield_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PEC, get_ng_fieldgather(), Geom(lev), lev, patch_type, ref_ratio); } } + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + if (patch_type == PatchType::fine) { + PEC::ApplyPECtoEfield( + m_fields.get_alldirs(FieldType::Bfield_fp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio); + } else { + PEC::ApplyPECtoEfield( + m_fields.get_alldirs(FieldType::Bfield_cp, lev), + field_boundary_lo, field_boundary_hi, FieldBoundaryType::PMC, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio); + } + } + + if (::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { + if (patch_type == PatchType::fine) { + pec_insulator_boundary->ApplyPEC_InsulatortoBfield( + {m_fields.get(FieldType::Bfield_fp,Direction{0},lev), + m_fields.get(FieldType::Bfield_fp,Direction{1},lev), + m_fields.get(FieldType::Bfield_fp,Direction{2},lev)}, + field_boundary_lo, field_boundary_hi, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, time); + } else { + pec_insulator_boundary->ApplyPEC_InsulatortoBfield( + {m_fields.get(FieldType::Bfield_cp,Direction{0},lev), + m_fields.get(FieldType::Bfield_cp,Direction{1},lev), + m_fields.get(FieldType::Bfield_cp,Direction{2},lev)}, + field_boundary_lo, field_boundary_hi, + get_ng_fieldgather(), Geom(lev), + lev, patch_type, ref_ratio, time); + } + } + // Silver-Mueller boundaries are only applied on the first half-push of B // This is because the formula used for Silver-Mueller assumes that // E and B are staggered in time, which is only true after the first half-push @@ -163,7 +268,8 @@ void WarpX::ApplyRhofieldBoundary (const int lev, MultiFab* rho, { if (::isAnyBoundary(particle_boundary_lo, particle_boundary_hi) || ::isAnyBoundary(particle_boundary_lo, particle_boundary_hi) || - ::isAnyBoundary(field_boundary_lo, field_boundary_hi)) + ::isAnyBoundary(field_boundary_lo, field_boundary_hi) || + ::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { PEC::ApplyReflectiveBoundarytoRhofield(rho, field_boundary_lo, field_boundary_hi, @@ -178,7 +284,8 @@ void WarpX::ApplyJfieldBoundary (const int lev, amrex::MultiFab* Jx, { if (::isAnyBoundary(particle_boundary_lo, particle_boundary_hi) || ::isAnyBoundary(particle_boundary_lo, particle_boundary_hi) || - ::isAnyBoundary(field_boundary_lo, field_boundary_hi)) + ::isAnyBoundary(field_boundary_lo, field_boundary_hi) || + ::isAnyBoundary(field_boundary_lo, field_boundary_hi)) { PEC::ApplyReflectiveBoundarytoJfield(Jx, Jy, Jz, field_boundary_lo, field_boundary_hi, diff --git a/Source/BoundaryConditions/WarpX_PEC.H b/Source/BoundaryConditions/WarpX_PEC.H index c387d8c1793..e3fd804b62c 100644 --- a/Source/BoundaryConditions/WarpX_PEC.H +++ b/Source/BoundaryConditions/WarpX_PEC.H @@ -33,6 +33,7 @@ namespace PEC { std::array Efield, const amrex::Array& field_boundary_lo, const amrex::Array& field_boundary_hi, + FieldBoundaryType bc_type, const amrex::IntVect& ng_fieldgather, const amrex::Geometry& geom, int lev, PatchType patch_type, const amrex::Vector& ref_ratios, bool split_pml_field = false); @@ -54,8 +55,10 @@ namespace PEC { std::array Bfield, const amrex::Array& field_boundary_lo, const amrex::Array& field_boundary_hi, + FieldBoundaryType bc_type, const amrex::IntVect& ng_fieldgather, const amrex::Geometry& geom, - int lev, PatchType patch_type, const amrex::Vector& ref_ratios); + int lev, PatchType patch_type, const amrex::Vector& ref_ratios, + bool split_pml_field = false); /** * \brief Reflects charge density deposited over the PEC boundary back into diff --git a/Source/BoundaryConditions/WarpX_PEC.cpp b/Source/BoundaryConditions/WarpX_PEC.cpp index bedc5b264b7..a3b75791582 100644 --- a/Source/BoundaryConditions/WarpX_PEC.cpp +++ b/Source/BoundaryConditions/WarpX_PEC.cpp @@ -121,7 +121,8 @@ namespace amrex::Array4 const& Efield, const amrex::IntVect& is_nodal, amrex::GpuArray const& fbndry_lo, - amrex::GpuArray const& fbndry_hi ) + amrex::GpuArray const& fbndry_hi, + FieldBoundaryType bc_type) { // Tangential Efield components in guard cells set equal and opposite to cells // in the mirror locations across the PEC boundary, whereas normal E-field @@ -136,8 +137,8 @@ namespace // Loop over sides, iside = 0 (lo), iside = 1 (hi) for (int iside = 0; iside < 2; ++iside) { const bool isPECBoundary = ( (iside == 0) - ? fbndry_lo[idim] == FieldBoundaryType::PEC - : fbndry_hi[idim] == FieldBoundaryType::PEC ); + ? fbndry_lo[idim] == bc_type + : fbndry_hi[idim] == bc_type ); #if (defined WARPX_DIM_XZ) || (defined WARPX_DIM_RZ) // For 2D : for icomp==1, (Ey in XZ, Etheta in RZ), // icomp=1 is tangential to both x and z boundaries @@ -260,7 +261,8 @@ namespace amrex::Array4 const& Bfield, const amrex::IntVect & is_nodal, amrex::GpuArray const& fbndry_lo, - amrex::GpuArray const& fbndry_hi ) + amrex::GpuArray const& fbndry_hi, + FieldBoundaryType bc_type) { amrex::IntVect ijk_mirror = ijk_vec; bool OnPECBoundary = false; @@ -271,8 +273,8 @@ namespace // Loop over sides, iside = 0 (lo), iside = 1 (hi) for (int iside = 0; iside < 2; ++iside) { const bool isPECBoundary = ( (iside == 0) - ? fbndry_lo[idim] == FieldBoundaryType::PEC - : fbndry_hi[idim] == FieldBoundaryType::PEC ); + ? fbndry_lo[idim] == bc_type + : fbndry_hi[idim] == bc_type ); if (isPECBoundary) { #if (defined WARPX_DIM_XZ) || (defined WARPX_DIM_RZ) // For 2D : for icomp==1, (By in XZ, Btheta in RZ), @@ -357,7 +359,7 @@ namespace amrex::Array4 const& field, amrex::GpuArray, AMREX_SPACEDIM> const& mirrorfac, amrex::GpuArray, AMREX_SPACEDIM> const& psign, - amrex::GpuArray, AMREX_SPACEDIM> const& is_reflective, + amrex::GpuArray, AMREX_SPACEDIM> const& is_reflective, amrex::GpuArray const& tangent_to_bndy, amrex::Box const& fabbox) { @@ -374,11 +376,11 @@ namespace amrex::IntVect iv_mirror = ijk_vec; iv_mirror[idim] = mirrorfac[idim][iside] - ijk_vec[idim]; - // On the PEC boundary the charge/current density is set to 0 - if (ijk_vec == iv_mirror) { - field(ijk_vec, n) = 0._rt; - // otherwise update the internal cell if the mirror guard cell exists + // Update the cell if the mirror guard cell exists + if (ijk_vec == iv_mirror && is_reflective[idim][iside] == 1) { + field(ijk_vec,n) = 0._rt; } else if (fabbox.contains(iv_mirror)) { + // Note that this includes the cells on the boundary for PMC field(ijk_vec,n) += psign[idim][iside] * field(iv_mirror,n); } } @@ -459,6 +461,7 @@ PEC::ApplyPECtoEfield ( std::array Efield, const amrex::Array& field_boundary_lo, const amrex::Array& field_boundary_hi, + FieldBoundaryType bc_type, const amrex::IntVect& ng_fieldgather, const amrex::Geometry& geom, const int lev, PatchType patch_type, const amrex::Vector& ref_ratios, const bool split_pml_field) @@ -514,7 +517,7 @@ PEC::ApplyPECtoEfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 0; ::SetEfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - Ex, Ex_nodal, fbndry_lo, fbndry_hi); + Ex, Ex_nodal, fbndry_lo, fbndry_hi, bc_type); }, tey, nComp_y, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { @@ -522,7 +525,7 @@ PEC::ApplyPECtoEfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 1; ::SetEfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - Ey, Ey_nodal, fbndry_lo, fbndry_hi); + Ey, Ey_nodal, fbndry_lo, fbndry_hi, bc_type); }, tez, nComp_z, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { @@ -530,7 +533,7 @@ PEC::ApplyPECtoEfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 2; ::SetEfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - Ez, Ez_nodal, fbndry_lo, fbndry_hi); + Ez, Ez_nodal, fbndry_lo, fbndry_hi, bc_type); } ); } @@ -542,8 +545,10 @@ PEC::ApplyPECtoBfield ( std::array Bfield, const amrex::Array& field_boundary_lo, const amrex::Array& field_boundary_hi, + FieldBoundaryType bc_type, const amrex::IntVect& ng_fieldgather, const amrex::Geometry& geom, - const int lev, PatchType patch_type, const amrex::Vector& ref_ratios) + const int lev, PatchType patch_type, const amrex::Vector& ref_ratios, + const bool split_pml_field) { amrex::Box domain_box = geom.Domain(); if (patch_type == PatchType::coarse && (lev > 0)) { @@ -579,9 +584,12 @@ PEC::ApplyPECtoBfield ( // gather fields from in the guard-cell region are included. // Note that for simulations without particles or laser, ng_field_gather is 0 // and the guard-cell values of the B-field multifab will not be modified. - amrex::Box const& tbx = mfi.tilebox(Bfield[0]->ixType().toIntVect(), ng_fieldgather); - amrex::Box const& tby = mfi.tilebox(Bfield[1]->ixType().toIntVect(), ng_fieldgather); - amrex::Box const& tbz = mfi.tilebox(Bfield[2]->ixType().toIntVect(), ng_fieldgather); + amrex::Box const& tbx = (split_pml_field) ? mfi.tilebox(Bfield[0]->ixType().toIntVect()) + : mfi.tilebox(Bfield[0]->ixType().toIntVect(), ng_fieldgather); + amrex::Box const& tby = (split_pml_field) ? mfi.tilebox(Bfield[1]->ixType().toIntVect()) + : mfi.tilebox(Bfield[1]->ixType().toIntVect(), ng_fieldgather); + amrex::Box const& tbz = (split_pml_field) ? mfi.tilebox(Bfield[2]->ixType().toIntVect()) + : mfi.tilebox(Bfield[2]->ixType().toIntVect(), ng_fieldgather); // loop over cells and update fields amrex::ParallelFor( @@ -591,7 +599,7 @@ PEC::ApplyPECtoBfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 0; ::SetBfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - Bx, Bx_nodal, fbndry_lo, fbndry_hi); + Bx, Bx_nodal, fbndry_lo, fbndry_hi, bc_type); }, tby, nComp_y, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { @@ -599,7 +607,7 @@ PEC::ApplyPECtoBfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 1; ::SetBfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - By, By_nodal, fbndry_lo, fbndry_hi); + By, By_nodal, fbndry_lo, fbndry_hi, bc_type); }, tbz, nComp_z, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { @@ -607,7 +615,7 @@ PEC::ApplyPECtoBfield ( const amrex::IntVect iv(AMREX_D_DECL(i,j,k)); const int icomp = 2; ::SetBfieldOnPEC(icomp, domain_lo, domain_hi, iv, n, - Bz, Bz_nodal, fbndry_lo, fbndry_hi); + Bz, Bz_nodal, fbndry_lo, fbndry_hi, bc_type); } ); } @@ -650,7 +658,7 @@ PEC::ApplyReflectiveBoundarytoRhofield ( // cells for boundaries that are NOT PEC amrex::Box grown_domain_box = domain_box; - amrex::GpuArray, AMREX_SPACEDIM> is_reflective; + amrex::GpuArray, AMREX_SPACEDIM> is_reflective; amrex::GpuArray is_tangent_to_bndy; amrex::GpuArray, AMREX_SPACEDIM> psign; amrex::GpuArray, AMREX_SPACEDIM> mirrorfac; @@ -658,9 +666,11 @@ PEC::ApplyReflectiveBoundarytoRhofield ( is_reflective[idim][0] = ( particle_boundary_lo[idim] == ParticleBoundaryType::Reflecting) || ( particle_boundary_lo[idim] == ParticleBoundaryType::Thermal) || ( field_boundary_lo[idim] == FieldBoundaryType::PEC); + if (field_boundary_lo[idim] == FieldBoundaryType::PMC) { is_reflective[idim][0] = 2; } is_reflective[idim][1] = ( particle_boundary_hi[idim] == ParticleBoundaryType::Reflecting) || ( particle_boundary_hi[idim] == ParticleBoundaryType::Thermal) || ( field_boundary_hi[idim] == FieldBoundaryType::PEC); + if (field_boundary_hi[idim] == FieldBoundaryType::PMC) { is_reflective[idim][1] = 2; } if (!is_reflective[idim][0]) { grown_domain_box.growLo(idim, ng_fieldgather[idim]); } if (!is_reflective[idim][1]) { grown_domain_box.growHi(idim, ng_fieldgather[idim]); } @@ -669,10 +679,12 @@ PEC::ApplyReflectiveBoundarytoRhofield ( is_tangent_to_bndy[idim] = true; psign[idim][0] = ((particle_boundary_lo[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_lo[idim] == FieldBoundaryType::PMC)) ? 1._rt : -1._rt; psign[idim][1] = ((particle_boundary_hi[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_hi[idim] == FieldBoundaryType::PMC)) ? 1._rt : -1._rt; mirrorfac[idim][0] = 2*domain_lo[idim] - (1 - rho_nodal[idim]); mirrorfac[idim][1] = 2*domain_hi[idim] + (1 - rho_nodal[idim]); @@ -746,17 +758,21 @@ PEC::ApplyReflectiveBoundarytoJfield( // directions of the current density multifab const amrex::IntVect ng_fieldgather = Jx->nGrowVect(); - amrex::GpuArray, AMREX_SPACEDIM> is_reflective; + amrex::GpuArray, AMREX_SPACEDIM> is_reflective; amrex::GpuArray, 3> is_tangent_to_bndy; amrex::GpuArray, AMREX_SPACEDIM>, 3> psign; amrex::GpuArray, AMREX_SPACEDIM>, 3> mirrorfac; for (int idim=0; idim < AMREX_SPACEDIM; ++idim) { is_reflective[idim][0] = ( particle_boundary_lo[idim] == ParticleBoundaryType::Reflecting) || ( particle_boundary_lo[idim] == ParticleBoundaryType::Thermal) - || ( field_boundary_lo[idim] == FieldBoundaryType::PEC); + || ( field_boundary_lo[idim] == FieldBoundaryType::PEC) + || ( field_boundary_lo[idim] == FieldBoundaryType::PMC); + if (field_boundary_lo[idim] == FieldBoundaryType::PMC) { is_reflective[idim][0] = 2; } is_reflective[idim][1] = ( particle_boundary_hi[idim] == ParticleBoundaryType::Reflecting) || ( particle_boundary_hi[idim] == ParticleBoundaryType::Thermal) - || ( field_boundary_hi[idim] == FieldBoundaryType::PEC); + || ( field_boundary_hi[idim] == FieldBoundaryType::PEC) + || ( field_boundary_hi[idim] == FieldBoundaryType::PMC); + if (field_boundary_hi[idim] == FieldBoundaryType::PMC) { is_reflective[idim][1] = 2; } if (!is_reflective[idim][0]) { grown_domain_box.growLo(idim, ng_fieldgather[idim]); } if (!is_reflective[idim][1]) { grown_domain_box.growHi(idim, ng_fieldgather[idim]); } @@ -778,18 +794,22 @@ PEC::ApplyReflectiveBoundarytoJfield( if (is_tangent_to_bndy[icomp][idim]){ psign[icomp][idim][0] = ( (particle_boundary_lo[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_lo[idim] == FieldBoundaryType::PMC)) ? 1._rt : -1._rt; psign[icomp][idim][1] = ( (particle_boundary_hi[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_hi[idim] == FieldBoundaryType::PMC)) ? 1._rt : -1._rt; } else { psign[icomp][idim][0] = ( (particle_boundary_lo[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_lo[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_lo[idim] == FieldBoundaryType::PMC)) ? -1._rt : 1._rt; psign[icomp][idim][1] = ( (particle_boundary_hi[idim] == ParticleBoundaryType::Reflecting) - ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal)) + ||(particle_boundary_hi[idim] == ParticleBoundaryType::Thermal) + ||(field_boundary_hi[idim] == FieldBoundaryType::PMC)) ? -1._rt : 1._rt; } } diff --git a/Source/Diagnostics/BTDiagnostics.H b/Source/Diagnostics/BTDiagnostics.H index c7137f45c9d..f4f118892a8 100644 --- a/Source/Diagnostics/BTDiagnostics.H +++ b/Source/Diagnostics/BTDiagnostics.H @@ -242,7 +242,7 @@ private: * will be used by all snapshots to obtain lab-frame data at the respective * z slice location. */ - std::string const m_cell_centered_data_name; + std::string m_cell_centered_data_name; /** Vector of pointers to compute cell-centered data, per level, per component * using the coarsening-ratio provided by the user. */ diff --git a/Source/Diagnostics/BTDiagnostics.cpp b/Source/Diagnostics/BTDiagnostics.cpp index 4939e2fb207..cae2d2bbc03 100644 --- a/Source/Diagnostics/BTDiagnostics.cpp +++ b/Source/Diagnostics/BTDiagnostics.cpp @@ -1091,7 +1091,7 @@ BTDiagnostics::Flush (int i_buffer, bool force_flush) m_varnames, m_mf_output.at(i_buffer), m_geom_output.at(i_buffer), warpx.getistep(), labtime, m_output_species.at(i_buffer), nlev_output, file_name, m_file_min_digits, - m_plot_raw_fields, m_plot_raw_fields_guards, + m_plot_raw_fields, m_plot_raw_fields_guards, m_verbose, use_pinned_pc, isBTD, i_buffer, m_buffer_flush_counter.at(i_buffer), m_max_buffer_multifabs.at(i_buffer), m_geom_snapshot.at(i_buffer).at(0), isLastBTDFlush); @@ -1462,6 +1462,17 @@ BTDiagnostics::InitializeParticleBuffer () m_totalParticles_in_buffer[i][isp] = 0; m_particles_buffer[i][isp] = std::make_unique(WarpX::GetInstance().GetParGDB()); const int idx = mpc.getSpeciesID(m_output_species_names[isp]); + + // SoA component names + { + auto &pc = mpc.GetParticleContainer(idx); + auto rn = pc.GetRealSoANames(); + rn.resize(WarpXParticleContainer::NArrayReal); // strip runtime comps + auto in = pc.GetRealSoANames(); + in.resize(WarpXParticleContainer::NArrayInt); // strip runtime comps + m_particles_buffer[i][isp]->SetSoACompileTimeNames(rn, in); + } + m_output_species[i].push_back(ParticleDiag(m_diag_name, m_output_species_names[isp], mpc.GetParticleContainerPtr(idx), diff --git a/Source/Diagnostics/BoundaryScrapingDiagnostics.cpp b/Source/Diagnostics/BoundaryScrapingDiagnostics.cpp index 8df58b6fb28..bcccda48c18 100644 --- a/Source/Diagnostics/BoundaryScrapingDiagnostics.cpp +++ b/Source/Diagnostics/BoundaryScrapingDiagnostics.cpp @@ -153,7 +153,7 @@ BoundaryScrapingDiagnostics::Flush (int i_buffer, bool /* force_flush */) warpx.gett_new(0), m_output_species.at(i_buffer), nlev_output, file_prefix, - m_file_min_digits, false, false, use_pinned_pc, isBTD, + m_file_min_digits, false, false, m_verbose, use_pinned_pc, isBTD, warpx.getistep(0), bufferID, numBTDBuffers, geom, isLastBTD); diff --git a/Source/Diagnostics/CMakeLists.txt b/Source/Diagnostics/CMakeLists.txt index 376487dc94a..d899bd5e155 100644 --- a/Source/Diagnostics/CMakeLists.txt +++ b/Source/Diagnostics/CMakeLists.txt @@ -7,7 +7,6 @@ foreach(D IN LISTS WarpX_DIMS) FullDiagnostics.cpp MultiDiagnostics.cpp ParticleIO.cpp - SliceDiagnostic.cpp WarpXIO.cpp WarpXOpenPMD.cpp BTDiagnostics.cpp diff --git a/Source/Diagnostics/ComputeDiagFunctors/BackTransformFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/BackTransformFunctor.H index bef40ae1ce0..c4410b0a722 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/BackTransformFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/BackTransformFunctor.H @@ -100,11 +100,11 @@ public: amrex::Real beta_boost) const; private: /** pointer to source multifab (cell-centered multi-component multifab) */ - amrex::MultiFab const * const m_mf_src = nullptr; + const amrex::MultiFab* m_mf_src = nullptr; /** level at which m_mf_src is defined */ - int const m_lev; + int m_lev; /** Number of buffers or snapshots */ - int const m_num_buffers; + int m_num_buffers; /** Vector of amrex::Box with index-space in the lab-frame */ amrex::Vector m_buffer_box; /** Vector of current z co-ordinate in the boosted-frame for each buffer */ diff --git a/Source/Diagnostics/ComputeDiagFunctors/CellCenterFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/CellCenterFunctor.H index dd5bb239ecf..6f0818b180e 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/CellCenterFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/CellCenterFunctor.H @@ -36,7 +36,7 @@ public: void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: /** pointer to source multifab (can be multi-component) */ - amrex::MultiFab const * const m_mf_src = nullptr; + const amrex::MultiFab* m_mf_src = nullptr; int m_lev; /**< level on which mf_src is defined (used in cylindrical) */ /**< (for cylindrical) whether to average all modes into 1 comp */ bool m_convertRZmodes2cartesian; diff --git a/Source/Diagnostics/ComputeDiagFunctors/DivBFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/DivBFunctor.H index 1d36b434ae2..347c40e0338 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/DivBFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/DivBFunctor.H @@ -42,7 +42,7 @@ public: private: /** Vector of pointer to source multifab Bx, By, Bz */ ablastr::fields::VectorField m_arr_mf_src; - int const m_lev; /**< level on which mf_src is defined (used in cylindrical) */ + int m_lev; /**< level on which mf_src is defined (used in cylindrical) */ /**< (for cylindrical) whether to average all modes into 1 comp */ bool m_convertRZmodes2cartesian; }; diff --git a/Source/Diagnostics/ComputeDiagFunctors/DivEFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/DivEFunctor.H index e7691187f3a..3874ebeb6c6 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/DivEFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/DivEFunctor.H @@ -41,7 +41,7 @@ public: private: /** Vector of pointer to source multifab Bx, By, Bz */ ablastr::fields::VectorField m_arr_mf_src; - int const m_lev; /**< level on which mf_src is defined (used in cylindrical) */ + int m_lev; /**< level on which mf_src is defined (used in cylindrical) */ /**< (for cylindrical) whether to average all modes into 1 comp */ bool m_convertRZmodes2cartesian; }; diff --git a/Source/Diagnostics/ComputeDiagFunctors/JFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/JFunctor.H index d9f9a1e82e0..21e0d3f5034 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/JFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/JFunctor.H @@ -39,7 +39,7 @@ public: void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: /** direction of the current density to save */ - const int m_dir; + int m_dir; /** level on which mf_src is defined */ int m_lev; /** (for cylindrical) whether to average all modes into 1 comp */ diff --git a/Source/Diagnostics/ComputeDiagFunctors/PartPerCellFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/PartPerCellFunctor.H index 1b8785af7b7..491cd2cfe37 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/PartPerCellFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/PartPerCellFunctor.H @@ -30,7 +30,7 @@ public: */ void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: - int const m_lev; /**< level on which mf_src is defined */ + int m_lev; /**< level on which mf_src is defined */ }; #endif // WARPX_PARTPERCELLFUNCTOR_H_ diff --git a/Source/Diagnostics/ComputeDiagFunctors/PartPerGridFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/PartPerGridFunctor.H index 9718c9c7163..b0c3f28ab90 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/PartPerGridFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/PartPerGridFunctor.H @@ -30,7 +30,7 @@ public: */ void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: - int const m_lev; /**< level on which mf_src is defined */ + int m_lev; /**< level on which mf_src is defined */ }; #endif // WARPX_PARTPERGRIDFUNCTOR_H_ diff --git a/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.H index 7de9844a99e..33211900553 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.H @@ -43,10 +43,10 @@ public: */ void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: - int const m_lev; /**< level on which mf_src is defined */ - int const m_ispec; /**< index of species to average over */ - bool const m_do_average; /**< Whether to calculate the average of the data */ - bool const m_do_filter; /**< whether to apply #m_filter_fn */ + int m_lev; /**< level on which mf_src is defined */ + int m_ispec; /**< index of species to average over */ + bool m_do_average; /**< Whether to calculate the average of the data */ + bool m_do_filter; /**< whether to apply #m_filter_fn */ /** Parser function to be averaged by the functor. Arguments: x, y, z, ux, uy, uz */ std::unique_ptr m_map_fn_parser; /** Parser function to filter particles before pass to map. Arguments: x, y, z, ux, uy, uz */ diff --git a/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.cpp b/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.cpp index d6cd27f7cc0..abc3fb2c8cf 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.cpp +++ b/Source/Diagnostics/ComputeDiagFunctors/ParticleReductionFunctor.cpp @@ -69,6 +69,9 @@ ParticleReductionFunctor::operator() (amrex::MultiFab& mf_dst, const int dcomp, get_particle_position(p, xw, yw, zw); // Get position in AMReX convention to calculate corresponding index. + // Ideally this will be replaced with the AMReX NGP interpolator + // Always do x direction. No RZ case because it's not implemented, and code + // will have aborted const auto [ii, jj, kk] = amrex::getParticleCell(p, plo, dxi).dim3(); // Fix dimensions since parser assumes u = gamma * v / c @@ -97,20 +100,8 @@ ParticleReductionFunctor::operator() (amrex::MultiFab& mf_dst, const int dcomp, // Ideally this will be replaced with the AMReX NGP interpolator // Always do x direction. No RZ case because it's not implemented, and code // will have aborted - int ii = 0, jj = 0, kk = 0; - const amrex::ParticleReal x = p.pos(0); - const amrex::Real lx = (x - plo[0]) * dxi[0]; - ii = static_cast(amrex::Math::floor(lx)); -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_3D) - const amrex::ParticleReal y = p.pos(1); - const amrex::Real ly = (y - plo[1]) * dxi[1]; - jj = static_cast(amrex::Math::floor(ly)); -#endif -#if defined(WARPX_DIM_3D) - const amrex::ParticleReal z = p.pos(2); - const amrex::Real lz = (z - plo[2]) * dxi[2]; - kk = static_cast(amrex::Math::floor(lz)); -#endif + const auto [ii, jj, kk] = amrex::getParticleCell(p, plo, dxi).dim3(); + // Fix dimensions since parser assumes u = gamma * v / c const amrex::ParticleReal ux = p.rdata(PIdx::ux) / PhysConst::c; const amrex::ParticleReal uy = p.rdata(PIdx::uy) / PhysConst::c; diff --git a/Source/Diagnostics/ComputeDiagFunctors/RhoFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/RhoFunctor.H index bc0c8b9f270..073e6476110 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/RhoFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/RhoFunctor.H @@ -43,13 +43,13 @@ public: private: // Level on which source MultiFab mf_src is defined in RZ geometry - int const m_lev; + int m_lev; // Whether to apply k-space filtering of charge density in the diagnostics output in RZ PSATD bool m_apply_rz_psatd_filter; // Species index to dump rho per species - const int m_species_index; + int m_species_index; // Whether to average all modes into one component in RZ geometry bool m_convertRZmodes2cartesian; diff --git a/Source/Diagnostics/ComputeDiagFunctors/TemperatureFunctor.H b/Source/Diagnostics/ComputeDiagFunctors/TemperatureFunctor.H index f6c425e74d5..1716ab61652 100644 --- a/Source/Diagnostics/ComputeDiagFunctors/TemperatureFunctor.H +++ b/Source/Diagnostics/ComputeDiagFunctors/TemperatureFunctor.H @@ -28,8 +28,8 @@ public: */ void operator()(amrex::MultiFab& mf_dst, int dcomp, int /*i_buffer=0*/) const override; private: - int const m_lev; /**< level on which mf_src is defined */ - int const m_ispec; /**< index of species to average over */ + int m_lev; /**< level on which mf_src is defined */ + int m_ispec; /**< index of species to average over */ }; #endif // WARPX_TEMPERATUREFUNCTOR_H_ diff --git a/Source/Diagnostics/Diagnostics.H b/Source/Diagnostics/Diagnostics.H index d0c70e76c1f..a078bab3597 100644 --- a/Source/Diagnostics/Diagnostics.H +++ b/Source/Diagnostics/Diagnostics.H @@ -190,6 +190,8 @@ public: protected: /** Read Parameters of the base Diagnostics class */ bool BaseReadParameters (); + /** Whether to output a message when diagnostics are output */ + int m_verbose = 2; /** Initialize member variables of the base Diagnostics class. */ void InitBaseData (); /** Initialize m_mf_output vectors and data required to construct the buffers diff --git a/Source/Diagnostics/Diagnostics.cpp b/Source/Diagnostics/Diagnostics.cpp index 0f659065185..2b3b6d7df61 100644 --- a/Source/Diagnostics/Diagnostics.cpp +++ b/Source/Diagnostics/Diagnostics.cpp @@ -62,6 +62,9 @@ Diagnostics::BaseReadParameters () std::string dims; pp_geometry.get("dims", dims); + const amrex::ParmParse pp_warpx("warpx"); + pp_warpx.query("verbose", m_verbose); + // Query list of grid fields to write to output const bool varnames_specified = pp_diag_name.queryarr("fields_to_plot", m_varnames_fields); if (!varnames_specified){ @@ -77,8 +80,9 @@ Diagnostics::BaseReadParameters () if (utils::algorithms::is_in(m_varnames_fields, "phi")){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.electrostatic_solver_id==ElectrostaticSolverAlgo::LabFrame || - warpx.electrostatic_solver_id==ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic, - "plot phi only works if do_electrostatic = labframe or do_electrostatic = labframe-electromagnetostatic"); + warpx.electrostatic_solver_id==ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic || + warpx.electrostatic_solver_id==ElectrostaticSolverAlgo::LabFrameEffectivePotential, + "plot phi only works if do_electrostatic = labframe, do_electrostatic = labframe-electromagnetostatic or do_electrostatic = labframe-effective-potential"); } // Sanity check if user requests to plot A diff --git a/Source/Diagnostics/FlushFormats/FlushFormat.H b/Source/Diagnostics/FlushFormats/FlushFormat.H index be1322bd61b..f0a83f7a24b 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormat.H +++ b/Source/Diagnostics/FlushFormats/FlushFormat.H @@ -19,6 +19,7 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, diff --git a/Source/Diagnostics/FlushFormats/FlushFormatAscent.H b/Source/Diagnostics/FlushFormats/FlushFormatAscent.H index a5a10d77bdc..86ad4b09cfb 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatAscent.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatAscent.H @@ -37,11 +37,12 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, const amrex::Geometry& full_BTD_snapshot = amrex::Geometry(), - bool isLastBTDFlush = false ) const override; + bool isLastBTDFlush = false) const override; FlushFormatAscent () = default; ~FlushFormatAscent() override = default; diff --git a/Source/Diagnostics/FlushFormats/FlushFormatAscent.cpp b/Source/Diagnostics/FlushFormats/FlushFormatAscent.cpp index 36f0ef05faa..5a405568aa7 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatAscent.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatAscent.cpp @@ -18,6 +18,7 @@ FlushFormatAscent::WriteToFile ( const amrex::Vector& particle_diags, int nlev, const std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose, const bool /*use_pinned_pc*/, bool isBTD, int /*snapshotID*/, int /*bufferID*/, int /*numBuffers*/, const amrex::Geometry& /*full_BTD_snapshot*/, @@ -32,7 +33,9 @@ FlushFormatAscent::WriteToFile ( "In-situ visualization is not currently supported for back-transformed diagnostics."); const std::string& filename = amrex::Concatenate(prefix, iteration[0], file_min_digits); - amrex::Print() << Utils::TextMsg::Info("Writing Ascent file " + filename); + if (verbose > 0) { + amrex::Print() << Utils::TextMsg::Info("Writing Ascent file " + filename); + } // wrap mesh data WARPX_PROFILE_VAR("FlushFormatAscent::WriteToFile::MultiLevelToBlueprint", prof_ascent_mesh_blueprint); @@ -67,7 +70,7 @@ FlushFormatAscent::WriteToFile ( #else amrex::ignore_unused(varnames, mf, geom, iteration, time, - particle_diags, nlev, file_min_digits, isBTD); + particle_diags, nlev, file_min_digits, verbose, isBTD); #endif // AMREX_USE_ASCENT amrex::ignore_unused(prefix, plot_raw_fields, plot_raw_fields_guards); } diff --git a/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.H b/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.H index 6974bf731a6..c5f3b9148c1 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.H @@ -43,6 +43,7 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, diff --git a/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.cpp b/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.cpp index 425c13de6a4..5e5f3634e8f 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatCatalyst.cpp @@ -110,7 +110,7 @@ FlushFormatCatalyst::FlushFormatCatalyst() { if (err != catalyst_status_ok) { std::string message = " Error: Failed to initialize Catalyst!\n"; - std::cerr << message << err << std::endl; + std::cerr << message << err << "\n"; amrex::Print() << message; amrex::Abort(message); } @@ -127,6 +127,7 @@ FlushFormatCatalyst::WriteToFile ( const amrex::Vector& particle_diags, int nlev, const std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int /*verbose*/, bool /*use_pinned_pc*/, bool isBTD, int /*snapshotID*/, int /*bufferID*/, int /*numBuffers*/, const amrex::Geometry& /*full_BTD_snapshot*/, @@ -179,7 +180,7 @@ FlushFormatCatalyst::WriteToFile ( if (err != catalyst_status_ok) { std::string message = " Error: Failed to execute Catalyst!\n"; - std::cerr << message << err << std::endl; + std::cerr << message << err << "\n"; amrex::Print() << message; } WARPX_PROFILE_VAR_STOP(prof_catalyst_execute); @@ -199,7 +200,7 @@ FlushFormatCatalyst::~FlushFormatCatalyst() { if (err != catalyst_status_ok) { std::string message = " Error: Failed to finalize Catalyst!\n"; - std::cerr << message << err << std::endl; + std::cerr << message << err << "\n"; amrex::Print() << message; amrex::Abort(message); } else { diff --git a/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.H b/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.H index 5c26ac97f61..e2cd28f9e1c 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.H @@ -24,6 +24,7 @@ class FlushFormatCheckpoint final : public FlushFormatPlotfile std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, @@ -34,6 +35,8 @@ class FlushFormatCheckpoint final : public FlushFormatPlotfile const amrex::Vector& particle_diags) const; void WriteDMaps (const std::string& dir, int nlev) const; + + void WriteReducedDiagsData (std::string const & dir) const; }; #endif // WARPX_FLUSHFORMATCHECKPOINT_H_ diff --git a/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.cpp b/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.cpp index 4d721dd6abe..ba371464782 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatCheckpoint.cpp @@ -5,6 +5,7 @@ # include "BoundaryConditions/PML_RZ.H" #endif #include "Diagnostics/ParticleDiag/ParticleDiag.H" +#include "Diagnostics/ReducedDiags/MultiReducedDiags.H" #include "Fields.H" #include "Particles/WarpXParticleContainer.H" #include "Utils/TextMsg.H" @@ -39,6 +40,7 @@ FlushFormatCheckpoint::WriteToFile ( const std::string prefix, int file_min_digits, bool /*plot_raw_fields*/, bool /*plot_raw_fields_guards*/, + int verbose, const bool /*use_pinned_pc*/, bool /*isBTD*/, int /*snapshotID*/, int /*bufferID*/, int /*numBuffers*/, @@ -56,8 +58,10 @@ FlushFormatCheckpoint::WriteToFile ( const std::string& checkpointname = amrex::Concatenate(prefix, iteration[0], file_min_digits); - amrex::Print() << Utils::TextMsg::Info( - "Writing checkpoint " + checkpointname); + if (verbose > 0) { + amrex::Print() << Utils::TextMsg::Info( + "Writing checkpoint " + checkpointname); + } // const int nlevels = finestLevel()+1; amrex::PreBuildDirectorHierarchy(checkpointname, default_level_prefix, nlev, true); @@ -171,6 +175,8 @@ FlushFormatCheckpoint::WriteToFile ( WriteDMaps(checkpointname, nlev); + WriteReducedDiagsData(checkpointname); + VisMF::SetHeaderVersion(current_version); } @@ -185,31 +191,47 @@ FlushFormatCheckpoint::CheckpointParticles ( Vector real_names; Vector int_names; + Vector write_real_comps; + Vector write_int_comps; // note: positions skipped here, since we reconstruct a plotfile SoA from them - real_names.push_back("weight"); - real_names.push_back("momentum_x"); - real_names.push_back("momentum_y"); - real_names.push_back("momentum_z"); - + std::vector const fixed_names = {"weight", + "momentum_x", + "momentum_y", + "momentum_z" #ifdef WARPX_DIM_RZ - real_names.push_back("theta"); + ,"theta" #endif + }; - // get the names of the real comps - // note: skips the mandatory AMREX_SPACEDIM positions for pure SoA + for (auto const& name : fixed_names) { + real_names.push_back(name); + write_real_comps.push_back(1); + } + + // get the names of the extra real comps real_names.resize(pc->NumRealComps() - AMREX_SPACEDIM); - auto runtime_rnames = pc->getParticleRuntimeComps(); - for (auto const& x : runtime_rnames) { - real_names[x.second + PIdx::nattribs - AMREX_SPACEDIM] = x.first; + write_real_comps.resize(pc->NumRealComps() - AMREX_SPACEDIM); + + // note, skip the required compnent names here + auto rnames = pc->GetRealSoANames(); + for (std::size_t index = PIdx::nattribs; index < rnames.size(); ++index) { + std::size_t const i = index - AMREX_SPACEDIM; + real_names[i] = rnames[index]; + write_real_comps[i] = pc->h_redistribute_real_comp[index]; } // and the int comps int_names.resize(pc->NumIntComps()); - auto runtime_inames = pc->getParticleRuntimeiComps(); - for (auto const& x : runtime_inames) { int_names[x.second+0] = x.first; } + write_int_comps.resize(pc->NumIntComps()); + auto inames = pc->GetIntSoANames(); + for (std::size_t index = 0; index < inames.size(); ++index) { + int_names[index] = inames[index]; + write_int_comps[index] = pc->h_redistribute_int_comp[index]; + } - pc->Checkpoint(dir, part_diag.getSpeciesName(), true, + pc->Checkpoint(dir, part_diag.getSpeciesName(), + write_real_comps, write_int_comps, real_names, int_names); } } @@ -242,3 +264,12 @@ FlushFormatCheckpoint::WriteDMaps (const std::string& dir, int nlev) const } } } + +void +FlushFormatCheckpoint::WriteReducedDiagsData (std::string const & dir) const +{ + if (ParallelDescriptor::IOProcessor()) { + auto & warpx = WarpX::GetInstance(); + warpx.reduced_diags->WriteCheckpointData(dir); + } +} diff --git a/Source/Diagnostics/FlushFormats/FlushFormatInSitu.cpp b/Source/Diagnostics/FlushFormats/FlushFormatInSitu.cpp index be3047d7ab6..af8f53df9b9 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatInSitu.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatInSitu.cpp @@ -27,17 +27,17 @@ FlushFormatInSitu::WriteParticles(const amrex::Vector& particle_di // we prefix the fields with "particle_{species_name}" b/c we // want to to uniquely name all the fields that can be plotted - for (unsigned i = 0, n = particle_diags.size(); i < n; ++i) { + for (const auto & particle_diag : particle_diags) { Vector particle_varnames; Vector particle_int_varnames; - std::string prefix = "particle_" + particle_diags[i].getSpeciesName(); + std::string prefix = "particle_" + particle_diag.getSpeciesName(); // Get pc for species // auto& pc = mypc->GetParticleContainer(i); - WarpXParticleContainer* pc = particle_diags[i].getParticleContainer(); + WarpXParticleContainer* pc = particle_diag.getParticleContainer(); // get names of real comps - std::map real_comps_map = pc->getParticleComps(); + std::vector real_comps_map = pc->GetRealSoANames(); // WarpXParticleContainer compile-time extra AoS attributes (Real): 0 // WarpXParticleContainer compile-time extra AoS attributes (int): 0 @@ -46,14 +46,7 @@ FlushFormatInSitu::WriteParticles(const amrex::Vector& particle_di // not an efficient search, but N is small... for(int j = 0; j < PIdx::nattribs; ++j) { - auto rvn_it = real_comps_map.begin(); - for (; rvn_it != real_comps_map.end(); ++rvn_it) - if (rvn_it->second == j) - break; - WARPX_ALWAYS_ASSERT_WITH_MESSAGE( - rvn_it != real_comps_map.end(), - "WarpX In Situ: SoA real attribute not found"); - std::string varname = rvn_it->first; + std::string varname = real_comps_map.at(j); particle_varnames.push_back(prefix + "_" + varname); } // WarpXParticleContainer compile-time extra SoA attributes (int): 0 diff --git a/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.H b/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.H index 141760ac2a3..5666d85bf3a 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.H @@ -36,11 +36,12 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, const amrex::Geometry& full_BTD_snapshot = amrex::Geometry(), - bool isLastBTDFlush = false ) const override; + bool isLastBTDFlush = false) const override; ~FlushFormatOpenPMD () override = default; diff --git a/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.cpp b/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.cpp index e0c8c4ef2d6..aeb26656b46 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatOpenPMD.cpp @@ -123,6 +123,7 @@ FlushFormatOpenPMD::WriteToFile ( const amrex::Vector& particle_diags, int output_levels, const std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose, const bool use_pinned_pc, bool isBTD, int snapshotID, int bufferID, int numBuffers, const amrex::Geometry& full_BTD_snapshot, @@ -130,16 +131,18 @@ FlushFormatOpenPMD::WriteToFile ( { WARPX_PROFILE("FlushFormatOpenPMD::WriteToFile()"); const std::string& filename = amrex::Concatenate(prefix, iteration[0], file_min_digits); - if (!isBTD) - { - amrex::Print() << Utils::TextMsg::Info("Writing openPMD file " + filename); - } else - { - amrex::Print() << Utils::TextMsg::Info("Writing buffer " + std::to_string(bufferID+1) + " of " + std::to_string(numBuffers) - + " to snapshot " + std::to_string(snapshotID) + " to openPMD BTD " + prefix); - if (isLastBTDFlush) + if (verbose > 0) { + if (!isBTD) + { + amrex::Print() << Utils::TextMsg::Info("Writing openPMD file " + filename); + } else { - amrex::Print() << Utils::TextMsg::Info("Finished writing snapshot " + std::to_string(snapshotID) + " in openPMD BTD " + prefix); + amrex::Print() << Utils::TextMsg::Info("Writing buffer " + std::to_string(bufferID+1) + " of " + std::to_string(numBuffers) + + " to snapshot " + std::to_string(snapshotID) + " to openPMD BTD " + prefix); + if (isLastBTDFlush) + { + amrex::Print() << Utils::TextMsg::Info("Finished writing snapshot " + std::to_string(snapshotID) + " in openPMD BTD " + prefix); + } } } diff --git a/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.H b/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.H index c62056b8907..18648c07e69 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.H @@ -31,6 +31,7 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, diff --git a/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.cpp b/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.cpp index 0f05496e4c0..13117bad105 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatPlotfile.cpp @@ -66,6 +66,7 @@ FlushFormatPlotfile::WriteToFile ( const amrex::Vector& particle_diags, int nlev, const std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose, const bool /*use_pinned_pc*/, bool isBTD, int snapshotID, int bufferID, int numBuffers, const amrex::Geometry& /*full_BTD_snapshot*/, @@ -74,17 +75,19 @@ FlushFormatPlotfile::WriteToFile ( WARPX_PROFILE("FlushFormatPlotfile::WriteToFile()"); auto & warpx = WarpX::GetInstance(); const std::string& filename = amrex::Concatenate(prefix, iteration[0], file_min_digits); - if (!isBTD) - { - amrex::Print() << Utils::TextMsg::Info("Writing plotfile " + filename); - } else - { - amrex::Print() << Utils::TextMsg::Info("Writing buffer " + std::to_string(bufferID+1) + " of " + std::to_string(numBuffers) - + " to snapshot " + std::to_string(snapshotID) + " in plotfile BTD " + prefix ); - if (isLastBTDFlush) - { - amrex::Print() << Utils::TextMsg::Info("Finished writing snapshot " + std::to_string(snapshotID) + " in plotfile BTD " + filename); - } + if (verbose > 0) { + if (!isBTD) + { + amrex::Print() << Utils::TextMsg::Info("Writing plotfile " + filename); + } else + { + amrex::Print() << Utils::TextMsg::Info("Writing buffer " + std::to_string(bufferID+1) + " of " + std::to_string(numBuffers) + + " to snapshot " + std::to_string(snapshotID) + " in plotfile BTD " + prefix ); + if (isLastBTDFlush) + { + amrex::Print() << Utils::TextMsg::Info("Finished writing snapshot " + std::to_string(snapshotID) + " in plotfile BTD " + filename); + } + } } Vector rfs; @@ -369,13 +372,13 @@ FlushFormatPlotfile::WriteParticles(const std::string& dir, real_names.push_back("theta"); #endif - // get the names of the real comps - - // note: skips the mandatory AMREX_SPACEDIM positions for pure SoA + // get the names of the extra real comps real_names.resize(tmp.NumRealComps() - AMREX_SPACEDIM); - auto runtime_rnames = tmp.getParticleRuntimeComps(); - for (auto const& x : runtime_rnames) { - real_names[x.second + PIdx::nattribs - AMREX_SPACEDIM] = x.first; + + // note, skip the required compnent names here + auto rnames = tmp.GetRealSoANames(); + for (std::size_t index = PIdx::nattribs; index < rnames.size(); ++index) { + real_names[index - AMREX_SPACEDIM] = rnames[index]; } // plot any "extra" fields by default @@ -387,8 +390,10 @@ FlushFormatPlotfile::WriteParticles(const std::string& dir, // and the names int_names.resize(tmp.NumIntComps()); - auto runtime_inames = tmp.getParticleRuntimeiComps(); - for (auto const& x : runtime_inames) { int_names[x.second+0] = x.first; } + auto inames = tmp.GetIntSoANames(); + for (std::size_t index = 0; index < inames.size(); ++index) { + int_names[index] = inames[index]; + } // plot by default int_flags.resize(tmp.NumIntComps(), 1); diff --git a/Source/Diagnostics/FlushFormats/FlushFormatSensei.H b/Source/Diagnostics/FlushFormats/FlushFormatSensei.H index 45ea40077e4..87ed00e539e 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatSensei.H +++ b/Source/Diagnostics/FlushFormats/FlushFormatSensei.H @@ -57,6 +57,7 @@ public: std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, + int verbose = 2, bool use_pinned_pc = false, bool isBTD = false, int snapshotID = -1, int bufferID = 1, int numBuffers = 1, diff --git a/Source/Diagnostics/FlushFormats/FlushFormatSensei.cpp b/Source/Diagnostics/FlushFormats/FlushFormatSensei.cpp index 468ed81ce18..b96c6d76f91 100644 --- a/Source/Diagnostics/FlushFormats/FlushFormatSensei.cpp +++ b/Source/Diagnostics/FlushFormats/FlushFormatSensei.cpp @@ -51,7 +51,7 @@ FlushFormatSensei::WriteToFile ( const amrex::Vector& particle_diags, int nlev, const std::string prefix, int file_min_digits, bool plot_raw_fields, bool plot_raw_fields_guards, - const bool use_pinned_pc, + int verbose, const bool use_pinned_pc, bool isBTD, int /*snapshotID*/, int /*bufferID*/, int /*numBuffers*/, const amrex::Geometry& /*full_BTD_snapshot*/, bool /*isLastBTDFlush*/) const { @@ -63,7 +63,7 @@ FlushFormatSensei::WriteToFile ( #ifndef AMREX_USE_SENSEI_INSITU amrex::ignore_unused(varnames, mf, iteration, time, particle_diags, - isBTD); + verbose, isBTD); #else WARPX_ALWAYS_ASSERT_WITH_MESSAGE( !isBTD, @@ -71,7 +71,9 @@ FlushFormatSensei::WriteToFile ( WARPX_PROFILE("FlushFormatSensei::WriteToFile()"); const std::string& filename = amrex::Concatenate(prefix, iteration[0], file_min_digits); - amrex::Print() << Utils::TextMsg::Info("Writing Sensei file " + filename); + if (verbose > 0) { + amrex::Print() << Utils::TextMsg::Info("Writing Sensei file " + filename); + } amrex::Vector *mf_ptr = const_cast*>(&mf); diff --git a/Source/Diagnostics/FullDiagnostics.cpp b/Source/Diagnostics/FullDiagnostics.cpp index eeca8ffdb44..5e8cede12ea 100644 --- a/Source/Diagnostics/FullDiagnostics.cpp +++ b/Source/Diagnostics/FullDiagnostics.cpp @@ -261,7 +261,8 @@ FullDiagnostics::Flush ( int i_buffer, bool /* force_flush */ ) m_varnames, m_sum_mf_output.at(i_buffer), m_geom_output.at(i_buffer), warpx.getistep(), warpx.gett_new(0), m_output_species.at(i_buffer), nlev_output, m_file_prefix, - m_file_min_digits, m_plot_raw_fields, m_plot_raw_fields_guards); + m_file_min_digits, m_plot_raw_fields, m_plot_raw_fields_guards, + m_verbose); // Reset the values in the dynamic start time-averaged diagnostics after flush if (m_time_average_mode == TimeAverageType::Dynamic) { @@ -281,7 +282,8 @@ FullDiagnostics::Flush ( int i_buffer, bool /* force_flush */ ) m_varnames, m_mf_output.at(i_buffer), m_geom_output.at(i_buffer), warpx.getistep(), warpx.gett_new(0), m_output_species.at(i_buffer), nlev_output, m_file_prefix, - m_file_min_digits, m_plot_raw_fields, m_plot_raw_fields_guards); + m_file_min_digits, m_plot_raw_fields, m_plot_raw_fields_guards, + m_verbose); } FlushRaw(); @@ -340,7 +342,7 @@ FullDiagnostics::DoComputeAndPack (int step, bool force_flush) } } // Print information on when time-averaging is active - if (in_averaging_period) { + if ((m_verbose > 1) && in_averaging_period) { if (step == m_average_start_step) { amrex::Print() << Utils::TextMsg::Info( "Begin time averaging for " + m_diag_name + " and output at step " @@ -407,85 +409,43 @@ FullDiagnostics::InitializeFieldFunctorsRZopenPMD (int lev) // diagnostic output bool deposit_current = !m_solver_deposits_current; + std::vector field_names = {"r", "t", "z"}; + // Fill vector of functors for all components except individual cylindrical modes. const auto m_varname_fields_size = static_cast(m_varnames_fields.size()); for (int comp=0; comp(warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Er"), ncomp); - } - } else if ( m_varnames_fields[comp] == "Et" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Et"), ncomp); - } - } else if ( m_varnames_fields[comp] == "Ez" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{2}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Ez"), ncomp); - } - } else if ( m_varnames_fields[comp] == "Br" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Br"), ncomp); - } - } else if ( m_varnames_fields[comp] == "Bt" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Bt"), ncomp); - } - } else if ( m_varnames_fields[comp] == "Bz" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{2}, lev), lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("Bz"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jr" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio, - false, deposit_current, ncomp); - deposit_current = false; - if (update_varnames) { - AddRZModesToOutputNames(std::string("jr"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jt" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio, - false, deposit_current, ncomp); - deposit_current = false; - if (update_varnames) { - AddRZModesToOutputNames(std::string("jt"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jz" ){ - m_all_field_functors[lev][comp] = std::make_unique(2, lev, m_crse_ratio, - false, deposit_current, ncomp); - deposit_current = false; - if (update_varnames) { - AddRZModesToOutputNames(std::string("jz"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jr_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("jr_displacement"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jt_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("jt_displacement"), ncomp); - } - } else if ( m_varnames_fields[comp] == "jz_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(2, lev, m_crse_ratio, - false, ncomp); - if (update_varnames) { - AddRZModesToOutputNames(std::string("jz_displacement"), ncomp); + for (int idir=0; idir < 3; idir++) { + if ( m_varnames_fields[comp] == "E"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, + Direction{idir}, lev), lev, m_crse_ratio, false, ncomp); + if (update_varnames) { + AddRZModesToOutputNames(std::string("E"+field_names[idir]), ncomp); + } + } else if ( m_varnames_fields[comp] == "B"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, + Direction{idir}, lev), lev, m_crse_ratio, false, ncomp); + if (update_varnames) { + AddRZModesToOutputNames(std::string("B"+field_names[idir]), ncomp); + } + } else if ( m_varnames_fields[comp] == "j"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(idir, lev, m_crse_ratio, + false, deposit_current, ncomp); + deposit_current = false; + if (update_varnames) { + AddRZModesToOutputNames(std::string("j"+field_names[idir]), ncomp); + } + } else if ( m_varnames_fields[comp] == "j"+field_names[idir]+"_displacement" ){ + m_all_field_functors[lev][comp] = std::make_unique(idir, lev, m_crse_ratio, + false, ncomp); + if (update_varnames) { + AddRZModesToOutputNames(std::string("j"+field_names[idir]+"_displacement"), ncomp); + } } - } else if ( m_varnames_fields[comp] == "rho" ){ + } + // Check if comp was found above + if (m_all_field_functors[lev][comp]) {continue;} + + if ( m_varnames_fields[comp] == "rho" ){ // Initialize rho functor to dump total rho m_all_field_functors[lev][comp] = std::make_unique(lev, m_crse_ratio, true, -1, false, ncomp); @@ -605,12 +565,10 @@ FullDiagnostics::AddRZModesToDiags (int lev) // Check if divE is requested // If so, all components will be written out - bool divE_requested = false; - for (int comp = 0; comp < m_varnames.size(); comp++) { - if ( m_varnames[comp] == "divE" ) { - divE_requested = true; - } - } + const bool divE_requested = std::any_of( + std::begin(m_varnames), + std::end(m_varnames), + [](const auto& varname) { return varname == "divE"; }); // If rho is requested, all components will be written out const bool rho_requested = utils::algorithms::is_in( m_varnames, "rho" ); @@ -863,21 +821,33 @@ FullDiagnostics::InitializeFieldFunctors (int lev) using ablastr::fields::Direction; +#if defined(WARPX_DIM_RZ) + std::vector field_names = {"r", "t", "z"}; +#else + std::vector field_names = {"x", "y", "z"}; +#endif + m_all_field_functors[lev].resize(ntot); // Fill vector of functors for all components except individual cylindrical modes. for (int comp=0; comp(warpx.m_fields.get(FieldType::Efield_aux, Direction{2}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Bz" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{2}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "jz" ){ - m_all_field_functors[lev][comp] = std::make_unique(2, lev, m_crse_ratio, true, deposit_current); - deposit_current = false; - } else if ( m_varnames[comp] == "jz_displacement" ) { - m_all_field_functors[lev][comp] = std::make_unique(2, lev, m_crse_ratio, true); - } else if ( m_varnames[comp] == "Az" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{2}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "rho" ){ + for (int idir=0; idir < 3; idir++) { + if ( m_varnames[comp] == "E"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{idir}, lev), lev, m_crse_ratio); + } else if ( m_varnames[comp] == "B"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{idir}, lev), lev, m_crse_ratio); + } else if ( m_varnames[comp] == "j"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(idir, lev, m_crse_ratio, true, deposit_current); + deposit_current = false; + } else if ( m_varnames[comp] == "j"+field_names[idir]+"_displacement" ) { + m_all_field_functors[lev][comp] = std::make_unique(idir, lev, m_crse_ratio, true); + } else if ( m_varnames[comp] == "A"+field_names[idir] ){ + m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{idir}, lev), lev, m_crse_ratio); + } + } + // Check if comp was found above + if (m_all_field_functors[lev][comp]) {continue;} + + if ( m_varnames[comp] == "rho" ){ // Initialize rho functor to dump total rho m_all_field_functors[lev][comp] = std::make_unique(lev, m_crse_ratio, true); } else if ( m_varnames[comp].rfind("rho_", 0) == 0 ){ @@ -902,64 +872,9 @@ FullDiagnostics::InitializeFieldFunctors (int lev) m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get_alldirs(FieldType::Bfield_aux, lev), lev, m_crse_ratio); } else if ( m_varnames[comp] == "divE" ){ m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get_alldirs(FieldType::Efield_aux, lev), lev, m_crse_ratio); - } - else { - -#ifdef WARPX_DIM_RZ - if ( m_varnames[comp] == "Er" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Et" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Br" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Bt" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "jr" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio, true, deposit_current); - deposit_current = false; - } else if ( m_varnames[comp] == "jt" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio, true, deposit_current); - deposit_current = false; - } else if (m_varnames[comp] == "jr_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio, true); - } else if (m_varnames[comp] == "jt_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio, true); - } else if ( m_varnames[comp] == "Ar" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "At" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{1}, lev), lev, m_crse_ratio); - } else { - WARPX_ABORT_WITH_MESSAGE(m_varnames[comp] + " is not a known field output type for RZ geometry"); - } -#else - // Valid transverse fields in Cartesian coordinates - if ( m_varnames[comp] == "Ex" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Ey" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Bx" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "By" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "jx" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio, true, deposit_current); - deposit_current = false; - } else if ( m_varnames[comp] == "jy" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio, true, deposit_current); - deposit_current = false; - } else if ( m_varnames[comp] == "jx_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(0, lev, m_crse_ratio); - } else if ( m_varnames[comp] == "jy_displacement" ){ - m_all_field_functors[lev][comp] = std::make_unique(1, lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Ax" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{0}, lev), lev, m_crse_ratio); - } else if ( m_varnames[comp] == "Ay" ){ - m_all_field_functors[lev][comp] = std::make_unique(warpx.m_fields.get(FieldType::vector_potential_fp_nodal, Direction{1}, lev), lev, m_crse_ratio); - } else { - std::cout << "Error on component " << m_varnames[comp] << std::endl; - WARPX_ABORT_WITH_MESSAGE(m_varnames[comp] + " is not a known field output type for this geometry"); - } -#endif + } else { + std::cout << "Error on component " << m_varnames[comp] << "\n"; + WARPX_ABORT_WITH_MESSAGE(m_varnames[comp] + " is not a known field output type for this geometry"); } } // Add functors for average particle data for each species diff --git a/Source/Diagnostics/Make.package b/Source/Diagnostics/Make.package index 75b41fba5e8..28afdb35290 100644 --- a/Source/Diagnostics/Make.package +++ b/Source/Diagnostics/Make.package @@ -4,7 +4,6 @@ CEXE_sources += FullDiagnostics.cpp CEXE_sources += WarpXIO.cpp CEXE_sources += ParticleIO.cpp CEXE_sources += FieldIO.cpp -CEXE_sources += SliceDiagnostic.cpp CEXE_sources += BTDiagnostics.cpp CEXE_sources += BoundaryScrapingDiagnostics.cpp CEXE_sources += BTD_Plotfile_Header_Impl.cpp diff --git a/Source/Diagnostics/ParticleDiag/ParticleDiag.cpp b/Source/Diagnostics/ParticleDiag/ParticleDiag.cpp index 1a64ae20f0e..8e61e7464ad 100644 --- a/Source/Diagnostics/ParticleDiag/ParticleDiag.cpp +++ b/Source/Diagnostics/ParticleDiag/ParticleDiag.cpp @@ -36,26 +36,23 @@ ParticleDiag::ParticleDiag ( std::fill(m_plot_flags.begin(), m_plot_flags.end(), 0); bool contains_positions = false; if (variables[0] != "none"){ - std::map existing_variable_names = pc->getParticleComps(); + for (auto& var : variables){ #ifdef WARPX_DIM_RZ - // we reconstruct to Cartesian x,y,z for RZ particle output - existing_variable_names["y"] = PIdx::theta; + // we reconstruct to Cartesian x,y,z for RZ particle output + if (var == "y") { var = "theta"; } #endif - for (const auto& var : variables){ if (var == "phi") { // User requests phi on particle. This is *not* part of the variables that // the particle container carries, and is only added to particles during output. // Therefore, this case needs to be treated specifically. m_plot_phi = true; } else { - const auto search = existing_variable_names.find(var); - WARPX_ALWAYS_ASSERT_WITH_MESSAGE( - search != existing_variable_names.end(), + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(pc->HasRealComp(var), "variables argument '" + var +"' is not an existing attribute for this species"); - m_plot_flags[existing_variable_names.at(var)] = 1; + m_plot_flags[pc->GetRealCompIndex(var)] = 1; - if (var == "x" || var == "y" || var == "z") { + if (var == "x" || var == "y" || var == "z" || var == "theta") { contains_positions = true; } } @@ -75,7 +72,7 @@ ParticleDiag::ParticleDiag ( // Always write out theta, whether or not it's requested, // to be consistent with always writing out r and z. // TODO: openPMD does a reconstruction to Cartesian, so we can now skip force-writing this - m_plot_flags[pc->getParticleComps().at("theta")] = 1; + m_plot_flags[pc->GetRealCompIndex("theta")] = 1; #endif // build filter functors diff --git a/Source/Diagnostics/ParticleIO.cpp b/Source/Diagnostics/ParticleIO.cpp index 05c44f5f594..62a5e126558 100644 --- a/Source/Diagnostics/ParticleIO.cpp +++ b/Source/Diagnostics/ParticleIO.cpp @@ -153,27 +153,30 @@ MultiParticleContainer::Restart (const std::string& dir) real_comp_names.push_back(comp_name); } - for (auto const& comp : pc->getParticleRuntimeComps()) { - auto search = std::find(real_comp_names.begin(), real_comp_names.end(), comp.first); + int n_rc = 0; + for (auto const& comp : pc->GetRealSoANames()) { + // skip compile-time components + if (n_rc < WarpXParticleContainer::NArrayReal) { continue; } + n_rc++; + + auto search = std::find(real_comp_names.begin(), real_comp_names.end(), comp); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( search != real_comp_names.end(), "Species " + species_names[i] - + "needs runtime real component " + comp.first + + " needs runtime real component " + comp + ", but it was not found in the checkpoint file." ); } for (int j = PIdx::nattribs-AMREX_SPACEDIM; j < nr; ++j) { const auto& comp_name = real_comp_names[j]; - auto current_comp_names = pc->getParticleComps(); - auto search = current_comp_names.find(comp_name); - if (search == current_comp_names.end()) { + if (!pc->HasRealComp(comp_name)) { amrex::Print() << Utils::TextMsg::Info( "Runtime real component " + comp_name + " was found in the checkpoint file, but it has not been added yet. " + " Adding it now." ); - pc->NewRealComp(comp_name); + pc->AddRealComp(comp_name); } } @@ -187,26 +190,29 @@ MultiParticleContainer::Restart (const std::string& dir) int_comp_names.push_back(comp_name); } - for (auto const& comp : pc->getParticleRuntimeiComps()) { - auto search = std::find(int_comp_names.begin(), int_comp_names.end(), comp.first); + int n_ic = 0; + for (auto const& comp : pc->GetIntSoANames()) { + // skip compile-time components + if (n_ic < WarpXParticleContainer::NArrayInt) { continue; } + n_ic++; + + auto search = std::find(int_comp_names.begin(), int_comp_names.end(), comp); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( search != int_comp_names.end(), - "Species " + species_names[i] + "needs runtime int component " + comp.first + "Species " + species_names[i] + " needs runtime int component " + comp + ", but it was not found in the checkpoint file." ); } for (int j = 0; j < ni; ++j) { const auto& comp_name = int_comp_names[j]; - auto current_comp_names = pc->getParticleiComps(); - auto search = current_comp_names.find(comp_name); - if (search == current_comp_names.end()) { + if (!pc->HasIntComp(comp_name)) { amrex::Print()<< Utils::TextMsg::Info( "Runtime int component " + comp_name + " was found in the checkpoint file, but it has not been added yet. " + " Adding it now." ); - pc->NewIntComp(comp_name); + pc->AddIntComp(comp_name); } } @@ -258,18 +264,18 @@ storePhiOnParticles ( PinnedMemoryParticleContainer& tmp, is_full_diagnostic, "Output of the electrostatic potential (phi) on the particles was requested, " "but this is only available with `diag_type = Full`."); - tmp.NewRealComp("phi"); - int const phi_index = tmp.getParticleComps().at("phi"); + tmp.AddRealComp("phi"); + int const phi_index = tmp.GetRealCompIndex("phi"); auto& warpx = WarpX::GetInstance(); -#ifdef AMREX_USE_OMP -#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) -#endif for (int lev=0; lev<=warpx.finestLevel(); lev++) { const amrex::Geometry& geom = warpx.Geom(lev); auto plo = geom.ProbLoArray(); auto dxi = geom.InvCellSizeArray(); amrex::MultiFab const& phi = *warpx.m_fields.get(FieldType::phi_fp, lev); +#ifdef AMREX_USE_OMP + #pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif for (PinnedParIter pti(tmp, lev); pti.isValid(); ++pti) { auto phi_grid = phi[pti].array(); diff --git a/Source/Diagnostics/ReducedDiags/CMakeLists.txt b/Source/Diagnostics/ReducedDiags/CMakeLists.txt index bbf1b6b65b0..c548553b875 100644 --- a/Source/Diagnostics/ReducedDiags/CMakeLists.txt +++ b/Source/Diagnostics/ReducedDiags/CMakeLists.txt @@ -6,9 +6,11 @@ foreach(D IN LISTS WarpX_DIMS) ChargeOnEB.cpp ColliderRelevant.cpp DifferentialLuminosity.cpp + DifferentialLuminosity2D.cpp FieldEnergy.cpp FieldMaximum.cpp FieldMomentum.cpp + FieldPoyntingFlux.cpp FieldProbe.cpp FieldProbeParticleContainer.cpp FieldReduction.cpp diff --git a/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.H b/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.H new file mode 100644 index 00000000000..7ffefec324e --- /dev/null +++ b/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.H @@ -0,0 +1,70 @@ +/* Copyright 2023 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: Arianna Formenti, Remi Lehe + * License: BSD-3-Clause-LBNL + */ + +#ifndef WARPX_DIAGNOSTICS_REDUCEDDIAGS_DIFFERENTIALLUMINOSITY2D_H_ +#define WARPX_DIAGNOSTICS_REDUCEDDIAGS_DIFFERENTIALLUMINOSITY2D_H_ + +#include "ReducedDiags.H" +#include +#include + +#include +#include +#include + +/** + * This class contains the differential luminosity diagnostics. + */ +class DifferentialLuminosity2D : public ReducedDiags +{ +public: + + /** + * constructor + * @param[in] rd_name reduced diags names + */ + DifferentialLuminosity2D(const std::string& rd_name); + + /// File type + std::string m_openpmd_backend {"default"}; + + /// minimum number of digits for file suffix (file-based only supported for now) */ + int m_file_min_digits = 6; + + /// name of the two colliding species + std::vector m_beam_name; + + /// number of bins for the c.o.m. energy of the 2 species + int m_bin_num_1; + int m_bin_num_2; + + /// max and min bin values + amrex::Real m_bin_max_1; + amrex::Real m_bin_min_1; + amrex::Real m_bin_max_2; + amrex::Real m_bin_min_2; + + /// bin size + amrex::Real m_bin_size_1; + amrex::Real m_bin_size_2; + + /// output data + amrex::TableData m_h_data_2D; + + void ComputeDiags(int step) final; + + void WriteToFile (int step) const final; + +private: + + /// output table in which to accumulate the luminosity across timesteps + amrex::TableData m_d_data_2D; + +}; + +#endif // WARPX_DIAGNOSTICS_REDUCEDDIAGS_DIFFERENTIALLUMINOSITY2D_H_ diff --git a/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.cpp b/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.cpp new file mode 100644 index 00000000000..b3968b9fb02 --- /dev/null +++ b/Source/Diagnostics/ReducedDiags/DifferentialLuminosity2D.cpp @@ -0,0 +1,401 @@ +/* Copyright 2023 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: Arianna Formenti, Yinjian Zhao, Remi Lehe + * License: BSD-3-Clause-LBNL + */ +#include "DifferentialLuminosity2D.H" + +#include "Diagnostics/ReducedDiags/ReducedDiags.H" +#include "Diagnostics/OpenPMDHelpFunction.H" +#include "Particles/MultiParticleContainer.H" +#include "Particles/Pusher/GetAndSetPosition.H" +#include "Particles/SpeciesPhysicalProperties.H" +#include "Particles/WarpXParticleContainer.H" +#include "Utils/ParticleUtils.H" +#include "Utils/Parser/ParserUtils.H" +#include "Utils/WarpXConst.H" +#include "Utils/TextMsg.H" +#include "Utils/WarpXProfilerWrapper.H" +#include "WarpX.H" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WARPX_USE_OPENPMD +# include +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using ParticleType = WarpXParticleContainer::ParticleType; +using ParticleTileType = WarpXParticleContainer::ParticleTileType; +using ParticleTileDataType = ParticleTileType::ParticleTileDataType; +using ParticleBins = amrex::DenseBins; +using index_type = ParticleBins::index_type; + +#ifdef WARPX_USE_OPENPMD +namespace io = openPMD; +#endif + +using namespace amrex; + +DifferentialLuminosity2D::DifferentialLuminosity2D (const std::string& rd_name) +: ReducedDiags{rd_name} +{ + // RZ coordinate is not supported +#if (defined WARPX_DIM_RZ) + WARPX_ABORT_WITH_MESSAGE( + "DifferentialLuminosity2D diagnostics does not work in RZ geometry."); +#endif + + // read colliding species names - must be 2 + amrex::ParmParse pp_rd_name(m_rd_name); + pp_rd_name.getarr("species", m_beam_name); + + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + m_beam_name.size() == 2u, + "DifferentialLuminosity2D diagnostics must involve exactly two species"); + + pp_rd_name.query("openpmd_backend", m_openpmd_backend); + pp_rd_name.query("file_min_digits", m_file_min_digits); + // pick first available backend if default is chosen + if( m_openpmd_backend == "default" ) { + m_openpmd_backend = WarpXOpenPMDFileType(); + } + pp_rd_name.add("openpmd_backend", m_openpmd_backend); + + // read bin parameters for species 1 + int bin_num_1 = 0; + amrex::Real bin_max_1 = 0.0_rt, bin_min_1 = 0.0_rt; + utils::parser::getWithParser(pp_rd_name, "bin_number_1", bin_num_1); + utils::parser::getWithParser(pp_rd_name, "bin_max_1", bin_max_1); + utils::parser::getWithParser(pp_rd_name, "bin_min_1", bin_min_1); + m_bin_num_1 = bin_num_1; + m_bin_max_1 = bin_max_1; + m_bin_min_1 = bin_min_1; + m_bin_size_1 = (bin_max_1 - bin_min_1) / bin_num_1; + + // read bin parameters for species 2 + int bin_num_2 = 0; + amrex::Real bin_max_2 = 0.0_rt, bin_min_2 = 0.0_rt; + utils::parser::getWithParser(pp_rd_name, "bin_number_2", bin_num_2); + utils::parser::getWithParser(pp_rd_name, "bin_max_2", bin_max_2); + utils::parser::getWithParser(pp_rd_name, "bin_min_2", bin_min_2); + m_bin_num_2 = bin_num_2; + m_bin_max_2 = bin_max_2; + m_bin_min_2 = bin_min_2; + m_bin_size_2 = (bin_max_2 - bin_min_2) / bin_num_2; + + // resize data array on the host + Array tlo{0,0}; // lower bounds + Array thi{m_bin_num_1-1, m_bin_num_2-1}; // inclusive upper bounds + m_h_data_2D.resize(tlo, thi, The_Pinned_Arena()); + + auto const& h_table_data = m_h_data_2D.table(); + // initialize data on the host + for (int i = tlo[0]; i <= thi[0]; ++i) { + for (int j = tlo[1]; j <= thi[1]; ++j) { + h_table_data(i,j) = 0.0_rt; + } + } + + // resize data on the host + m_d_data_2D.resize(tlo, thi); + // copy data from host to device + m_d_data_2D.copy(m_h_data_2D); + Gpu::streamSynchronize(); +} // end constructor + +void DifferentialLuminosity2D::ComputeDiags (int step) +{ +#if defined(WARPX_DIM_RZ) + amrex::ignore_unused(step); +#else + + WARPX_PROFILE("DifferentialLuminosity2D::ComputeDiags"); + + // Since this diagnostic *accumulates* the luminosity in the + // table m_d_data_2D, we add contributions at *each timestep*, but + // we only write the data to file at intervals specified by the user. + const Real c_sq = PhysConst::c*PhysConst::c; + const Real c_over_qe = PhysConst::c/PhysConst::q_e; + + // output table data + auto d_table = m_d_data_2D.table(); + + // get a reference to WarpX instance + auto& warpx = WarpX::GetInstance(); + const Real dt = warpx.getdt(0); + // get cell volume + Geometry const & geom = warpx.Geom(0); + const Real dV = AMREX_D_TERM(geom.CellSize(0), *geom.CellSize(1), *geom.CellSize(2)); + + // declare local variables + auto const num_bins_1 = m_bin_num_1; + Real const bin_min_1 = m_bin_min_1; + Real const bin_size_1 = m_bin_size_1; + auto const num_bins_2 = m_bin_num_2; + Real const bin_min_2 = m_bin_min_2; + Real const bin_size_2 = m_bin_size_2; + + // get MultiParticleContainer class object + const MultiParticleContainer& mypc = warpx.GetPartContainer(); + + auto& species_1 = mypc.GetParticleContainerFromName(m_beam_name[0]); + auto& species_2 = mypc.GetParticleContainerFromName(m_beam_name[1]); + + const ParticleReal m1 = species_1.getMass(); + const ParticleReal m2 = species_2.getMass(); + + // Enable tiling + amrex::MFItInfo info; + if (amrex::Gpu::notInLaunchRegion()) { info.EnableTiling(WarpXParticleContainer::tile_size); } + + int const nlevs = std::max(0, species_1.finestLevel()+1); // species_1 ? + for (int lev = 0; lev < nlevs; ++lev) { +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + + for (amrex::MFIter mfi = species_1.MakeMFIter(lev, info); mfi.isValid(); ++mfi){ + + ParticleTileType& ptile_1 = species_1.ParticlesAt(lev, mfi); + ParticleTileType& ptile_2 = species_2.ParticlesAt(lev, mfi); + + ParticleBins bins_1 = ParticleUtils::findParticlesInEachCell( lev, mfi, ptile_1 ); + ParticleBins bins_2 = ParticleUtils::findParticlesInEachCell( lev, mfi, ptile_2 ); + + // species 1 + const auto soa_1 = ptile_1.getParticleTileData(); + index_type* AMREX_RESTRICT indices_1 = bins_1.permutationPtr(); + index_type const* AMREX_RESTRICT cell_offsets_1 = bins_1.offsetsPtr(); + + // extract particle data of species 1 in the current tile/box + amrex::ParticleReal * const AMREX_RESTRICT w1 = soa_1.m_rdata[PIdx::w]; + amrex::ParticleReal * const AMREX_RESTRICT u1x = soa_1.m_rdata[PIdx::ux]; // u=v*gamma=p/m + amrex::ParticleReal * const AMREX_RESTRICT u1y = soa_1.m_rdata[PIdx::uy]; + amrex::ParticleReal * const AMREX_RESTRICT u1z = soa_1.m_rdata[PIdx::uz]; + bool const species1_is_photon = species_1.AmIA(); + + // same for species 2 + const auto soa_2 = ptile_2.getParticleTileData(); + index_type* AMREX_RESTRICT indices_2 = bins_2.permutationPtr(); + index_type const* AMREX_RESTRICT cell_offsets_2 = bins_2.offsetsPtr(); + + amrex::ParticleReal * const AMREX_RESTRICT w2 = soa_2.m_rdata[PIdx::w]; + amrex::ParticleReal * const AMREX_RESTRICT u2x = soa_2.m_rdata[PIdx::ux]; + amrex::ParticleReal * const AMREX_RESTRICT u2y = soa_2.m_rdata[PIdx::uy]; + amrex::ParticleReal * const AMREX_RESTRICT u2z = soa_2.m_rdata[PIdx::uz]; + bool const species2_is_photon = species_2.AmIA(); + + // Extract low-level (cell-level) data + auto const n_cells = static_cast(bins_1.numBins()); + + // Loop over cells + amrex::ParallelFor( n_cells, + [=] AMREX_GPU_DEVICE (int i_cell) noexcept + { + + // The particles from species1 that are in the cell `i_cell` are + // given by the `indices_1[cell_start_1:cell_stop_1]` + index_type const cell_start_1 = cell_offsets_1[i_cell]; + index_type const cell_stop_1 = cell_offsets_1[i_cell+1]; + // Same for species 2 + index_type const cell_start_2 = cell_offsets_2[i_cell]; + index_type const cell_stop_2 = cell_offsets_2[i_cell+1]; + + for(index_type i_1=cell_start_1; i_1=num_bins_1 ) { continue; } // discard if out-of-range + + // determine energy bin of particle 2 + int const bin_2 = int(Math::floor((E_2-bin_min_2)/bin_size_2)); + if ( bin_2<0 || bin_2>=num_bins_2 ) { continue; } // discard if out-of-range + + Real const inv_p1t = 1.0_rt/p1t; + Real const inv_p2t = 1.0_rt/p2t; + + Real const beta1_sq = (p1x*p1x + p1y*p1y + p1z*p1z) * inv_p1t*inv_p1t; + Real const beta2_sq = (p2x*p2x + p2y*p2y + p2z*p2z) * inv_p2t*inv_p2t; + Real const beta1_dot_beta2 = (p1x*p2x + p1y*p2y + p1z*p2z) * inv_p1t*inv_p2t; + + // Here we use the fact that: + // (v1 - v2)^2 = v1^2 + v2^2 - 2 v1.v2 + // and (v1 x v2)^2 = v1^2 v2^2 - (v1.v2)^2 + // we also use beta=v/c instead of v + Real const radicand = beta1_sq + beta2_sq - 2*beta1_dot_beta2 - beta1_sq*beta2_sq + beta1_dot_beta2*beta1_dot_beta2; + + Real const d2L_dE1_dE2 = PhysConst::c * std::sqrt( radicand ) * w1[j_1] * w2[j_2] / (dV * bin_size_1 * bin_size_2) * dt; // m^-2 eV^-2 + + amrex::Real &data = d_table(bin_1, bin_2); + amrex::HostDevice::Atomic::Add(&data, d2L_dE1_dE2); + + } // particles species 2 + } // particles species 1 + }); // cells + } // boxes + } // levels + + // Only write to file at intervals specified by the user. + // At these intervals, the data needs to ready on the CPU, + // so we copy it from the GPU to the CPU and reduce across MPI ranks. + if (m_intervals.contains(step+1)) { + + // Copy data from GPU memory + m_h_data_2D.copy(m_d_data_2D); + + // reduced sum over mpi ranks + const int size = static_cast (m_d_data_2D.size()); + ParallelDescriptor::ReduceRealSum + (m_h_data_2D.table().p, size, ParallelDescriptor::IOProcessorNumber()); + } + + // Return for all that are not IO processor + if ( !ParallelDescriptor::IOProcessor() ) { return; } + +#endif // not RZ +} // end void DifferentialLuminosity2D::ComputeDiags + +void DifferentialLuminosity2D::WriteToFile (int step) const +{ + // Judge if the diags should be done at this step + if (!m_intervals.contains(step+1)) { return; } + +#ifdef WARPX_USE_OPENPMD + // only IO processor writes + if ( !ParallelDescriptor::IOProcessor() ) { return; } + + // TODO: support different filename templates + std::string filename = "openpmd"; + // TODO: support also group-based encoding + const std::string fileSuffix = std::string("_%0") + std::to_string(m_file_min_digits) + std::string("T"); + filename = filename.append(fileSuffix).append(".").append(m_openpmd_backend); + + // transform paths for Windows + #ifdef _WIN32 + const std::string filepath = openPMD::auxiliary::replace_all( + m_path + m_rd_name + "/" + filename, "/", "\\"); + #else + const std::string filepath = m_path + m_rd_name + "/" + filename; + #endif + + // Create the OpenPMD series + auto series = io::Series( + filepath, + io::Access::CREATE); + auto i = series.iterations[step + 1]; + // record + auto f_mesh = i.meshes["d2L_dE1_dE2"]; // m^-2 eV^-2 + f_mesh.setUnitDimension({ + {io::UnitDimension::L, -6}, + {io::UnitDimension::M, -2}, + {io::UnitDimension::T, 4} + }); + + // record components + auto data = f_mesh[io::RecordComponent::SCALAR]; + + // meta data + f_mesh.setAxisLabels({"E2", "E1"}); // eV, eV + std::vector< double > const& gridGlobalOffset = {m_bin_min_2, m_bin_min_1}; + f_mesh.setGridGlobalOffset(gridGlobalOffset); + f_mesh.setGridSpacing({m_bin_size_2, m_bin_size_1}); + + data.setPosition({0.5, 0.5}); + + auto dataset = io::Dataset( + io::determineDatatype(), + {static_cast(m_bin_num_2), static_cast(m_bin_num_1)}); + data.resetDataset(dataset); + + // Get time at level 0 + auto & warpx = WarpX::GetInstance(); + auto const time = warpx.gett_new(0); + i.setTime(time); + + auto const& h_table_data = m_h_data_2D.table(); + data.storeChunkRaw( + h_table_data.p, + {0, 0}, + {static_cast(m_bin_num_2), static_cast(m_bin_num_1)}); + + series.flush(); + i.close(); + series.close(); +#else + amrex::ignore_unused(step); + WARPX_ABORT_WITH_MESSAGE("DifferentialLuminosity2D: Needs openPMD-api compiled into WarpX, but was not found!"); +#endif +} diff --git a/Source/Diagnostics/ReducedDiags/FieldEnergy.H b/Source/Diagnostics/ReducedDiags/FieldEnergy.H index 40de174526e..fe17f15f071 100644 --- a/Source/Diagnostics/ReducedDiags/FieldEnergy.H +++ b/Source/Diagnostics/ReducedDiags/FieldEnergy.H @@ -40,13 +40,14 @@ public: void ComputeDiags(int step) final; /** - * \brief Calculate the integral of the field squared in RZ + * \brief Calculate the integral of the field squared, taking into + * account the fraction of the cell volume within the domain. * * \param field The MultiFab to be integrated * \param lev The refinement level * \return The integral */ - amrex::Real ComputeNorm2RZ(const amrex::MultiFab& field, int lev); + amrex::Real ComputeNorm2(const amrex::MultiFab& field, int lev); }; diff --git a/Source/Diagnostics/ReducedDiags/FieldEnergy.cpp b/Source/Diagnostics/ReducedDiags/FieldEnergy.cpp index 1a984368b4e..d16319c37e8 100644 --- a/Source/Diagnostics/ReducedDiags/FieldEnergy.cpp +++ b/Source/Diagnostics/ReducedDiags/FieldEnergy.cpp @@ -30,7 +30,7 @@ #include #include -using namespace amrex; +using namespace amrex::literals; using warpx::fields::FieldType; // constructor @@ -40,7 +40,7 @@ FieldEnergy::FieldEnergy (const std::string& rd_name) // read number of levels int nLevel = 0; - const ParmParse pp_amr("amr"); + amrex::ParmParse const pp_amr("amr"); pp_amr.query("max_level", nLevel); nLevel += 1; @@ -48,7 +48,7 @@ FieldEnergy::FieldEnergy (const std::string& rd_name) // resize data array m_data.resize(noutputs*nLevel, 0.0_rt); - if (ParallelDescriptor::IOProcessor()) + if (amrex::ParallelDescriptor::IOProcessor()) { if ( m_write_header ) { @@ -84,10 +84,10 @@ void FieldEnergy::ComputeDiags (int step) if (!m_intervals.contains(step+1)) { return; } // get a reference to WarpX instance - auto & warpx = WarpX::GetInstance(); + auto const & warpx = WarpX::GetInstance(); // get number of level - const auto nLevel = warpx.finestLevel() + 1; + int const nLevel = warpx.finestLevel() + 1; using ablastr::fields::Direction; @@ -95,42 +95,29 @@ void FieldEnergy::ComputeDiags (int step) for (int lev = 0; lev < nLevel; ++lev) { // get MultiFab data at lev - const MultiFab & Ex = *warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, lev); - const MultiFab & Ey = *warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, lev); - const MultiFab & Ez = *warpx.m_fields.get(FieldType::Efield_aux, Direction{2}, lev); - const MultiFab & Bx = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, lev); - const MultiFab & By = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, lev); - const MultiFab & Bz = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{2}, lev); + amrex::MultiFab const & Ex = *warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, lev); + amrex::MultiFab const & Ey = *warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, lev); + amrex::MultiFab const & Ez = *warpx.m_fields.get(FieldType::Efield_aux, Direction{2}, lev); + amrex::MultiFab const & Bx = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, lev); + amrex::MultiFab const & By = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, lev); + amrex::MultiFab const & Bz = *warpx.m_fields.get(FieldType::Bfield_aux, Direction{2}, lev); // get cell volume - const std::array &dx = WarpX::CellSize(lev); - const amrex::Real dV = dx[0]*dx[1]*dx[2]; - -#if defined(WARPX_DIM_RZ) - amrex::Real const tmpEx = ComputeNorm2RZ(Ex, lev); - amrex::Real const tmpEy = ComputeNorm2RZ(Ey, lev); - amrex::Real const tmpEz = ComputeNorm2RZ(Ez, lev); - amrex::Real const Es = tmpEx + tmpEy + tmpEz; - - amrex::Real const tmpBx = ComputeNorm2RZ(Bx, lev); - amrex::Real const tmpBy = ComputeNorm2RZ(By, lev); - amrex::Real const tmpBz = ComputeNorm2RZ(Bz, lev); - amrex::Real const Bs = tmpBx + tmpBy + tmpBz; -#else - Geometry const & geom = warpx.Geom(lev); + std::array const &dx = WarpX::CellSize(lev); + amrex::Real const dV = dx[0]*dx[1]*dx[2]; // compute E squared - Real const tmpEx = Ex.norm2(0,geom.periodicity()); - Real const tmpEy = Ey.norm2(0,geom.periodicity()); - Real const tmpEz = Ez.norm2(0,geom.periodicity()); - Real const Es = tmpEx*tmpEx + tmpEy*tmpEy + tmpEz*tmpEz; + amrex::Real const tmpEx = ComputeNorm2(Ex, lev); + amrex::Real const tmpEy = ComputeNorm2(Ey, lev); + amrex::Real const tmpEz = ComputeNorm2(Ez, lev); // compute B squared - Real const tmpBx = Bx.norm2(0,geom.periodicity()); - Real const tmpBy = By.norm2(0,geom.periodicity()); - Real const tmpBz = Bz.norm2(0,geom.periodicity()); - Real const Bs = tmpBx*tmpBx + tmpBy*tmpBy + tmpBz*tmpBz; -#endif + amrex::Real const tmpBx = ComputeNorm2(Bx, lev); + amrex::Real const tmpBy = ComputeNorm2(By, lev); + amrex::Real const tmpBz = ComputeNorm2(Bz, lev); + + amrex::Real const Es = tmpEx + tmpEy + tmpEz; + amrex::Real const Bs = tmpBx + tmpBy + tmpBz; constexpr int noutputs = 3; // total energy, E-field energy and B-field energy constexpr int index_total = 0; @@ -156,15 +143,13 @@ void FieldEnergy::ComputeDiags (int step) } // end void FieldEnergy::ComputeDiags -// Function that computes the sum of the field squared in RZ +// Function that computes the sum of the field squared. +// This takes into account the fraction of the cell volumes within the domain +// and the cell volumes in cylindrical coordinates. amrex::Real -FieldEnergy::ComputeNorm2RZ(const amrex::MultiFab& field, const int lev) +FieldEnergy::ComputeNorm2(amrex::MultiFab const& field, [[maybe_unused]]int lev) { - // get a reference to WarpX instance - auto & warpx = WarpX::GetInstance(); - - Geometry const & geom = warpx.Geom(lev); - const amrex::Real dr = geom.CellSize(0); + amrex::IntVect const is_nodal = field.ixType().toIntVect(); amrex::ReduceOps reduce_ops; amrex::ReduceData reduce_data(reduce_ops); @@ -178,45 +163,63 @@ FieldEnergy::ComputeNorm2RZ(const amrex::MultiFab& field, const int lev) amrex::Array4 const& field_arr = field.array(mfi); - const amrex::Box tilebox = mfi.tilebox(); - amrex::Box tb = convert(tilebox, field.ixType().toIntVect()); + amrex::Box const tilebox = mfi.tilebox(); + amrex::Box const tb = convert(tilebox, is_nodal); + amrex::IntVect const tb_lo = tb.smallEnd(); + amrex::IntVect const tb_hi = tb.bigEnd(); +#if defined(WARPX_DIM_RZ) // Lower corner of tile box physical domain - const amrex::XDim3 xyzmin = WarpX::LowerCorner(tilebox, lev, 0._rt); - const Dim3 lo = lbound(tilebox); - const Dim3 hi = ubound(tilebox); - const Real rmin = xyzmin.x + (tb.ixType().nodeCentered(0) ? 0._rt : 0.5_rt*dr); - const int irmin = lo.x; - const int irmax = hi.x; + auto const & warpx = WarpX::GetInstance(); + amrex::Geometry const & geom = warpx.Geom(lev); + amrex::Real const dr = geom.CellSize(0); + amrex::XDim3 const xyzmin = WarpX::LowerCorner(tilebox, lev, 0._rt); + amrex::Real const rmin = xyzmin.x + (is_nodal[0] ? 0._rt : 0.5_rt*dr); +#endif - int const ncomp = field.nComp(); + // On the boundaries, if the grid is nodal, use half of the volume. + // This applies to all boundary conditions, and to the overlap of + // boxes within the domain. + // Previously, the code used MultiFab::norm2, but that does not do + // the half-volume scaling for the domain boundaries when not periodic. + + auto volume_factor = [=] AMREX_GPU_DEVICE(int i, int j, int k, int n) noexcept { + amrex::ignore_unused(i,j,k,n); +#if defined WARPX_DIM_RZ + amrex::Real const r = rmin + (i - tb_lo[0])*dr; + amrex::Real v_factor = 2._rt*r; + if (i == tb_lo[0] && is_nodal[0]) { v_factor = r + dr/4._rt; } + if (i == tb_hi[0] && is_nodal[0]) { v_factor = r - dr/4._rt; } + if (j == tb_lo[1] && is_nodal[1]) { v_factor *= 0.5_rt; } + if (j == tb_hi[1] && is_nodal[1]) { v_factor *= 0.5_rt; } + amrex::Real const theta_integral = (n == 0 ? 1._rt : 0.5_rt); + return MathConst::pi*v_factor*theta_integral; +#else + amrex::Real v_factor = 1._rt; + AMREX_D_TERM( + if (i == tb_lo[0] && is_nodal[0]) { v_factor *= 0.5_rt; }, + if (j == tb_lo[1] && is_nodal[1]) { v_factor *= 0.5_rt; }, + if (k == tb_lo[2] && is_nodal[2]) { v_factor *= 0.5_rt; }) + AMREX_D_TERM( + if (i == tb_hi[0] && is_nodal[0]) { v_factor *= 0.5_rt; }, + if (j == tb_hi[1] && is_nodal[1]) { v_factor *= 0.5_rt; }, + if (k == tb_hi[2] && is_nodal[2]) { v_factor *= 0.5_rt; }) + return v_factor; +#endif + }; - for (int idir=0 ; idir < AMREX_SPACEDIM ; idir++) { - if (WarpX::field_boundary_hi[idir] == FieldBoundaryType::Periodic) { - // For periodic boundaries, do not include the data in the nodes - // on the upper edge of the domain - tb.enclosedCells(idir); - } - } + int const ncomp = field.nComp(); reduce_ops.eval(tb, ncomp, reduce_data, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) -> ReduceTuple { - const amrex::Real r = rmin + (i - irmin)*dr; - amrex::Real volume_factor = r; - if (r == 0._rt) { - volume_factor = dr/8._rt; - } else if (rmin == 0._rt && i == irmax) { - volume_factor = r/2._rt - dr/8._rt; - } - const amrex::Real theta_integral = (n == 0 ? 2._rt : 1._rt); - return theta_integral*field_arr(i,j,k,n)*field_arr(i,j,k,n)*volume_factor; + return field_arr(i,j,k,n)*field_arr(i,j,k,n)*volume_factor(i,j,k,n); }); } - const amrex::Real field_sum = amrex::get<0>(reduce_data.value()); - const amrex::Real result = MathConst::pi*field_sum; + amrex::Real result = amrex::get<0>(reduce_data.value()); + amrex::ParallelDescriptor::ReduceRealSum(result); + return result; } -// end Real FieldEnergy::ComputeNorm2RZ diff --git a/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.H b/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.H new file mode 100644 index 00000000000..3a45bd6c789 --- /dev/null +++ b/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.H @@ -0,0 +1,63 @@ +/* Copyright 2019-2020 + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#ifndef WARPX_DIAGNOSTICS_REDUCEDDIAGS_FIELDPOYTINGFLUX_H_ +#define WARPX_DIAGNOSTICS_REDUCEDDIAGS_FIELDPOYTINGFLUX_H_ + +#include "ReducedDiags.H" + +#include + +/** + * \brief This class mainly contains a function that computes the field Poynting flux, + * S = E cross B, integrated over each face of the domain. + */ +class FieldPoyntingFlux : public ReducedDiags +{ +public: + + /** + * \brief Constructor + * + * \param[in] rd_name reduced diags names + */ + FieldPoyntingFlux (const std::string& rd_name); + + /** + * \brief Call the routine to compute the Poynting flux if needed + * + * \param[in] step current time step + */ + void ComputeDiags (int step) final; + + /** + * \brief Call the routine to compute the Poynting flux at the mid step time level + * + * \param[in] step current time step + */ + void ComputeDiagsMidStep (int step) final; + + /** + * \brief This function computes the electromagnetic Poynting flux, + * obtained by integrating the electromagnetic Poynting flux density g = eps0 * (E x B) + * on the surface of the domain. + * + * \param[in] step current time step + */ + void ComputePoyntingFlux (); + + void WriteCheckpointData (std::string const & dir) final; + + void ReadCheckpointData (std::string const & dir) final; + +private: + + bool use_mid_step_value = false; + +}; + +#endif diff --git a/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.cpp b/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.cpp new file mode 100644 index 00000000000..f760516f2b9 --- /dev/null +++ b/Source/Diagnostics/ReducedDiags/FieldPoyntingFlux.cpp @@ -0,0 +1,333 @@ +/* Copyright 2019-2020 + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#include "FieldPoyntingFlux.H" + +#include "Fields.H" +#include "Utils/TextMsg.H" +#include "Utils/WarpXConst.H" +#include "WarpX.H" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace amrex::literals; + +FieldPoyntingFlux::FieldPoyntingFlux (const std::string& rd_name) + : ReducedDiags{rd_name} +{ + // Resize data array + // lo and hi is 2 + // space dims is AMREX_SPACEDIM + // instantaneous and integrated is 2 + // The order will be outward flux for low faces, then high faces, + // energy loss for low faces, then high faces + m_data.resize(2*AMREX_SPACEDIM*2, 0.0_rt); + + if (amrex::ParallelDescriptor::IOProcessor()) + { + if (m_write_header) + { + // Open file + std::ofstream ofs{m_path + m_rd_name + "." + m_extension, std::ofstream::out}; + + int c = 0; + + // Write header row + ofs << "#"; + ofs << "[" << c++ << "]step()"; + ofs << m_sep; + ofs << "[" << c++ << "]time(s)"; + + std::vector sides = {"lo", "hi"}; + +#if defined(WARPX_DIM_3D) + std::vector space_coords = {"x", "y", "z"}; +#elif defined(WARPX_DIM_XZ) + std::vector space_coords = {"x", "z"}; +#elif defined(WARPX_DIM_1D_Z) + std::vector space_coords = {"z"}; +#elif defined(WARPX_DIM_RZ) + std::vector space_coords = {"r", "z"}; +#endif + + // Only on level 0 + for (int iside = 0; iside < 2; iside++) { + for (int ic = 0; ic < AMREX_SPACEDIM; ic++) { + ofs << m_sep; + ofs << "[" << c++ << "]outward_power_" + sides[iside] + "_" + space_coords[ic] +"(W)"; + }} + for (int iside = 0; iside < 2; iside++) { + for (int ic = 0; ic < AMREX_SPACEDIM; ic++) { + ofs << m_sep; + ofs << "[" << c++ << "]integrated_energy_loss_" + sides[iside] + "_" + space_coords[ic] +"(J)"; + }} + + ofs << "\n"; + ofs.close(); + } + } +} + +void FieldPoyntingFlux::ComputeDiags (int /*step*/) +{ + // This will be called at the end of the time step. Only calculate the + // flux if it had not already been calculated mid step. + if (!use_mid_step_value) { + ComputePoyntingFlux(); + } +} + +void FieldPoyntingFlux::ComputeDiagsMidStep (int /*step*/) +{ + // If this is called, always use the value calculated here. + use_mid_step_value = true; + ComputePoyntingFlux(); +} + +void FieldPoyntingFlux::ComputePoyntingFlux () +{ + using warpx::fields::FieldType; + using ablastr::fields::Direction; + + // Note that this is calculated every step to get the + // full resolution on the integrated data + + int const lev = 0; + + // Get a reference to WarpX instance + auto & warpx = WarpX::GetInstance(); + + // RZ coordinate only working with one mode +#if defined(WARPX_DIM_RZ) + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(warpx.n_rz_azimuthal_modes == 1, + "FieldPoyntingFlux reduced diagnostics only implemented in RZ geometry for one mode"); +#endif + + amrex::Box domain_box = warpx.Geom(lev).Domain(); + domain_box.surroundingNodes(); + + // Get MultiFab data at given refinement level + amrex::MultiFab const & Ex = *warpx.m_fields.get(FieldType::Efield_fp, Direction{0}, lev); + amrex::MultiFab const & Ey = *warpx.m_fields.get(FieldType::Efield_fp, Direction{1}, lev); + amrex::MultiFab const & Ez = *warpx.m_fields.get(FieldType::Efield_fp, Direction{2}, lev); + amrex::MultiFab const & Bx = *warpx.m_fields.get(FieldType::Bfield_fp, Direction{0}, lev); + amrex::MultiFab const & By = *warpx.m_fields.get(FieldType::Bfield_fp, Direction{1}, lev); + amrex::MultiFab const & Bz = *warpx.m_fields.get(FieldType::Bfield_fp, Direction{2}, lev); + + // Coarsening ratio (no coarsening) + amrex::GpuArray const cr{1,1,1}; + + // Reduction component (fourth component in Array4) + constexpr int comp = 0; + + // Index type (staggering) of each MultiFab + // (with third component set to zero in 2D) + amrex::GpuArray Ex_stag{0,0,0}; + amrex::GpuArray Ey_stag{0,0,0}; + amrex::GpuArray Ez_stag{0,0,0}; + amrex::GpuArray Bx_stag{0,0,0}; + amrex::GpuArray By_stag{0,0,0}; + amrex::GpuArray Bz_stag{0,0,0}; + for (int i = 0; i < AMREX_SPACEDIM; ++i) + { + Ex_stag[i] = Ex.ixType()[i]; + Ey_stag[i] = Ey.ixType()[i]; + Ez_stag[i] = Ez.ixType()[i]; + Bx_stag[i] = Bx.ixType()[i]; + By_stag[i] = By.ixType()[i]; + Bz_stag[i] = Bz.ixType()[i]; + } + + for (amrex::OrientationIter face; face; ++face) { + + int const face_dir = face().coordDir(); + + if (face().isHigh() && WarpX::field_boundary_hi[face_dir] == FieldBoundaryType::Periodic) { + // For upper periodic boundaries, copy the lower value instead of regenerating it. + int const iu = int(face()); + int const il = int(face().flip()); + m_data[iu] = -m_data[il]; + m_data[iu + 2*AMREX_SPACEDIM] = -m_data[il + 2*AMREX_SPACEDIM]; + continue; + } + + amrex::Box const boundary = amrex::bdryNode(domain_box, face()); + + // Get cell area + amrex::Real const *dx = warpx.Geom(lev).CellSize(); + std::array dxtemp = {AMREX_D_DECL(dx[0], dx[1], dx[2])}; + dxtemp[face_dir] = 1._rt; + amrex::Real const dA = AMREX_D_TERM(dxtemp[0], *dxtemp[1], *dxtemp[2]); + + // Node-centered in the face direction, Cell-centered in other directions + amrex::GpuArray cc{0,0,0}; + cc[face_dir] = 1; + + // Only calculate the ExB term that is normal to the surface. + // normal_dir is the normal direction relative to the WarpX coordinates +#if (defined WARPX_DIM_XZ) || (defined WARPX_DIM_RZ) + // For 2D : it is either 0, or 2 + int const normal_dir = 2*face_dir; +#elif (defined WARPX_DIM_1D_Z) + // For 1D : it is always 2 + int const normal_dir = 2; +#else + // For 3D : it is the same as the face direction + int const normal_dir = face_dir; +#endif + + amrex::ReduceOps reduce_ops; + amrex::ReduceData reduce_data(reduce_ops); + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + // Loop over boxes, interpolate E,B data to cell face centers + // and compute sum over cells of (E x B) components + for (amrex::MFIter mfi(Ex, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) + { + amrex::Array4 const & Ex_arr = Ex[mfi].array(); + amrex::Array4 const & Ey_arr = Ey[mfi].array(); + amrex::Array4 const & Ez_arr = Ez[mfi].array(); + amrex::Array4 const & Bx_arr = Bx[mfi].array(); + amrex::Array4 const & By_arr = By[mfi].array(); + amrex::Array4 const & Bz_arr = Bz[mfi].array(); + + amrex::Box box = enclosedCells(mfi.nodaltilebox()); + box.surroundingNodes(face_dir); + + // Find the intersection with the boundary + // boundary needs to have the same type as box + amrex::Box const boundary_matched = amrex::convert(boundary, box.ixType()); + box &= boundary_matched; + +#if defined(WARPX_DIM_RZ) + // Lower corner of box physical domain + amrex::XDim3 const xyzmin = WarpX::LowerCorner(box, lev, 0._rt); + amrex::Dim3 const lo = amrex::lbound(box); + amrex::Real const dr = warpx.Geom(lev).CellSize(lev); + amrex::Real const rmin = xyzmin.x; + int const irmin = lo.x; +#endif + + auto area_factor = [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { + amrex::ignore_unused(i,j,k); +#if defined WARPX_DIM_RZ + amrex::Real r; + if (normal_dir == 0) { + r = rmin + (i - irmin)*dr; + } else { + r = rmin + (i + 0.5_rt - irmin)*dr; + } + return 2._rt*MathConst::pi*r; +#else + return 1._rt; +#endif + }; + + // Compute E x B + reduce_ops.eval(box, reduce_data, + [=] AMREX_GPU_DEVICE (int i, int j, int k) -> amrex::GpuTuple + { + amrex::Real Ex_cc = 0._rt, Ey_cc = 0._rt, Ez_cc = 0._rt; + amrex::Real Bx_cc = 0._rt, By_cc = 0._rt, Bz_cc = 0._rt; + + if (normal_dir == 1 || normal_dir == 2) { + Ex_cc = ablastr::coarsen::sample::Interp(Ex_arr, Ex_stag, cc, cr, i, j, k, comp); + Bx_cc = ablastr::coarsen::sample::Interp(Bx_arr, Bx_stag, cc, cr, i, j, k, comp); + } + + if (normal_dir == 0 || normal_dir == 2) { + Ey_cc = ablastr::coarsen::sample::Interp(Ey_arr, Ey_stag, cc, cr, i, j, k, comp); + By_cc = ablastr::coarsen::sample::Interp(By_arr, By_stag, cc, cr, i, j, k, comp); + } + if (normal_dir == 0 || normal_dir == 1) { + Ez_cc = ablastr::coarsen::sample::Interp(Ez_arr, Ez_stag, cc, cr, i, j, k, comp); + Bz_cc = ablastr::coarsen::sample::Interp(Bz_arr, Bz_stag, cc, cr, i, j, k, comp); + } + + amrex::Real const af = area_factor(i,j,k); + if (normal_dir == 0) { return af*(Ey_cc * Bz_cc - Ez_cc * By_cc); } + else if (normal_dir == 1) { return af*(Ez_cc * Bx_cc - Ex_cc * Bz_cc); } + else { return af*(Ex_cc * By_cc - Ey_cc * Bx_cc); } + }); + } + + int const sign = (face().isLow() ? -1 : 1); + auto r = reduce_data.value(); + int const ii = int(face()); + m_data[ii] = sign*amrex::get<0>(r)/PhysConst::mu0*dA; + + } + + amrex::ParallelDescriptor::ReduceRealSum(m_data.data(), 2*AMREX_SPACEDIM); + + amrex::Real const dt = warpx.getdt(lev); + for (int ii=0 ; ii < 2*AMREX_SPACEDIM ; ii++) { + m_data[ii + 2*AMREX_SPACEDIM] += m_data[ii]*dt; + } + +} + +void +FieldPoyntingFlux::WriteCheckpointData (std::string const & dir) +{ + // Write out the current values of the time integrated data + std::ofstream chkfile{dir + "/FieldPoyntingFlux_data.txt", std::ofstream::out}; + if (!chkfile.good()) { + WARPX_ABORT_WITH_MESSAGE("FieldPoyntingFlux::WriteCheckpointData: could not open file for writing checkpoint data"); + } + + chkfile.precision(17); + + for (int i=0; i < 2*AMREX_SPACEDIM; i++) { + chkfile << m_data[2*AMREX_SPACEDIM + i] << "\n"; + } +} + +void +FieldPoyntingFlux::ReadCheckpointData (std::string const & dir) +{ + // Read in the current values of the time integrated data + std::ifstream chkfile{dir + "/FieldPoyntingFlux_data.txt", std::ifstream::in}; + if (!chkfile.good()) { + WARPX_ABORT_WITH_MESSAGE("FieldPoyntingFlux::ReadCheckpointData: could not open file for reading checkpoint data"); + } + + for (int i=0; i < 2*AMREX_SPACEDIM; i++) { + amrex::Real data; + if (chkfile >> data) { + m_data[2*AMREX_SPACEDIM + i] = data; + } else { + WARPX_ABORT_WITH_MESSAGE("FieldPoyntingFlux::ReadCheckpointData: could not read in time integrated data"); + } + } +} diff --git a/Source/Diagnostics/ReducedDiags/LoadBalanceCosts.H b/Source/Diagnostics/ReducedDiags/LoadBalanceCosts.H index cfba804d0f0..b30d6b0bb6e 100644 --- a/Source/Diagnostics/ReducedDiags/LoadBalanceCosts.H +++ b/Source/Diagnostics/ReducedDiags/LoadBalanceCosts.H @@ -40,9 +40,9 @@ public: * (cost, processor, level, i_low, j_low, k_low, gpu_ID [if GPU run], num_cells, num_macro_particles * note: the hostname per box is stored separately (in m_data_string) */ #ifdef AMREX_USE_GPU - const int m_nDataFields = 9; + static const int m_nDataFields = 9; #else - const int m_nDataFields = 8; + static const int m_nDataFields = 8; #endif /** used to keep track of max number of boxes over all timesteps; this allows diff --git a/Source/Diagnostics/ReducedDiags/Make.package b/Source/Diagnostics/ReducedDiags/Make.package index 2611831a3dd..98fa093e2df 100644 --- a/Source/Diagnostics/ReducedDiags/Make.package +++ b/Source/Diagnostics/ReducedDiags/Make.package @@ -4,9 +4,11 @@ CEXE_sources += BeamRelevant.cpp CEXE_sources += ChargeOnEB.cpp CEXE_sources += ColliderRelevant.cpp CEXE_sources += DifferentialLuminosity.cpp +CEXE_sources += DifferentialLuminosity2D.cpp CEXE_sources += FieldEnergy.cpp CEXE_sources += FieldMaximum.cpp CEXE_sources += FieldMomentum.cpp +CEXE_sources += FieldPoyntingFlux.cpp CEXE_sources += FieldProbe.cpp CEXE_sources += FieldProbeParticleContainer.cpp CEXE_sources += FieldReduction.cpp diff --git a/Source/Diagnostics/ReducedDiags/MultiReducedDiags.H b/Source/Diagnostics/ReducedDiags/MultiReducedDiags.H index 1a2f51794c6..5a782db7118 100644 --- a/Source/Diagnostics/ReducedDiags/MultiReducedDiags.H +++ b/Source/Diagnostics/ReducedDiags/MultiReducedDiags.H @@ -49,10 +49,21 @@ public: * @param[in] step current iteration time */ void ComputeDiags (int step); + /** Loop over all ReducedDiags and call their ComputeDiagsMidStep + * @param[in] step current iteration time */ + void ComputeDiagsMidStep (int step); + /** Loop over all ReducedDiags and call their WriteToFile * @param[in] step current iteration time */ void WriteToFile (int step); + /** \brief Loop over all ReducedDiags and call their WriteCheckpointData + * @param[in] dir checkpoint directory */ + void WriteCheckpointData (std::string const & dir); + + /** \brief Loop over all ReducedDiags and call their ReadCheckpointData + * @param[in] dir checkpoint directory */ + void ReadCheckpointData (std::string const & dir); }; #endif diff --git a/Source/Diagnostics/ReducedDiags/MultiReducedDiags.cpp b/Source/Diagnostics/ReducedDiags/MultiReducedDiags.cpp index 5035eac58a8..e4c982f7323 100644 --- a/Source/Diagnostics/ReducedDiags/MultiReducedDiags.cpp +++ b/Source/Diagnostics/ReducedDiags/MultiReducedDiags.cpp @@ -10,9 +10,11 @@ #include "ChargeOnEB.H" #include "ColliderRelevant.H" #include "DifferentialLuminosity.H" +#include "DifferentialLuminosity2D.H" #include "FieldEnergy.H" #include "FieldMaximum.H" #include "FieldMomentum.H" +#include "FieldPoyntingFlux.H" #include "FieldProbe.H" #include "FieldReduction.H" #include "LoadBalanceCosts.H" @@ -57,6 +59,7 @@ MultiReducedDiags::MultiReducedDiags () {"ChargeOnEB", [](CS s){return std::make_unique(s);}}, {"ColliderRelevant", [](CS s){return std::make_unique(s);}}, {"DifferentialLuminosity",[](CS s){return std::make_unique(s);}}, + {"DifferentialLuminosity2D",[](CS s){return std::make_unique(s);}}, {"ParticleEnergy", [](CS s){return std::make_unique(s);}}, {"ParticleExtrema", [](CS s){return std::make_unique(s);}}, {"ParticleHistogram", [](CS s){return std::make_unique(s);}}, @@ -66,6 +69,7 @@ MultiReducedDiags::MultiReducedDiags () {"FieldEnergy", [](CS s){return std::make_unique(s);}}, {"FieldMaximum", [](CS s){return std::make_unique(s);}}, {"FieldMomentum", [](CS s){return std::make_unique(s);}}, + {"FieldPoyntingFlux", [](CS s){return std::make_unique(s);}}, {"FieldProbe", [](CS s){return std::make_unique(s);}}, {"FieldReduction", [](CS s){return std::make_unique(s);}}, {"LoadBalanceCosts", [](CS s){return std::make_unique(s);}}, @@ -124,6 +128,20 @@ void MultiReducedDiags::ComputeDiags (int step) } // end void MultiReducedDiags::ComputeDiags +// call functions to compute diags at the mid step time level +void MultiReducedDiags::ComputeDiagsMidStep (int step) +{ + WARPX_PROFILE("MultiReducedDiags::ComputeDiagsMidStep()"); + + // loop over all reduced diags + for (int i_rd = 0; i_rd < static_cast(m_rd_names.size()); ++i_rd) + { + m_multi_rd[i_rd] -> ComputeDiagsMidStep(step); + } + // end loop over all reduced diags +} +// end void MultiReducedDiags::ComputeDiagsMidStep + // function to write data void MultiReducedDiags::WriteToFile (int step) { @@ -142,3 +160,26 @@ void MultiReducedDiags::WriteToFile (int step) // end loop over all reduced diags } // end void MultiReducedDiags::WriteToFile + +void MultiReducedDiags::WriteCheckpointData (std::string const & dir) +{ + // Only the I/O rank does + if ( !ParallelDescriptor::IOProcessor() ) { return; } + + // loop over all reduced diags + for (int i_rd = 0; i_rd < static_cast(m_rd_names.size()); ++i_rd) + { + m_multi_rd[i_rd]->WriteCheckpointData(dir); + } + // end loop over all reduced diags +} + +void MultiReducedDiags::ReadCheckpointData (std::string const & dir) +{ + // loop over all reduced diags + for (int i_rd = 0; i_rd < static_cast(m_rd_names.size()); ++i_rd) + { + m_multi_rd[i_rd]->ReadCheckpointData(dir); + } + // end loop over all reduced diags +} diff --git a/Source/Diagnostics/ReducedDiags/ReducedDiags.H b/Source/Diagnostics/ReducedDiags/ReducedDiags.H index 2c942e1df6d..a32de30cc6f 100644 --- a/Source/Diagnostics/ReducedDiags/ReducedDiags.H +++ b/Source/Diagnostics/ReducedDiags/ReducedDiags.H @@ -83,6 +83,13 @@ public: */ virtual void ComputeDiags (int step) = 0; + /** + * function to compute diags at the mid step time level + * + * @param[in] step current time step + */ + virtual void ComputeDiagsMidStep (int step); + /** * write to file function * @@ -90,6 +97,20 @@ public: */ virtual void WriteToFile (int step) const; + /** + * \brief Write out checkpoint related data + * + * \param[in] dir Directory where checkpoint data is written + */ + virtual void WriteCheckpointData (std::string const & dir); + + /** + * \brief Read in checkpoint related data + * + * \param[in] dir Directory where checkpoint data was written + */ + virtual void ReadCheckpointData (std::string const & dir); + /** * This function queries deprecated input parameters and aborts * the run if one of them is specified. diff --git a/Source/Diagnostics/ReducedDiags/ReducedDiags.cpp b/Source/Diagnostics/ReducedDiags/ReducedDiags.cpp index ec31d9de81c..b0e20584a12 100644 --- a/Source/Diagnostics/ReducedDiags/ReducedDiags.cpp +++ b/Source/Diagnostics/ReducedDiags/ReducedDiags.cpp @@ -28,12 +28,15 @@ m_rd_name{rd_name} { BackwardCompatibility(); + const ParmParse pp_rd("reduced_diags"); const ParmParse pp_rd_name(m_rd_name); // read path + pp_rd.query("path", m_path); pp_rd_name.query("path", m_path); // read extension + pp_rd.query("extension", m_extension); pp_rd_name.query("extension", m_extension); // check if it is a restart run @@ -61,13 +64,16 @@ m_rd_name{rd_name} // read reduced diags intervals std::vector intervals_string_vec = {"1"}; - pp_rd_name.getarr("intervals", intervals_string_vec); + pp_rd.queryarr("intervals", intervals_string_vec); + pp_rd_name.queryarr("intervals", intervals_string_vec); m_intervals = utils::parser::IntervalsParser(intervals_string_vec); // read separator + pp_rd.query("separator", m_sep); pp_rd_name.query("separator", m_sep); // precision of data in the output file + utils::parser::queryWithParser(pp_rd, "precision", m_precision); utils::parser::queryWithParser(pp_rd_name, "precision", m_precision); } // end constructor @@ -86,6 +92,27 @@ void ReducedDiags::LoadBalance () // load balancing operations } +void ReducedDiags::ComputeDiagsMidStep (int /*step*/) +{ + // Defines an empty function ComputeDiagsMidStep() to be overwritten if needed. + // Function used to calculate the diagnostic at the mid step time leve + // (instead of at the end of the step). +} + +void ReducedDiags::WriteCheckpointData (std::string const & /*dir*/) +{ + // Defines an empty function WriteCheckpointData() to be overwritten if needed. + // Function used to write out and data needed by the diagnostic in + // the checkpoint. +} + +void ReducedDiags::ReadCheckpointData (std::string const & /*dir*/) +{ + // Defines an empty function ReadCheckpointData() to be overwritten if needed. + // Function used to read in any data that was written out in the checkpoint + // when doing a restart. +} + void ReducedDiags::BackwardCompatibility () const { const amrex::ParmParse pp_rd_name(m_rd_name); diff --git a/Source/Diagnostics/ReducedDiags/Timestep.cpp b/Source/Diagnostics/ReducedDiags/Timestep.cpp index 3474121db91..e74f22c27ec 100644 --- a/Source/Diagnostics/ReducedDiags/Timestep.cpp +++ b/Source/Diagnostics/ReducedDiags/Timestep.cpp @@ -50,7 +50,7 @@ Timestep::Timestep (const std::string& rd_name) } // close file - ofs << std::endl; + ofs << "\n"; ofs.close(); } } diff --git a/Source/Diagnostics/SliceDiagnostic.H b/Source/Diagnostics/SliceDiagnostic.H deleted file mode 100644 index 570f86d5384..00000000000 --- a/Source/Diagnostics/SliceDiagnostic.H +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright 2019 Revathi Jambunathan - * - * This file is part of WarpX. - * - * License: BSD-3-Clause-LBNL - */ -#ifndef WARPX_SliceDiagnostic_H_ -#define WARPX_SliceDiagnostic_H_ - -#include - -#include - -#include - -std::unique_ptr CreateSlice( const amrex::MultiFab& mf, - const amrex::Vector &dom_geom, - amrex::RealBox &slice_realbox, - amrex::IntVect &slice_cr_ratio ); - -void CheckSliceInput( amrex::RealBox real_box, - amrex::RealBox &slice_cc_nd_box, amrex::RealBox &slice_realbox, - amrex::IntVect &slice_cr_ratio, amrex::Vector dom_geom, - amrex::IntVect SliceType, amrex::IntVect &slice_lo, - amrex::IntVect &slice_hi, amrex::IntVect &interp_lo); - -void InterpolateSliceValues( amrex::MultiFab& smf, - amrex::IntVect interp_lo, amrex::RealBox slice_realbox, - const amrex::Vector& geom, int ncomp, int nghost, - amrex::IntVect slice_lo, amrex::IntVect slice_hi, - amrex::IntVect SliceType, amrex::RealBox real_box); - -void InterpolateLo( const amrex::Box& bx, amrex::FArrayBox &fabox, - amrex::IntVect slice_lo, amrex::Vector geom, - int idir, amrex::IntVect IndType, amrex::RealBox slice_realbox, - int srccomp, int ncomp, int nghost, amrex::RealBox real_box); - -#endif diff --git a/Source/Diagnostics/SliceDiagnostic.cpp b/Source/Diagnostics/SliceDiagnostic.cpp deleted file mode 100644 index bcb6070abdf..00000000000 --- a/Source/Diagnostics/SliceDiagnostic.cpp +++ /dev/null @@ -1,526 +0,0 @@ -/* Copyright 2019-2020 Luca Fedeli, Revathi Jambunathan, Weiqun Zhang - * - * - * This file is part of WarpX. - * - * License: BSD-3-Clause-LBNL - */ -#include "SliceDiagnostic.H" - -#include "Fields.H" -#include "Utils/TextMsg.H" -#include "WarpX.H" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -using namespace amrex; -using warpx::fields::FieldType; - -/* \brief - * The functions creates the slice for diagnostics based on the user-input. - * The slice can be 1D, 2D, or 3D and it inherits the index type of the underlying data. - * The implementation assumes that the slice is aligned with the coordinate axes. - * The input parameters are modified if the user-input does not comply with requirements of coarsenability or if the slice extent is not contained within the simulation domain. - * First a slice multifab (smf) with cell size equal to that of the simulation grid is created such that it extends from slice.dim_lo to slice.dim_hi and shares the same index space as the source multifab (mf) - * The values are copied from src mf to dst smf using amrex::ParallelCopy - * If interpolation is required, then on the smf, using data points stored in the ghost cells, the data in interpolated. - * If coarsening is required, then a coarse slice multifab is generated (cs_mf) and the - * values of the refined slice (smf) is averaged down to obtain the coarse slice. - * \param mf is the source multifab containing the field data - * \param dom_geom is the geometry of the domain and used in the function to obtain the - * CellSize of the underlying grid. - * \param slice_realbox defines the extent of the slice - * \param slice_cr_ratio provides the coarsening ratio for diagnostics - */ - -std::unique_ptr -CreateSlice( const MultiFab& mf, const Vector &dom_geom, - RealBox &slice_realbox, IntVect &slice_cr_ratio ) -{ - std::unique_ptr smf; - std::unique_ptr cs_mf; - - Vector slice_ncells(AMREX_SPACEDIM); - const int nghost = 1; - auto nlevels = static_cast(dom_geom.size()); - const int ncomp = (mf).nComp(); - - WARPX_ALWAYS_ASSERT_WITH_MESSAGE( nlevels==1, - "Slice diagnostics does not work with mesh refinement yet (TO DO)."); - - const auto conversionType = (mf).ixType(); - IntVect SliceType(AMREX_D_DECL(0,0,0)); - for (int idim = 0; idim < AMREX_SPACEDIM; ++idim ) - { - SliceType[idim] = conversionType.nodeCentered(idim); - } - - const RealBox& real_box = dom_geom[0].ProbDomain(); - RealBox slice_cc_nd_box; - const int default_grid_size = 32; - int slice_grid_size = default_grid_size; - - bool interpolate = false; - bool coarsen = false; - - // same index space as domain // - IntVect slice_lo(AMREX_D_DECL(0,0,0)); - IntVect slice_hi(AMREX_D_DECL(1,1,1)); - IntVect interp_lo(AMREX_D_DECL(0,0,0)); - - CheckSliceInput(real_box, slice_cc_nd_box, slice_realbox, slice_cr_ratio, - dom_geom, SliceType, slice_lo, - slice_hi, interp_lo); - int configuration_dim = 0; - // Determine if interpolation is required and number of cells in slice // - for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { - - // Flag for interpolation if required // - if ( interp_lo[idim] == 1) { - interpolate = true; - } - - // For the case when a dimension is reduced // - if ( ( slice_hi[idim] - slice_lo[idim]) == 1) { - slice_ncells[idim] = 1; - } - else { - slice_ncells[idim] = ( slice_hi[idim] - slice_lo[idim] + 1 ) - / slice_cr_ratio[idim]; - - const int refined_ncells = slice_hi[idim] - slice_lo[idim] + 1 ; - if ( slice_cr_ratio[idim] > 1) { - coarsen = true; - - // modify slice_grid_size if >= refines_cells // - if ( slice_grid_size >= refined_ncells ) { - slice_grid_size = refined_ncells - 1; - } - - } - configuration_dim += 1; - } - } - if (configuration_dim==1) { - ablastr::warn_manager::WMRecordWarning("Diagnostics", - "The slice configuration is 1D and cannot be visualized using yt."); - } - - // Slice generation with index type inheritance // - const Box slice(slice_lo, slice_hi); - - Vector sba(1); - sba[0].define(slice); - sba[0].maxSize(slice_grid_size); - - // Distribution mapping for slice can be different from that of domain // - Vector sdmap(1); - sdmap[0] = DistributionMapping{sba[0]}; - - smf = std::make_unique(amrex::convert(sba[0],SliceType), sdmap[0], - ncomp, nghost); - - // Copy data from domain to slice that has same cell size as that of // - // the domain mf. src and dst have the same number of ghost cells // - const amrex::IntVect nghost_vect(AMREX_D_DECL(nghost, nghost, nghost)); - ablastr::utils::communication::ParallelCopy(*smf, mf, 0, 0, ncomp, nghost_vect, nghost_vect, WarpX::do_single_precision_comms); - - // interpolate if required on refined slice // - if (interpolate) { - InterpolateSliceValues( *smf, interp_lo, slice_cc_nd_box, dom_geom, - ncomp, nghost, slice_lo, slice_hi, SliceType, real_box); - } - - - if (!coarsen) { - return smf; - } - else { - Vector crse_ba(1); - crse_ba[0] = sba[0]; - crse_ba[0].coarsen(slice_cr_ratio); - - AMREX_ALWAYS_ASSERT(crse_ba[0].size() == sba[0].size()); - - cs_mf = std::make_unique(amrex::convert(crse_ba[0],SliceType), - sdmap[0], ncomp,nghost); - - const MultiFab& mfSrc = *smf; - MultiFab& mfDst = *cs_mf; - - auto & warpx = WarpX::GetInstance(); - - using ablastr::fields::Direction; - - MFIter mfi_dst(mfDst); - for (MFIter mfi(mfSrc); mfi.isValid(); ++mfi) { - - Array4 const& Src_fabox = mfSrc.const_array(mfi); - - const Box& Dst_bx = mfi_dst.validbox(); - Array4 const& Dst_fabox = mfDst.array(mfi_dst); - - const int scomp = 0; - const int dcomp = 0; - - const IntVect cctype(AMREX_D_DECL(0,0,0)); - if( SliceType==cctype ) { - amrex::amrex_avgdown(Dst_bx, Dst_fabox, Src_fabox, dcomp, scomp, - ncomp, slice_cr_ratio); - } - const IntVect ndtype(AMREX_D_DECL(1,1,1)); - if( SliceType == ndtype ) { - amrex::amrex_avgdown_nodes(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio); - } - if( SliceType == warpx.m_fields.get(FieldType::Efield_aux, Direction{0}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_edges(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 0); - } - if( SliceType == warpx.m_fields.get(FieldType::Efield_aux, Direction{1}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_edges(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 1); - } - if( SliceType == warpx.m_fields.get(FieldType::Efield_aux, Direction{2}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_edges(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 2); - } - if( SliceType == warpx.m_fields.get(FieldType::Bfield_aux, Direction{0}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_faces(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 0); - } - if( SliceType == warpx.m_fields.get(FieldType::Bfield_aux, Direction{1}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_faces(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 1); - } - if( SliceType == warpx.m_fields.get(FieldType::Bfield_aux, Direction{2}, 0)->ixType().toIntVect() ) { - amrex::amrex_avgdown_faces(Dst_bx, Dst_fabox, Src_fabox, dcomp, - scomp, ncomp, slice_cr_ratio, 2); - } - - if ( mfi_dst.isValid() ) { - ++mfi_dst; - } - - } - return cs_mf; - } -} - - -/* \brief - * This function modifies the slice input parameters under certain conditions. - * The coarsening ratio, slice_cr_ratio is modified if the input is not an exponent of 2. - * for example, if the coarsening ratio is 3, 5 or 6, which is not an exponent of 2, - * then the value of coarsening ratio is modified to the nearest exponent of 2. - * The default value for coarsening ratio is 1. - * slice_realbox.lo and slice_realbox.hi are set equal to the simulation domain lo and hi - * if for the user-input for the slice lo and hi coordinates are outside the domain. - * If the slice_realbox.lo and slice_realbox.hi coordinates do not align with the data - * points and the number of cells in that dimension is greater than 1, and if the extent of - * the slice in that dimension is not coarsenable, then the value lo and hi coordinates are - * shifted to the nearest coarsenable point to include some extra data points in the slice. - * If slice_realbox.lo==slice_realbox.hi, then that dimension has only one cell and no - * modifications are made to the value. If the lo and hi do not align with a data point, - * then it is flagged for interpolation. - * \param real_box a Real box defined for the underlying domain. - * \param slice_realbox a Real box for defining the slice dimension. - * \param slice_cc_nd_box a Real box for defining the modified lo and hi of the slice - * such that the coordinates align with the underlying data points. - * If the dimension is reduced to have only one cell, the slice_realbox is not modified and * instead the values are interpolated to the coordinate from the nearest data points. - * \param slice_cr_ratio contains values of the coarsening ratio which may be modified - * if the input values do not satisfy coarsenability conditions. - * \param slice_lo and slice_hi are the index values of the slice - * \param interp_lo are set to 0 or 1 if they are flagged for interpolation. - * The slice shares the same index space as that of the simulation domain. - */ - - -void -CheckSliceInput( const RealBox real_box, RealBox &slice_cc_nd_box, - RealBox &slice_realbox, IntVect &slice_cr_ratio, - Vector dom_geom, IntVect const SliceType, - IntVect &slice_lo, IntVect &slice_hi, IntVect &interp_lo) -{ - - IntVect slice_lo2(AMREX_D_DECL(0,0,0)); - for ( int idim = 0; idim < AMREX_SPACEDIM; ++idim) - { - // Modify coarsening ratio if the input value is not an exponent of 2 for AMR // - if ( slice_cr_ratio[idim] > 0 ) { - const int log_cr_ratio = - static_cast(floor ( log2( double(slice_cr_ratio[idim])))); - slice_cr_ratio[idim] = - static_cast (exp2( double(log_cr_ratio) )); - } - - //// Default coarsening ratio is 1 // - // Modify lo if input is out of bounds // - if ( slice_realbox.lo(idim) < real_box.lo(idim) ) { - slice_realbox.setLo( idim, real_box.lo(idim)); - std::stringstream warnMsg; - warnMsg << " slice lo is out of bounds. " << - " Modified it in dimension " << idim << - " to be aligned with the domain box."; - ablastr::warn_manager::WMRecordWarning("Diagnostics", - warnMsg.str(), ablastr::warn_manager::WarnPriority::low); - } - - // Modify hi if input in out od bounds // - if ( slice_realbox.hi(idim) > real_box.hi(idim) ) { - slice_realbox.setHi( idim, real_box.hi(idim)); - std::stringstream warnMsg; - warnMsg << " slice hi is out of bounds. " << - " Modified it in dimension " << idim << - " to be aligned with the domain box."; - ablastr::warn_manager::WMRecordWarning("Diagnostics", - warnMsg.str(), ablastr::warn_manager::WarnPriority::low); - } - - const auto very_small_number = 1E-10; - - // Factor to ensure index values computation depending on index type // - const double fac = ( 1.0 - SliceType[idim] )*dom_geom[0].CellSize(idim)*0.5; - // if dimension is reduced to one cell length // - if ( slice_realbox.hi(idim) - slice_realbox.lo(idim) <= 0) - { - slice_cc_nd_box.setLo( idim, slice_realbox.lo(idim) ); - slice_cc_nd_box.setHi( idim, slice_realbox.hi(idim) ); - - if ( slice_cr_ratio[idim] > 1) { slice_cr_ratio[idim] = 1; } - - // check for interpolation -- compute index lo with floor and ceil - if ( slice_cc_nd_box.lo(idim) - real_box.lo(idim) >= fac ) { - slice_lo[idim] = static_cast( - floor( ( (slice_cc_nd_box.lo(idim) - - (real_box.lo(idim) + fac ) ) - / dom_geom[0].CellSize(idim)) + fac * very_small_number) ); - slice_lo2[idim] = static_cast( - ceil( ( (slice_cc_nd_box.lo(idim) - - (real_box.lo(idim) + fac) ) - / dom_geom[0].CellSize(idim)) - fac * very_small_number) ); - } - else { - slice_lo[idim] = static_cast( - std::round( (slice_cc_nd_box.lo(idim) - - (real_box.lo(idim) ) ) - / dom_geom[0].CellSize(idim)) ); - slice_lo2[idim] = static_cast( - std::ceil((slice_cc_nd_box.lo(idim) - - (real_box.lo(idim) ) ) - / dom_geom[0].CellSize(idim) ) ); - } - - // flag for interpolation -- if reduced dimension location // - // does not align with data point // - if ( slice_lo[idim] == slice_lo2[idim]) { - if ( slice_cc_nd_box.lo(idim) - real_box.lo(idim) < fac ) { - interp_lo[idim] = 1; - } - } - else { - interp_lo[idim] = 1; - } - - // ncells = 1 if dimension is reduced // - slice_hi[idim] = slice_lo[idim] + 1; - } - else - { - // moving realbox.lo and realbox.hi to nearest coarsenable grid point // - auto index_lo = static_cast(floor(((slice_realbox.lo(idim) + very_small_number - - (real_box.lo(idim))) / dom_geom[0].CellSize(idim))) ); - auto index_hi = static_cast(ceil(((slice_realbox.hi(idim) - very_small_number - - (real_box.lo(idim))) / dom_geom[0].CellSize(idim))) ); - - bool modify_cr = true; - - while ( modify_cr ) { - int lo_new = index_lo; - int hi_new = index_hi; - const int mod_lo = index_lo % slice_cr_ratio[idim]; - const int mod_hi = index_hi % slice_cr_ratio[idim]; - modify_cr = false; - - // To ensure that the index.lo is coarsenable // - if ( mod_lo > 0) { - lo_new = index_lo - mod_lo; - } - // To ensure that the index.hi is coarsenable // - if ( mod_hi > 0) { - hi_new = index_hi + (slice_cr_ratio[idim] - mod_hi); - } - - // If modified index.hi is > baselinebox.hi, move the point // - // to the previous coarsenable point // - const auto small_number = 0.01; - if ( (hi_new * dom_geom[0].CellSize(idim)) - > real_box.hi(idim) - real_box.lo(idim) + dom_geom[0].CellSize(idim)*small_number) - { - hi_new = index_hi - mod_hi; - } - - if ( (hi_new - lo_new) == 0 ){ - std::stringstream warnMsg; - warnMsg << " Coarsening ratio " << slice_cr_ratio[idim] << " in dim "<< idim << - "is leading to zero cells for slice." << " Thus reducing cr_ratio by half.\n"; - - ablastr::warn_manager::WMRecordWarning("Diagnostics", - warnMsg.str()); - - slice_cr_ratio[idim] = slice_cr_ratio[idim]/2; - modify_cr = true; - } - - if ( !modify_cr ) { - index_lo = lo_new; - index_hi = hi_new; - } - slice_lo[idim] = index_lo; - slice_hi[idim] = index_hi - 1; // since default is cell-centered - } - slice_realbox.setLo( idim, index_lo * dom_geom[0].CellSize(idim) - + real_box.lo(idim) ); - slice_realbox.setHi( idim, index_hi * dom_geom[0].CellSize(idim) - + real_box.lo(idim) ); - slice_cc_nd_box.setLo( idim, slice_realbox.lo(idim) + Real(fac) ); - slice_cc_nd_box.setHi( idim, slice_realbox.hi(idim) - Real(fac) ); - } - } -} - - -/* \brief - * This function is called if the coordinates of the slice do not align with data points - * \param interp_lo is an IntVect which is flagged as 1, if interpolation - is required in the dimension. - */ -void -InterpolateSliceValues(MultiFab& smf, IntVect interp_lo, RealBox slice_realbox, - const Vector& geom, int ncomp, int nghost, - IntVect slice_lo, IntVect /*slice_hi*/, IntVect SliceType, - const RealBox real_box) -{ - for (MFIter mfi(smf); mfi.isValid(); ++mfi) - { - const Box& bx = mfi.tilebox(); - FArrayBox& fabox = smf[mfi]; - - for ( int idim = 0; idim < AMREX_SPACEDIM; ++idim) { - if ( interp_lo[idim] == 1 ) { - InterpolateLo( bx, fabox, slice_lo, geom, idim, SliceType, - slice_realbox, 0, ncomp, nghost, real_box); - } - } - } - -} - -void -InterpolateLo(const Box& bx, FArrayBox &fabox, IntVect slice_lo, - Vector geom, int idir, IntVect IndType, - RealBox slice_realbox, int srccomp, int ncomp, - int /*nghost*/, const RealBox real_box ) -{ - auto fabarr = fabox.array(); - const auto lo = amrex::lbound(bx); - const auto hi = amrex::ubound(bx); - const double fac = ( 1.0-IndType[idir] )*geom[0].CellSize(idir) * 0.5; - const int imin = slice_lo[idir]; - const double minpos = imin*geom[0].CellSize(idir) + fac + real_box.lo(idir); - const double maxpos = (imin+1)*geom[0].CellSize(idir) + fac + real_box.lo(idir); - const double slice_minpos = slice_realbox.lo(idir) ; - - switch (idir) { - case 0: - { - if ( imin >= lo.x && imin <= lo.x) { - for (int n = srccomp; n < srccomp + ncomp; ++n) { - for (int k = lo.z; k <= hi.z; ++k) { - for (int j = lo.y; j <= hi.y; ++j) { - for (int i = lo.x; i <= hi.x; ++i) { - const double minval = fabarr(i,j,k,n); - const double maxval = fabarr(i+1,j,k,n); - const double ratio = (maxval - minval) / (maxpos - minpos); - const double xdiff = slice_minpos - minpos; - const double newval = minval + xdiff * ratio; - fabarr(i,j,k,n) = static_cast(newval); - } - } - } - } - } - break; - } - case 1: - { - if ( imin >= lo.y && imin <= lo.y) { - for (int n = srccomp; n < srccomp+ncomp; ++n) { - for (int k = lo.z; k <= hi.z; ++k) { - for (int j = lo.y; j <= hi.y; ++j) { - for (int i = lo.x; i <= hi.x; ++i) { - const double minval = fabarr(i,j,k,n); - const double maxval = fabarr(i,j+1,k,n); - const double ratio = (maxval - minval) / (maxpos - minpos); - const double xdiff = slice_minpos - minpos; - const double newval = minval + xdiff * ratio; - fabarr(i,j,k,n) = static_cast(newval); - } - } - } - } - } - break; - } - case 2: - { - if ( imin >= lo.z && imin <= lo.z) { - for (int n = srccomp; n < srccomp+ncomp; ++n) { - for (int k = lo.z; k <= hi.z; ++k) { - for (int j = lo.y; j <= hi.y; ++j) { - for (int i = lo.x; i <= hi.x; ++i) { - const double minval = fabarr(i,j,k,n); - const double maxval = fabarr(i,j,k+1,n); - const double ratio = (maxval - minval) / (maxpos - minpos); - const double xdiff = slice_minpos - minpos; - const double newval = minval + xdiff * ratio; - fabarr(i,j,k,n) = static_cast(newval); - } - } - } - } - } - break; - } - - } - -} diff --git a/Source/Diagnostics/WarpXIO.cpp b/Source/Diagnostics/WarpXIO.cpp index 43415daf151..e90ae98eb17 100644 --- a/Source/Diagnostics/WarpXIO.cpp +++ b/Source/Diagnostics/WarpXIO.cpp @@ -19,6 +19,7 @@ #include "Utils/WarpXProfilerWrapper.H" #include "WarpX.H" #include "Diagnostics/MultiDiagnostics.H" +#include "Diagnostics/ReducedDiags/MultiReducedDiags.H" #include #include @@ -400,8 +401,18 @@ WarpX::InitFromCheckpoint () if (EB::enabled()) { InitializeEBGridData(maxLevel()); } + reduced_diags->ReadCheckpointData(restart_chkfile); + // Initialize particles mypc->AllocData(); mypc->Restart(restart_chkfile); + if (m_implicit_solver) { + + m_implicit_solver->Define(this); + m_implicit_solver->GetParticleSolverParams( max_particle_its_in_implicit_scheme, + particle_tol_in_implicit_scheme ); + m_implicit_solver->CreateParticleAttributes(); + } + } diff --git a/Source/Diagnostics/WarpXOpenPMD.H b/Source/Diagnostics/WarpXOpenPMD.H index 99d6e0682ab..a25b1057da9 100644 --- a/Source/Diagnostics/WarpXOpenPMD.H +++ b/Source/Diagnostics/WarpXOpenPMD.H @@ -176,6 +176,19 @@ private: } } + /** Flushing out data of the current openPMD iteration + * + * @param[in] isBTD if the current diagnostic is BTD + * + * if isBTD=false, apply the default flush behaviour + * if isBTD=true, advice to use ADIOS Put() instead of PDW for better performance. + * + * iteration.seriesFlush() is used instead of series.flush() + * because the latter flushes only if data is dirty + * this causes trouble when the underlying writing function is collective (like PDW) + * + */ + void flushCurrent (bool isBTD) const; /** This function does initial setup for the fields when interation is newly created * @param[in] meshes The meshes in a series diff --git a/Source/Diagnostics/WarpXOpenPMD.cpp b/Source/Diagnostics/WarpXOpenPMD.cpp index e38ae8c8300..91b187b05e2 100644 --- a/Source/Diagnostics/WarpXOpenPMD.cpp +++ b/Source/Diagnostics/WarpXOpenPMD.cpp @@ -10,7 +10,6 @@ #include "Diagnostics/ParticleDiag/ParticleDiag.H" #include "FieldIO.H" #include "Particles/Filter/FilterFunctors.H" -#include "Particles/NamedComponentParticleContainer.H" #include "Utils/TextMsg.H" #include "Utils/Parser/ParserUtils.H" #include "Utils/RelativeCellPosition.H" @@ -402,6 +401,24 @@ WarpXOpenPMDPlot::~WarpXOpenPMDPlot () } } +void WarpXOpenPMDPlot::flushCurrent (bool isBTD) const +{ + WARPX_PROFILE("WarpXOpenPMDPlot::flushCurrent"); + + auto hasOption = m_OpenPMDoptions.find("FlattenSteps"); + const bool flattenSteps = isBTD && (m_Series->backend() == "ADIOS2") && (hasOption != std::string::npos); + + openPMD::Iteration currIteration = GetIteration(m_CurrentStep, isBTD); + if (flattenSteps) { + // delayed until all fields and particles are registered for flush + // and dumped once via flattenSteps + currIteration.seriesFlush( "adios2.engine.preferred_flush_target = \"buffer\"" ); + } + else { + currIteration.seriesFlush(); + } +} + std::string WarpXOpenPMDPlot::GetFileName (std::string& filepath) { @@ -531,10 +548,9 @@ WarpXOpenPMDPlot::WriteOpenPMDParticles (const amrex::Vector& part { WARPX_PROFILE("WarpXOpenPMDPlot::WriteOpenPMDParticles()"); -for (unsigned i = 0, n = particle_diags.size(); i < n; ++i) { - - WarpXParticleContainer* pc = particle_diags[i].getParticleContainer(); - PinnedMemoryParticleContainer* pinned_pc = particle_diags[i].getPinnedParticleContainer(); +for (const auto & particle_diag : particle_diags) { + WarpXParticleContainer* pc = particle_diag.getParticleContainer(); + PinnedMemoryParticleContainer* pinned_pc = particle_diag.getPinnedParticleContainer(); if (isBTD || use_pinned_pc) { if (!pinned_pc->isDefined()) { continue; // Skip to the next particle container @@ -546,17 +562,17 @@ for (unsigned i = 0, n = particle_diags.size(); i < n; ++i) { pc->make_alike(); const auto mass = pc->AmIA() ? PhysConst::m_e : pc->getMass(); - RandomFilter const random_filter(particle_diags[i].m_do_random_filter, - particle_diags[i].m_random_fraction); - UniformFilter const uniform_filter(particle_diags[i].m_do_uniform_filter, - particle_diags[i].m_uniform_stride); - ParserFilter parser_filter(particle_diags[i].m_do_parser_filter, + RandomFilter const random_filter(particle_diag.m_do_random_filter, + particle_diag.m_random_fraction); + UniformFilter const uniform_filter(particle_diag.m_do_uniform_filter, + particle_diag.m_uniform_stride); + ParserFilter parser_filter(particle_diag.m_do_parser_filter, utils::parser::compileParser - (particle_diags[i].m_particle_filter_parser.get()), + (particle_diag.m_particle_filter_parser.get()), pc->getMass(), time); parser_filter.m_units = InputUnits::SI; - GeometryFilter const geometry_filter(particle_diags[i].m_do_geom_filter, - particle_diags[i].m_diag_domain); + GeometryFilter const geometry_filter(particle_diag.m_do_geom_filter, + particle_diag.m_diag_domain); if (isBTD || use_pinned_pc) { particlesConvertUnits(ConvertDirection::WarpX_to_SI, pinned_pc, mass); @@ -587,54 +603,62 @@ for (unsigned i = 0, n = particle_diags.size(); i < n; ++i) { } // Gather the electrostatic potential (phi) on the macroparticles - if ( particle_diags[i].m_plot_phi ) { + if ( particle_diag.m_plot_phi ) { storePhiOnParticles( tmp, WarpX::electrostatic_solver_id, !use_pinned_pc ); } - // names of amrex::Real and int particle attributes in SoA data + // names of amrex::ParticleReal and int particle attributes in SoA data + auto const rn = tmp.GetRealSoANames(); + auto const in = tmp.GetIntSoANames(); amrex::Vector real_names; - amrex::Vector int_names; - amrex::Vector int_flags; - amrex::Vector real_flags; - // see openPMD ED-PIC extension for namings - // note: an underscore separates the record name from its component - // for non-scalar records - // note: in RZ, we reconstruct x,y,z positions from r,z,theta in WarpX + amrex::Vector int_names(in.begin(), in.end()); + + // transform names to openPMD, separated by underscores + { + // see openPMD ED-PIC extension for namings + // note: an underscore separates the record name from its component + // for non-scalar records + // note: in RZ, we reconstruct x,y,z positions from r,z,theta in WarpX #if !defined (WARPX_DIM_1D_Z) - real_names.push_back("position_x"); + real_names.push_back("position_x"); #endif #if defined (WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - real_names.push_back("position_y"); + real_names.push_back("position_y"); #endif - real_names.push_back("position_z"); - real_names.push_back("weighting"); - real_names.push_back("momentum_x"); - real_names.push_back("momentum_y"); - real_names.push_back("momentum_z"); - // get the names of the real comps - real_names.resize(tmp.NumRealComps()); - auto runtime_rnames = tmp.getParticleRuntimeComps(); - for (auto const& x : runtime_rnames) + real_names.push_back("position_z"); + real_names.push_back("weighting"); + real_names.push_back("momentum_x"); + real_names.push_back("momentum_y"); + real_names.push_back("momentum_z"); + } + for (size_t i = real_names.size(); i < rn.size(); ++i) + { + real_names.push_back(rn[i]); + } + + for (size_t i = PIdx::nattribs; i < rn.size(); ++i) { - real_names[x.second+PIdx::nattribs] = detail::snakeToCamel(x.first); + real_names[i] = detail::snakeToCamel(rn[i]); } + // plot any "extra" fields by default - real_flags = particle_diags[i].m_plot_flags; + amrex::Vector real_flags = particle_diag.m_plot_flags; real_flags.resize(tmp.NumRealComps(), 1); - // and the names - int_names.resize(tmp.NumIntComps()); - auto runtime_inames = tmp.getParticleRuntimeiComps(); - for (auto const& x : runtime_inames) + + // and the int names + for (size_t i = 0; i < in.size(); ++i) { - int_names[x.second+0] = detail::snakeToCamel(x.first); + int_names[i] = detail::snakeToCamel(in[i]); } + // plot by default + amrex::Vector int_flags; int_flags.resize(tmp.NumIntComps(), 1); // real_names contains a list of all real particle attributes. // real_flags is 1 or 0, whether quantity is dumped or not. DumpToFile(&tmp, - particle_diags.at(i).getSpeciesName(), + particle_diag.getSpeciesName(), m_CurrentStep, real_flags, int_flags, @@ -642,6 +666,17 @@ for (unsigned i = 0, n = particle_diags.size(); i < n; ++i) { pc->getCharge(), pc->getMass(), isBTD, isLastBTDFlush); } + + auto hasOption = m_OpenPMDoptions.find("FlattenSteps"); + const bool flattenSteps = isBTD && (m_Series->backend() == "ADIOS2") && (hasOption != std::string::npos); + + if (flattenSteps) + { + // forcing new step so data from each btd batch in + // preferred_flush_target="buffer" can be flushed out + openPMD::Iteration currIteration = GetIteration(m_CurrentStep, isBTD); + currIteration.seriesFlush(R"(adios2.engine.preferred_flush_target = "new_step")"); + } } void @@ -658,6 +693,7 @@ WarpXOpenPMDPlot::DumpToFile (ParticleContainer* pc, const bool isLastBTDFlush ) { + WARPX_PROFILE("WarpXOpenPMDPlot::DumpToFile()"); WARPX_ALWAYS_ASSERT_WITH_MESSAGE(m_Series != nullptr, "openPMD: series must be initialized"); AMREX_ALWAYS_ASSERT(write_real_comp.size() == pc->NumRealComps()); @@ -716,8 +752,7 @@ WarpXOpenPMDPlot::DumpToFile (ParticleContainer* pc, SetConstParticleRecordsEDPIC(currSpecies, positionComponents, NewParticleVectorSize, charge, mass); } - // open files from all processors, in case some will not contribute below - m_Series->flush(); + flushCurrent(isBTD); // dump individual particles bool contributed_particles = false; // did the local MPI rank contribute particles? @@ -758,6 +793,7 @@ WarpXOpenPMDPlot::DumpToFile (ParticleContainer* pc, // BP4 (ADIOS 2.8): last MPI rank's `Put` meta-data wins // BP5 (ADIOS 2.8): everyone has to write an empty block if (is_resizing_flush && !contributed_particles && isBTD && m_Series->backend() == "ADIOS2") { + WARPX_PROFILE("WarpXOpenPMDPlot::ResizeInADIOS()"); for( auto & [record_name, record] : currSpecies ) { for( auto & [comp_name, comp] : record ) { if (comp.constant()) { continue; } @@ -797,7 +833,7 @@ WarpXOpenPMDPlot::DumpToFile (ParticleContainer* pc, } } - m_Series->flush(); + flushCurrent(isBTD); } void @@ -1469,7 +1505,7 @@ WarpXOpenPMDPlot::WriteOpenPMDFieldsAll ( //const std::string& filename, amrex::Gpu::streamSynchronize(); #endif // Flush data to disk after looping over all components - m_Series->flush(); + flushCurrent(isBTD); } // levels loop (i) } #endif // WARPX_USE_OPENPMD @@ -1483,6 +1519,7 @@ WarpXParticleCounter::WarpXParticleCounter (ParticleContainer* pc): m_MPIRank{amrex::ParallelDescriptor::MyProc()}, m_MPISize{amrex::ParallelDescriptor::NProcs()} { + WARPX_PROFILE("WarpXOpenPMDPlot::ParticleCounter()"); m_ParticleCounterByLevel.resize(pc->finestLevel()+1); m_ParticleOffsetAtRank.resize(pc->finestLevel()+1); m_ParticleSizeAtRank.resize(pc->finestLevel()+1); diff --git a/Source/Diagnostics/requirements.txt b/Source/Diagnostics/requirements.txt index d9f5cb553ee..9c85c8a621d 100644 --- a/Source/Diagnostics/requirements.txt +++ b/Source/Diagnostics/requirements.txt @@ -5,4 +5,4 @@ # License: BSD-3-Clause-LBNL # keep this entry for GitHub's dependency graph -openPMD-api>=0.15.1 +openPMD-api>=0.16.1 diff --git a/Source/EmbeddedBoundary/CMakeLists.txt b/Source/EmbeddedBoundary/CMakeLists.txt index 2fa5e3e602b..909886bbad6 100644 --- a/Source/EmbeddedBoundary/CMakeLists.txt +++ b/Source/EmbeddedBoundary/CMakeLists.txt @@ -2,10 +2,10 @@ foreach(D IN LISTS WarpX_DIMS) warpx_set_suffix_dims(SD ${D}) target_sources(lib_${SD} PRIVATE + EmbeddedBoundaryInit.cpp Enabled.cpp WarpXInitEB.cpp WarpXFaceExtensions.cpp WarpXFaceInfoBox.H - Enabled.cpp ) endforeach() diff --git a/Source/EmbeddedBoundary/EmbeddedBoundaryInit.H b/Source/EmbeddedBoundary/EmbeddedBoundaryInit.H new file mode 100644 index 00000000000..ed29fe5b688 --- /dev/null +++ b/Source/EmbeddedBoundary/EmbeddedBoundaryInit.H @@ -0,0 +1,141 @@ +/* Copyright 2021-2025 Lorenzo Giacomel, Luca Fedeli + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#ifndef WARPX_EMBEDDED_BOUNDARY_EMBEDDED_BOUNDARY_INIT_H_ +#define WARPX_EMBEDDED_BOUNDARY_EMBEDDED_BOUNDARY_INIT_H_ + +#include "Enabled.H" + +#ifdef AMREX_USE_EB + +#include + +#include +#include +#include +#include + +#include + +namespace warpx::embedded_boundary +{ + + /** \brief Set a flag to indicate in which cells a particle should deposit charge/current + * with a reduced, order 1 shape. + * + * More specifically, the flag is set to 1 if any of the neighboring cells over which the + * particle shape might extend are either partially or fully covered by an embedded boundary. + * This ensures that a particle in this cell deposits with an order 1 shape, which in turn + * makes sure that the particle never deposits any charge in a partially or fully covered cell. + * + * \param[in] eb_reduce_particle_shape multifab to be filled with 1s and 0s + * \param[in] eb_fact EB factory + * \param[in] particle_shape_order order of the particle shape function + * \param[in] periodicity TODO Geom(0).periodicity() + */ + void MarkReducedShapeCells ( + std::unique_ptr & eb_reduce_particle_shape, + amrex::EBFArrayBoxFactory const & eb_fact, + int particle_shape_order, + const amrex::Periodicity& periodicity); + + /** \brief Set a flag to indicate on which grid points the field `field` + * should be updated, depending on their position relative to the embedded boundary. + * + * This function is used by all finite-difference solvers, except the + * ECT solver, which instead uses `MarkUpdateECellsECT` and `MarkUpdateBCellsECT`. + * It uses a stair-case approximation of the embedded boundary: + * If a grid point touches cells that are either partially or fully covered + * by the embedded boundary: the corresponding field is not updated. + * + * More specifically, this function fills the iMultiFabs in `eb_update` + * (which have the same indexType as the MultiFabs in `field`) with 1 + * or 0, depending on whether the grid point should be updated or not. + */ + void MarkUpdateCellsStairCase ( + std::array< std::unique_ptr,3> & eb_update, + ablastr::fields::VectorField const & field, + amrex::EBFArrayBoxFactory const & eb_fact ); + + /** \brief Set a flag to indicate on which grid points the E field + * should be updated, depending on their position relative to the embedded boundary. + * + * This function is used by ECT solver. The E field is not updated if + * the edge on which it is defined is fully covered by the embedded boundary. + * + * More specifically, this function fills the iMultiFabs in `eb_update_E` + * (which have the same indexType as the E field) with 1 or 0, depending + * on whether the grid point should be updated or not. + */ + void MarkUpdateECellsECT ( + std::array< std::unique_ptr,3> & eb_update_E, + ablastr::fields::VectorField const& edge_lengths ); + + /** \brief Set a flag to indicate on which grid points the B field + * should be updated, depending on their position relative to the embedded boundary. + * + * This function is used by ECT solver. The B field is not updated if + * the face on which it is defined is fully covered by the embedded boundary. + * + * More specifically, this function fills the iMultiFabs in `eb_update_B` + * (which have the same indexType as the B field) with 1 or 0, depending + * on whether the grid point should be updated or not. + */ + void MarkUpdateBCellsECT ( + std::array< std::unique_ptr,3> & eb_update_B, + ablastr::fields::VectorField const& face_areas, + ablastr::fields::VectorField const& edge_lengths ); + + /** + * \brief Initialize information for cell extensions. + * The flags convention for m_flag_info_face is as follows + * - 0 for unstable cells + * - 1 for stable cells which have not been intruded + * - 2 for stable cells which have been intruded + * Here we cannot know if a cell is intruded or not so we initialize all stable cells with 1 + */ + void MarkExtensionCells( + const std::array& cell_size, + std::array< std::unique_ptr, 3 > & flag_info_face, + std::array< std::unique_ptr, 3 > & flag_ext_face, + const ablastr::fields::VectorField& b_field, + const ablastr::fields::VectorField& face_areas, + const ablastr::fields::VectorField& edge_lengths, + const ablastr::fields::VectorField& area_mod); + + /** + * \brief Compute the length of the mesh edges. Here the length is a value in [0, 1]. + * An edge of length 0 is fully covered. + */ + void ComputeEdgeLengths ( + ablastr::fields::VectorField& edge_lengths, + const amrex::EBFArrayBoxFactory& eb_fact); + /** + * \brief Compute the area of the mesh faces. Here the area is a value in [0, 1]. + * An edge of area 0 is fully covered. + */ + void ComputeFaceAreas ( + ablastr::fields::VectorField& face_areas, + const amrex::EBFArrayBoxFactory& eb_fact); + + /** + * \brief Scale the edges lengths by the mesh width to obtain the real lengths. + */ + void ScaleEdges ( + ablastr::fields::VectorField& edge_lengths, + const std::array& cell_size); + /** + * \brief Scale the edges areas by the mesh width to obtain the real areas. + */ + void ScaleAreas ( + ablastr::fields::VectorField& face_areas, + const std::array& cell_size); +} + +#endif + +#endif //WARPX_EMBEDDED_BOUNDARY_EMBEDDED_BOUNDARY_H_ diff --git a/Source/EmbeddedBoundary/EmbeddedBoundaryInit.cpp b/Source/EmbeddedBoundary/EmbeddedBoundaryInit.cpp new file mode 100644 index 00000000000..6a4caec2e99 --- /dev/null +++ b/Source/EmbeddedBoundary/EmbeddedBoundaryInit.cpp @@ -0,0 +1,614 @@ +/* Copyright 2021-2025 Lorenzo Giacomel, Luca Fedeli + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#include "Enabled.H" + +#ifdef AMREX_USE_EB + +#include "EmbeddedBoundaryInit.H" + +#include "Fields.H" +#include "Utils/TextMsg.H" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace web = warpx::embedded_boundary; + +void +web::MarkReducedShapeCells ( + std::unique_ptr & eb_reduce_particle_shape, + amrex::EBFArrayBoxFactory const & eb_fact, + int const particle_shape_order, + const amrex::Periodicity& periodicity) +{ + // Pre-fill array with 0, including in the ghost cells outside of the domain. + // (The guard cells in the domain will be updated by `FillBoundary` at the end of this function.) + eb_reduce_particle_shape->setVal(0, eb_reduce_particle_shape->nGrow()); + + // Extract structures for embedded boundaries + amrex::FabArray const& eb_flag = eb_fact.getMultiEBCellFlagFab(); + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for (amrex::MFIter mfi(*eb_reduce_particle_shape); mfi.isValid(); ++mfi) { + + const amrex::Box& box = mfi.tilebox(); + amrex::Array4 const & eb_reduce_particle_shape_arr = eb_reduce_particle_shape->array(mfi); + + // Check if the box (including one layer of guard cells) contains a mix of covered and regular cells + const amrex::Box eb_info_box = mfi.tilebox(amrex::IntVect::TheCellVector()).grow(1); + amrex::FabType const fab_type = eb_flag[mfi].getType( eb_info_box ); + + if (fab_type == amrex::FabType::regular) { // All cells in the box are regular + + // Every cell in box is regular: do not reduce particle shape in any cell + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + eb_reduce_particle_shape_arr(i, j, k) = 0; + }); + + } else if (fab_type == amrex::FabType::covered) { // All cells in the box are covered + + // Every cell in box is fully covered: reduce particle shape + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + eb_reduce_particle_shape_arr(i, j, k) = 1; + }); + + } else { // The box contains a mix of covered and regular cells + + auto const & flag = eb_flag[mfi].array(); + + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + + // Check if any of the neighboring cells over which the particle shape might extend + // are either partially or fully covered. In this case, set eb_reduce_particle_shape_arr + // to one for this cell, to indicate that the particle should use an order 1 shape + // (This ensures that the particle never deposits any charge in a partially or + // fully covered cell, even with higher-order shapes) + // Note: in the code below `particle_shape_order/2` corresponds to the number of neighboring cells + // over which the shape factor could extend, in each direction. + int const i_start = i-particle_shape_order/2; + int const i_end = i+particle_shape_order/2; +#if AMREX_SPACEDIM > 1 + int const j_start = j-particle_shape_order/2; + int const j_end = j+particle_shape_order/2; +#else + int const j_start = j; + int const j_end = j; +#endif +#if AMREX_SPACEDIM > 2 + int const k_start = k-particle_shape_order/2; + int const k_end = k+particle_shape_order/2; +#else + int const k_start = k; + int const k_end = k; +#endif + int reduce_shape = 0; + for (int i_cell = i_start; i_cell <= i_end; ++i_cell) { + for (int j_cell = j_start; j_cell <= j_end; ++j_cell) { + for (int k_cell = k_start; k_cell <= k_end; ++k_cell) { + // `isRegular` returns `false` if the cell is either partially or fully covered. + if ( !flag(i_cell, j_cell, k_cell).isRegular() ) { + reduce_shape = 1; + } + } + } + } + eb_reduce_particle_shape_arr(i, j, k) = reduce_shape; + }); + + } + + } + // FillBoundary to set the values in the guard cells + eb_reduce_particle_shape->FillBoundary(periodicity); +} + +void +web::MarkUpdateCellsStairCase ( + std::array< std::unique_ptr,3> & eb_update, + ablastr::fields::VectorField const& field, + amrex::EBFArrayBoxFactory const & eb_fact ) +{ + + using ablastr::fields::Direction; + using warpx::fields::FieldType; + + // Extract structures for embedded boundaries + amrex::FabArray const& eb_flag = eb_fact.getMultiEBCellFlagFab(); + + for (int idim = 0; idim < 3; ++idim) { + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for (amrex::MFIter mfi(*field[idim]); mfi.isValid(); ++mfi) { + + const amrex::Box& box = mfi.tilebox(); + amrex::Array4 const & eb_update_arr = eb_update[idim]->array(mfi); + + // Check if the box (including one layer of guard cells) contains a mix of covered and regular cells + const amrex::Box eb_info_box = mfi.tilebox(amrex::IntVect::TheCellVector()).grow(1); + amrex::FabType const fab_type = eb_flag[mfi].getType( eb_info_box ); + + if (fab_type == amrex::FabType::regular) { // All cells in the box are regular + + // Every cell in box is regular: update field in every cell + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + eb_update_arr(i, j, k) = 1; + }); + + } else if (fab_type == amrex::FabType::covered) { // All cells in the box are covered + + // Every cell in box is fully covered: do not update field + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + eb_update_arr(i, j, k) = 0; + }); + + } else { // The box contains a mix of covered and regular cells + + auto const & flag = eb_flag[mfi].array(); + auto index_type = field[idim]->ixType(); + + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + + // Stair-case approximation: If neighboring cells of this gridpoint + // are either partially or fully covered: do not update field + + // The number of cells that we need to check depend on the index type + // of the `eb_update_arr` in each direction. + // If `eb_update_arr` is nodal in a given direction, we need to check the cells + // to the left and right of this nodal gridpoint. + // For instance, if `eb_update_arr` is nodal in the first dimension, we need + // to check the cells at index i-1 and at index i, since, with AMReX indexing conventions, + // these are the neighboring cells for the nodal gripoint at index i. + // If `eb_update_arr` is cell-centerd in a given direction, we only need to check + // the cell at the same position (e.g., in the first dimension: the cell at index i). + int const i_start = ( index_type.nodeCentered(0) )? i-1 : i; +#if AMREX_SPACEDIM > 1 + int const j_start = ( index_type.nodeCentered(1) )? j-1 : j; +#else + int const j_start = j; +#endif +#if AMREX_SPACEDIM > 2 + int const k_start = ( index_type.nodeCentered(2) )? k-1 : k; +#else + int const k_start = k; +#endif + // Loop over neighboring cells + int eb_update_flag = 1; + for (int i_cell = i_start; i_cell <= i; ++i_cell) { + for (int j_cell = j_start; j_cell <= j; ++j_cell) { + for (int k_cell = k_start; k_cell <= k; ++k_cell) { + // If one of the neighboring is either partially or fully covered + // (i.e. if they are not regular cells), do not update field + // (`isRegular` returns `false` if the cell is either partially or fully covered.) + if ( !flag(i_cell, j_cell, k_cell).isRegular() ) { + eb_update_flag = 0; + } + } + } + } + eb_update_arr(i, j, k) = eb_update_flag; + }); + + } + + } + + } + +} + +void +web::MarkUpdateECellsECT ( + std::array< std::unique_ptr,3> & eb_update_E, + ablastr::fields::VectorField const& edge_lengths ) +{ + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( amrex::MFIter mfi(*eb_update_E[0], amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) { + + const amrex::Box& tbx = mfi.tilebox( eb_update_E[0]->ixType().toIntVect(), eb_update_E[0]->nGrowVect() ); + const amrex::Box& tby = mfi.tilebox( eb_update_E[1]->ixType().toIntVect(), eb_update_E[1]->nGrowVect() ); + const amrex::Box& tbz = mfi.tilebox( eb_update_E[2]->ixType().toIntVect(), eb_update_E[2]->nGrowVect() ); + + amrex::Array4 const & eb_update_Ex_arr = eb_update_E[0]->array(mfi); + amrex::Array4 const & eb_update_Ey_arr = eb_update_E[1]->array(mfi); + amrex::Array4 const & eb_update_Ez_arr = eb_update_E[2]->array(mfi); + + amrex::Array4 const & lx_arr = edge_lengths[0]->array(mfi); + amrex::Array4 const & lz_arr = edge_lengths[2]->array(mfi); +#if defined(WARPX_DIM_3D) + amrex::Array4 const & ly_arr = edge_lengths[1]->array(mfi); +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + amrex::Dim3 const lx_lo = amrex::lbound(lx_arr); + amrex::Dim3 const lx_hi = amrex::ubound(lx_arr); + amrex::Dim3 const lz_lo = amrex::lbound(lz_arr); + amrex::Dim3 const lz_hi = amrex::ubound(lz_arr); +#endif + + amrex::ParallelFor (tbx, tby, tbz, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { + // Do not update Ex if the edge on which it lives is fully covered + eb_update_Ex_arr(i, j, k) = (lx_arr(i, j, k) == 0)? 0 : 1; + }, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { +#ifdef WARPX_DIM_3D + // In 3D: Do not update Ey if the edge on which it lives is fully covered + eb_update_Ey_arr(i, j, k) = (ly_arr(i, j, k) == 0)? 0 : 1; +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + // In XZ and RZ: Ey is associated with a mesh node, + // so we need to check if the mesh node is covered + if((lx_arr(std::min(i , lx_hi.x), std::min(j , lx_hi.y), k)==0) + ||(lx_arr(std::max(i-1, lx_lo.x), std::min(j , lx_hi.y), k)==0) + ||(lz_arr(std::min(i , lz_hi.x), std::min(j , lz_hi.y), k)==0) + ||(lz_arr(std::min(i , lz_hi.x), std::max(j-1, lz_lo.y), k)==0)) { + eb_update_Ey_arr(i, j, k) = 0; + } else { + eb_update_Ey_arr(i, j, k) = 1; + } +#endif + }, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { + // Do not update Ez if the edge on which it lives is fully covered + eb_update_Ez_arr(i, j, k) = (lz_arr(i, j, k) == 0)? 0 : 1; + } + ); + + } +} + +void +web::MarkUpdateBCellsECT ( + std::array< std::unique_ptr,3> & eb_update_B, + ablastr::fields::VectorField const& face_areas, + ablastr::fields::VectorField const& edge_lengths ) +{ + +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( amrex::MFIter mfi(*eb_update_B[0], amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) { + + const amrex::Box& tbx = mfi.tilebox( eb_update_B[0]->ixType().toIntVect(), eb_update_B[0]->nGrowVect() ); + const amrex::Box& tby = mfi.tilebox( eb_update_B[1]->ixType().toIntVect(), eb_update_B[1]->nGrowVect() ); + const amrex::Box& tbz = mfi.tilebox( eb_update_B[2]->ixType().toIntVect(), eb_update_B[2]->nGrowVect() ); + + amrex::Array4 const & eb_update_Bx_arr = eb_update_B[0]->array(mfi); + amrex::Array4 const & eb_update_By_arr = eb_update_B[1]->array(mfi); + amrex::Array4 const & eb_update_Bz_arr = eb_update_B[2]->array(mfi); + +#ifdef WARPX_DIM_3D + amrex::Array4 const & Sx_arr = face_areas[0]->array(mfi); + amrex::Array4 const & Sy_arr = face_areas[1]->array(mfi); + amrex::Array4 const & Sz_arr = face_areas[2]->array(mfi); + amrex::ignore_unused(edge_lengths); +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + amrex::Array4 const & Sy_arr = face_areas[1]->array(mfi); + amrex::Array4 const & lx_arr = edge_lengths[0]->array(mfi); + amrex::Array4 const & lz_arr = edge_lengths[2]->array(mfi); +#endif + amrex::ParallelFor (tbx, tby, tbz, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { +#ifdef WARPX_DIM_3D + // In 3D: do not update Bx if the face on which it lives is fully covered + eb_update_Bx_arr(i, j, k) = (Sx_arr(i, j, k) == 0)? 0 : 1; +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + //In XZ and RZ, Bx lives on a z-edge ; do not update if fully covered + eb_update_Bx_arr(i, j, k) = (lz_arr(i, j, k) == 0)? 0 : 1; +#endif + }, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { + // Do not update By if the face on which it lives is fully covered + eb_update_By_arr(i, j, k) = (Sy_arr(i, j, k) == 0)? 0 : 1; + }, + [=] AMREX_GPU_DEVICE (int i, int j, int k) { +#ifdef WARPX_DIM_3D + // In 3D: do not update Bz if the face on which it lives is fully covered + eb_update_Bz_arr(i, j, k) = (Sz_arr(i, j, k) == 0)? 0 : 1; +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + //In XZ and RZ, Bz lives on a x-edge ; do not update if fully covered + eb_update_Bz_arr(i, j, k) = (lx_arr(i, j, k) == 0)? 0 : 1; +#endif + } + ); + + } +} + +void +web::MarkExtensionCells ( + const std::array& cell_size, + std::array< std::unique_ptr, 3 > & flag_info_face, + std::array< std::unique_ptr, 3 > & flag_ext_face, + const ablastr::fields::VectorField& b_field, + const ablastr::fields::VectorField& face_areas, + const ablastr::fields::VectorField& edge_lengths, + const ablastr::fields::VectorField& area_mod) +{ + using ablastr::fields::Direction; + using warpx::fields::FieldType; + +#ifdef WARPX_DIM_RZ + amrex::ignore_unused(cell_size, flag_info_face, flag_ext_face, b_field, + face_areas, edge_lengths, area_mod); + +#elif !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) + + WARPX_ABORT_WITH_MESSAGE("MarkExtensionCells only implemented in 2D and 3D"); + +#else + + for (int idim = 0; idim < 3; ++idim) { + +# if defined(WARPX_DIM_XZ) + if (idim == 0 || idim == 2) { + flag_info_face[idim]->setVal(0.); + flag_ext_face[idim]->setVal(0.); + continue; + } +# endif + for (amrex::MFIter mfi(*b_field[idim]); mfi.isValid(); ++mfi) { + auto* face_areas_idim_max_lev = face_areas[idim]; + + const amrex::Box& box = mfi.tilebox(face_areas_idim_max_lev->ixType().toIntVect(), + face_areas_idim_max_lev->nGrowVect() ); + + auto const& S = face_areas_idim_max_lev->array(mfi); + auto const& flag_info_face_data = flag_info_face[idim]->array(mfi); + auto const& flag_ext_face_data = flag_ext_face[idim]->array(mfi); + auto const& lx = edge_lengths[0]->array(mfi); + auto const& ly = edge_lengths[1]->array(mfi); + auto const& lz = edge_lengths[2]->array(mfi); + auto const& mod_areas_dim_data = area_mod[idim]->array(mfi); + + const amrex::Real dx = cell_size[0]; + const amrex::Real dy = cell_size[1]; + const amrex::Real dz = cell_size[2]; + + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + // Minimal area for this cell to be stable + mod_areas_dim_data(i, j, k) = S(i, j, k); + double S_stab; + if (idim == 0){ + S_stab = 0.5 * std::max({ly(i, j, k) * dz, ly(i, j, k + 1) * dz, + lz(i, j, k) * dy, lz(i, j + 1, k) * dy}); + }else if (idim == 1){ + +# if defined(WARPX_DIM_XZ) + S_stab = 0.5 * std::max({lx(i, j, k) * dz, lx(i, j + 1, k) * dz, + lz(i, j, k) * dx, lz(i + 1, j, k) * dx}); +# else + S_stab = 0.5 * std::max({lx(i, j, k) * dz, lx(i, j, k + 1) * dz, + lz(i, j, k) * dx, lz(i + 1, j, k) * dx}); +# endif + }else { + S_stab = 0.5 * std::max({lx(i, j, k) * dy, lx(i, j + 1, k) * dy, + ly(i, j, k) * dx, ly(i + 1, j, k) * dx}); + } + + // Does this face need to be extended? + // The difference between flag_info_face and flag_ext_face is that: + // - for every face flag_info_face contains a: + // * 0 if the face needs to be extended + // * 1 if the face is large enough to lend area to other faces + // * 2 if the face is actually intruded by other face + // Here we only take care of the first two cases. The entries corresponding + // to the intruded faces are going to be set in the function ComputeFaceExtensions + // - for every face flag_ext_face contains a: + // * 1 if the face needs to be extended + // * 0 otherwise + // In the function ComputeFaceExtensions, after the cells are extended, the + // corresponding entries in flag_ext_face are set to zero. This helps to keep + // track of which cells could not be extended + flag_ext_face_data(i, j, k) = int(S(i, j, k) < S_stab && S(i, j, k) > 0); + if(flag_ext_face_data(i, j, k)){ + flag_info_face_data(i, j, k) = 0; + } + // Is this face available to lend area to other faces? + // The criterion is that the face has to be interior and not already unstable itself + if(int(S(i, j, k) > 0 && !flag_ext_face_data(i, j, k))) { + flag_info_face_data(i, j, k) = 1; + } + }); + } + } +#endif +} + +void +web::ComputeEdgeLengths ( + ablastr::fields::VectorField& edge_lengths, + const amrex::EBFArrayBoxFactory& eb_fact) +{ + BL_PROFILE("ComputeEdgeLengths"); + +#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) + WARPX_ABORT_WITH_MESSAGE("ComputeEdgeLengths only implemented in 2D and 3D"); +#endif + + auto const &flags = eb_fact.getMultiEBCellFlagFab(); + auto const &edge_centroid = eb_fact.getEdgeCent(); + for (int idim = 0; idim < 3; ++idim){ +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + if (idim == 1) { + edge_lengths[1]->setVal(0.); + continue; + } +#endif + for (amrex::MFIter mfi(flags); mfi.isValid(); ++mfi){ + amrex::Box const box = mfi.tilebox(edge_lengths[idim]->ixType().toIntVect(), + edge_lengths[idim]->nGrowVect()); + amrex::FabType const fab_type = flags[mfi].getType(box); + auto const &edge_lengths_dim = edge_lengths[idim]->array(mfi); + + if (fab_type == amrex::FabType::regular) { + // every cell in box is all regular + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + edge_lengths_dim(i, j, k) = 1.; + }); + } else if (fab_type == amrex::FabType::covered) { + // every cell in box is all covered + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + edge_lengths_dim(i, j, k) = 0.; + }); + } else { +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + int idim_amrex = idim; + if (idim == 2) { idim_amrex = 1; } + auto const &edge_cent = edge_centroid[idim_amrex]->const_array(mfi); +#elif defined(WARPX_DIM_3D) + auto const &edge_cent = edge_centroid[idim]->const_array(mfi); +#endif + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + if (edge_cent(i, j, k) == amrex::Real(-1.0)) { + // This edge is all covered + edge_lengths_dim(i, j, k) = 0.; + } else if (edge_cent(i, j, k) == amrex::Real(1.0)) { + // This edge is all open + edge_lengths_dim(i, j, k) = 1.; + } else { + // This edge is cut. + edge_lengths_dim(i, j, k) = 1 - amrex::Math::abs(amrex::Real(2.0) + * edge_cent(i, j, k)); + } + + }); + } + } + } +} + + +void +web::ComputeFaceAreas ( + ablastr::fields::VectorField& face_areas, + const amrex::EBFArrayBoxFactory& eb_fact) +{ + BL_PROFILE("ComputeFaceAreas"); + +#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) + WARPX_ABORT_WITH_MESSAGE("ComputeFaceAreas only implemented in 2D and 3D"); +#endif + + auto const &flags = eb_fact.getMultiEBCellFlagFab(); +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + //In 2D the volume frac is actually the area frac. + auto const &area_frac = eb_fact.getVolFrac(); +#elif defined(WARPX_DIM_3D) + auto const &area_frac = eb_fact.getAreaFrac(); +#endif + + for (int idim = 0; idim < 3; ++idim) { +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + if (idim == 0 || idim == 2) { + face_areas[idim]->setVal(0.); + continue; + } +#endif + for (amrex::MFIter mfi(flags); mfi.isValid(); ++mfi) { + amrex::Box const box = mfi.tilebox(face_areas[idim]->ixType().toIntVect(), + face_areas[idim]->nGrowVect()); + amrex::FabType const fab_type = flags[mfi].getType(box); + auto const &face_areas_dim = face_areas[idim]->array(mfi); + if (fab_type == amrex::FabType::regular) { + // every cell in box is all regular + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + face_areas_dim(i, j, k) = amrex::Real(1.); + }); + } else if (fab_type == amrex::FabType::covered) { + // every cell in box is all covered + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + face_areas_dim(i, j, k) = amrex::Real(0.); + }); + } else { +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + auto const &face = area_frac.const_array(mfi); +#elif defined(WARPX_DIM_3D) + auto const &face = area_frac[idim]->const_array(mfi); +#endif + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + face_areas_dim(i, j, k) = face(i, j, k); + }); + } + } + } +} + +void +web::ScaleEdges ( + ablastr::fields::VectorField& edge_lengths, + const std::array& cell_size) +{ + BL_PROFILE("ScaleEdges"); + +#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) + WARPX_ABORT_WITH_MESSAGE("ScaleEdges only implemented in 2D and 3D"); +#endif + + for (int idim = 0; idim < 3; ++idim){ +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + if (idim == 1) { continue; } +#endif + for (amrex::MFIter mfi(*edge_lengths[0]); mfi.isValid(); ++mfi) { + const amrex::Box& box = mfi.tilebox(edge_lengths[idim]->ixType().toIntVect(), + edge_lengths[idim]->nGrowVect() ); + auto const &edge_lengths_dim = edge_lengths[idim]->array(mfi); + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + edge_lengths_dim(i, j, k) *= cell_size[idim]; + }); + } + } +} + + +void +web::ScaleAreas ( + ablastr::fields::VectorField& face_areas, + const std::array& cell_size) +{ + BL_PROFILE("ScaleAreas"); + +#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) + WARPX_ABORT_WITH_MESSAGE("ScaleAreas only implemented in 2D and 3D"); +#endif + + for (int idim = 0; idim < 3; ++idim) { +#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + if (idim == 0 || idim == 2) { continue; } +#endif + for (amrex::MFIter mfi(*face_areas[0]); mfi.isValid(); ++mfi) { + const amrex::Box& box = mfi.tilebox(face_areas[idim]->ixType().toIntVect(), + face_areas[idim]->nGrowVect() ); + amrex::Real const full_area = cell_size[(idim+1)%3]*cell_size[(idim+2)%3]; + auto const &face_areas_dim = face_areas[idim]->array(mfi); + + amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { + face_areas_dim(i, j, k) *= full_area; + }); + + } + } +} + +#endif diff --git a/Source/EmbeddedBoundary/Make.package b/Source/EmbeddedBoundary/Make.package index 76a20896f85..fd46932827d 100644 --- a/Source/EmbeddedBoundary/Make.package +++ b/Source/EmbeddedBoundary/Make.package @@ -1,9 +1,11 @@ +CEXE_headers += EmbeddedBoundaryInit.H CEXE_headers += Enabled.H CEXE_headers += ParticleScraper.H CEXE_headers += ParticleBoundaryProcess.H CEXE_headers += DistanceToEB.H CEXE_headers += WarpXFaceInfoBox.H +CEXE_sources += EmbeddedBoundaryInit.cpp CEXE_sources += Enabled.cpp CEXE_sources += WarpXInitEB.cpp CEXE_sources += WarpXFaceExtensions.cpp diff --git a/Source/EmbeddedBoundary/WarpXInitEB.cpp b/Source/EmbeddedBoundary/WarpXInitEB.cpp index edbc97a8efe..8b7ad7b9d64 100644 --- a/Source/EmbeddedBoundary/WarpXInitEB.cpp +++ b/Source/EmbeddedBoundary/WarpXInitEB.cpp @@ -13,31 +13,17 @@ # include "Utils/Parser/ParserUtils.H" # include "Utils/TextMsg.H" -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include # include # include @@ -123,265 +109,6 @@ WarpX::InitEB () #endif } -#ifdef AMREX_USE_EB -void -WarpX::ComputeEdgeLengths (ablastr::fields::VectorField& edge_lengths, - const amrex::EBFArrayBoxFactory& eb_fact) { - BL_PROFILE("ComputeEdgeLengths"); - -#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) - WARPX_ABORT_WITH_MESSAGE("ComputeEdgeLengths only implemented in 2D and 3D"); -#endif - - auto const &flags = eb_fact.getMultiEBCellFlagFab(); - auto const &edge_centroid = eb_fact.getEdgeCent(); - for (int idim = 0; idim < 3; ++idim){ -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - if (idim == 1) { - edge_lengths[1]->setVal(0.); - continue; - } -#endif - for (amrex::MFIter mfi(flags); mfi.isValid(); ++mfi){ - amrex::Box const box = mfi.tilebox(edge_lengths[idim]->ixType().toIntVect(), - edge_lengths[idim]->nGrowVect()); - amrex::FabType const fab_type = flags[mfi].getType(box); - auto const &edge_lengths_dim = edge_lengths[idim]->array(mfi); - - if (fab_type == amrex::FabType::regular) { - // every cell in box is all regular - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - edge_lengths_dim(i, j, k) = 1.; - }); - } else if (fab_type == amrex::FabType::covered) { - // every cell in box is all covered - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - edge_lengths_dim(i, j, k) = 0.; - }); - } else { -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - int idim_amrex = idim; - if (idim == 2) { idim_amrex = 1; } - auto const &edge_cent = edge_centroid[idim_amrex]->const_array(mfi); -#elif defined(WARPX_DIM_3D) - auto const &edge_cent = edge_centroid[idim]->const_array(mfi); -#endif - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - if (edge_cent(i, j, k) == amrex::Real(-1.0)) { - // This edge is all covered - edge_lengths_dim(i, j, k) = 0.; - } else if (edge_cent(i, j, k) == amrex::Real(1.0)) { - // This edge is all open - edge_lengths_dim(i, j, k) = 1.; - } else { - // This edge is cut. - edge_lengths_dim(i, j, k) = 1 - amrex::Math::abs(amrex::Real(2.0) - * edge_cent(i, j, k)); - } - - }); - } - } - } -} - - -void -WarpX::ComputeFaceAreas (VectorField& face_areas, - const amrex::EBFArrayBoxFactory& eb_fact) { - BL_PROFILE("ComputeFaceAreas"); - -#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) - WARPX_ABORT_WITH_MESSAGE("ComputeFaceAreas only implemented in 2D and 3D"); -#endif - - auto const &flags = eb_fact.getMultiEBCellFlagFab(); -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - //In 2D the volume frac is actually the area frac. - auto const &area_frac = eb_fact.getVolFrac(); -#elif defined(WARPX_DIM_3D) - auto const &area_frac = eb_fact.getAreaFrac(); -#endif - - for (int idim = 0; idim < 3; ++idim) { -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - if (idim == 0 || idim == 2) { - face_areas[idim]->setVal(0.); - continue; - } -#endif - for (amrex::MFIter mfi(flags); mfi.isValid(); ++mfi) { - amrex::Box const box = mfi.tilebox(face_areas[idim]->ixType().toIntVect(), - face_areas[idim]->nGrowVect()); - amrex::FabType const fab_type = flags[mfi].getType(box); - auto const &face_areas_dim = face_areas[idim]->array(mfi); - if (fab_type == amrex::FabType::regular) { - // every cell in box is all regular - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - face_areas_dim(i, j, k) = amrex::Real(1.); - }); - } else if (fab_type == amrex::FabType::covered) { - // every cell in box is all covered - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - face_areas_dim(i, j, k) = amrex::Real(0.); - }); - } else { -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - auto const &face = area_frac.const_array(mfi); -#elif defined(WARPX_DIM_3D) - auto const &face = area_frac[idim]->const_array(mfi); -#endif - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - face_areas_dim(i, j, k) = face(i, j, k); - }); - } - } - } -} - - -void -WarpX::ScaleEdges (ablastr::fields::VectorField& edge_lengths, - const std::array& cell_size) { - BL_PROFILE("ScaleEdges"); - -#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) - WARPX_ABORT_WITH_MESSAGE("ScaleEdges only implemented in 2D and 3D"); -#endif - - for (int idim = 0; idim < 3; ++idim){ -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - if (idim == 1) { continue; } -#endif - for (amrex::MFIter mfi(*edge_lengths[0]); mfi.isValid(); ++mfi) { - const amrex::Box& box = mfi.tilebox(edge_lengths[idim]->ixType().toIntVect(), - edge_lengths[idim]->nGrowVect() ); - auto const &edge_lengths_dim = edge_lengths[idim]->array(mfi); - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - edge_lengths_dim(i, j, k) *= cell_size[idim]; - }); - } - } -} - -void -WarpX::ScaleAreas (ablastr::fields::VectorField& face_areas, - const std::array& cell_size) { - BL_PROFILE("ScaleAreas"); - -#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) && !defined(WARPX_DIM_RZ) - WARPX_ABORT_WITH_MESSAGE("ScaleAreas only implemented in 2D and 3D"); -#endif - - for (int idim = 0; idim < 3; ++idim) { -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - if (idim == 0 || idim == 2) { continue; } -#endif - for (amrex::MFIter mfi(*face_areas[0]); mfi.isValid(); ++mfi) { - const amrex::Box& box = mfi.tilebox(face_areas[idim]->ixType().toIntVect(), - face_areas[idim]->nGrowVect() ); - amrex::Real const full_area = cell_size[(idim+1)%3]*cell_size[(idim+2)%3]; - auto const &face_areas_dim = face_areas[idim]->array(mfi); - - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - face_areas_dim(i, j, k) *= full_area; - }); - - } - } -} - - -void -WarpX::MarkCells () -{ - using ablastr::fields::Direction; - using warpx::fields::FieldType; - -#ifndef WARPX_DIM_RZ - auto const &cell_size = CellSize(maxLevel()); - -#if !defined(WARPX_DIM_3D) && !defined(WARPX_DIM_XZ) - WARPX_ABORT_WITH_MESSAGE("MarkCells only implemented in 2D and 3D"); -#endif - - for (int idim = 0; idim < 3; ++idim) { -#if defined(WARPX_DIM_XZ) - if (idim == 0 || idim == 2) { - m_flag_info_face[maxLevel()][idim]->setVal(0.); - m_flag_ext_face[maxLevel()][idim]->setVal(0.); - continue; - } -#endif - for (amrex::MFIter mfi(*m_fields.get(FieldType::Bfield_fp, Direction{idim}, maxLevel())); mfi.isValid(); ++mfi) { - auto* face_areas_idim_max_lev = - m_fields.get(FieldType::face_areas, Direction{idim}, maxLevel()); - - const amrex::Box& box = mfi.tilebox(face_areas_idim_max_lev->ixType().toIntVect(), - face_areas_idim_max_lev->nGrowVect() ); - - auto const &S = face_areas_idim_max_lev->array(mfi); - auto const &flag_info_face = m_flag_info_face[maxLevel()][idim]->array(mfi); - auto const &flag_ext_face = m_flag_ext_face[maxLevel()][idim]->array(mfi); - const auto &lx = m_fields.get(FieldType::edge_lengths, Direction{0}, maxLevel())->array(mfi); - const auto &ly = m_fields.get(FieldType::edge_lengths, Direction{1}, maxLevel())->array(mfi); - const auto &lz = m_fields.get(FieldType::edge_lengths, Direction{2}, maxLevel())->array(mfi); - auto const &mod_areas_dim = m_fields.get(FieldType::area_mod, Direction{idim}, maxLevel())->array(mfi); - - const amrex::Real dx = cell_size[0]; - const amrex::Real dy = cell_size[1]; - const amrex::Real dz = cell_size[2]; - - amrex::ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) { - // Minimal area for this cell to be stable - mod_areas_dim(i, j, k) = S(i, j, k); - double S_stab; - if (idim == 0){ - S_stab = 0.5 * std::max({ly(i, j, k) * dz, ly(i, j, k + 1) * dz, - lz(i, j, k) * dy, lz(i, j + 1, k) * dy}); - }else if (idim == 1){ -#ifdef WARPX_DIM_XZ - S_stab = 0.5 * std::max({lx(i, j, k) * dz, lx(i, j + 1, k) * dz, - lz(i, j, k) * dx, lz(i + 1, j, k) * dx}); -#elif defined(WARPX_DIM_3D) - S_stab = 0.5 * std::max({lx(i, j, k) * dz, lx(i, j, k + 1) * dz, - lz(i, j, k) * dx, lz(i + 1, j, k) * dx}); -#endif - }else { - S_stab = 0.5 * std::max({lx(i, j, k) * dy, lx(i, j + 1, k) * dy, - ly(i, j, k) * dx, ly(i + 1, j, k) * dx}); - } - - // Does this face need to be extended? - // The difference between flag_info_face and flag_ext_face is that: - // - for every face flag_info_face contains a: - // * 0 if the face needs to be extended - // * 1 if the face is large enough to lend area to other faces - // * 2 if the face is actually intruded by other face - // Here we only take care of the first two cases. The entries corresponding - // to the intruded faces are going to be set in the function ComputeFaceExtensions - // - for every face flag_ext_face contains a: - // * 1 if the face needs to be extended - // * 0 otherwise - // In the function ComputeFaceExtensions, after the cells are extended, the - // corresponding entries in flag_ext_face are set to zero. This helps to keep - // track of which cells could not be extended - flag_ext_face(i, j, k) = int(S(i, j, k) < S_stab && S(i, j, k) > 0); - if(flag_ext_face(i, j, k)){ - flag_info_face(i, j, k) = 0; - } - // Is this face available to lend area to other faces? - // The criterion is that the face has to be interior and not already unstable itself - if(int(S(i, j, k) > 0 && !flag_ext_face(i, j, k))) { - flag_info_face(i, j, k) = 1; - } - }); - } - } -#endif -} -#endif - void WarpX::ComputeDistanceToEB () { diff --git a/Source/Evolve/WarpXComputeDt.cpp b/Source/Evolve/WarpXComputeDt.cpp index 615513c846f..d54e448b69e 100644 --- a/Source/Evolve/WarpXComputeDt.cpp +++ b/Source/Evolve/WarpXComputeDt.cpp @@ -49,7 +49,7 @@ WarpX::ComputeDt () WARPX_ALWAYS_ASSERT_WITH_MESSAGE(m_const_dt.has_value(), "warpx.const_dt must be specified with the hybrid-PIC solver."); } else if (electromagnetic_solver_id == ElectromagneticSolverAlgo::None) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( - m_const_dt.has_value() || dt_update_interval.isActivated(), + m_const_dt.has_value() || m_dt_update_interval.isActivated(), "warpx.const_dt must be specified with the electrostatic solver, or warpx.dt_update_interval must be > 0." ); } @@ -97,7 +97,7 @@ WarpX::ComputeDt () dt.resize(0); dt.resize(max_level+1,deltat); - if (do_subcycling) { + if (m_do_subcycling) { for (int lev = max_level-1; lev >= 0; --lev) { dt[lev] = dt[lev+1] * refRatio(lev)[0]; } @@ -137,22 +137,3 @@ WarpX::UpdateDtFromParticleSpeeds () dt[lev] = dt[lev+1] * refRatio(lev)[0]; } } - -void -WarpX::PrintDtDxDyDz () -{ - for (int lev=0; lev <= max_level; lev++) { - const amrex::Real* dx_lev = geom[lev].CellSize(); - amrex::Print() << "Level " << lev << ": dt = " << dt[lev] -#if defined(WARPX_DIM_1D_Z) - << " ; dz = " << dx_lev[0] << '\n'; -#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - << " ; dx = " << dx_lev[0] - << " ; dz = " << dx_lev[1] << '\n'; -#elif defined(WARPX_DIM_3D) - << " ; dx = " << dx_lev[0] - << " ; dy = " << dx_lev[1] - << " ; dz = " << dx_lev[2] << '\n'; -#endif - } -} diff --git a/Source/Evolve/WarpXEvolve.cpp b/Source/Evolve/WarpXEvolve.cpp index a685afd28e7..5593642a944 100644 --- a/Source/Evolve/WarpXEvolve.cpp +++ b/Source/Evolve/WarpXEvolve.cpp @@ -61,6 +61,23 @@ using namespace amrex; using ablastr::utils::SignalHandling; +namespace +{ + /** Print Unused Parameter Warnings after Step 1 + * + * Instead of waiting for a simulation to end, we already do an early "unused parameter check" + * after step 1 to inform users early of potential issues with their simulation setup. + */ + void checkEarlyUnusedParams () + { + amrex::Print() << "\n"; // better: conditional \n based on return value + amrex::ParmParse::QueryUnusedInputs(); + + // Print the warning list right after the first step. + amrex::Print() << ablastr::warn_manager::GetWMInstance().PrintGlobalWarnings("FIRST STEP"); + } +} + void WarpX::Synchronize () { using ablastr::fields::Direction; @@ -130,7 +147,7 @@ WarpX::Evolve (int numsteps) // Update timestep for electrostatic solver if a constant dt is not provided // This first synchronizes the position and velocity before setting the new timestep if (electromagnetic_solver_id == ElectromagneticSolverAlgo::None && - !m_const_dt.has_value() && dt_update_interval.contains(step+1)) { + !m_const_dt.has_value() && m_dt_update_interval.contains(step+1)) { if (verbose) { amrex::Print() << Utils::TextMsg::Info("updating timestep"); } @@ -187,7 +204,7 @@ WarpX::Evolve (int numsteps) OneStep_multiJ(cur_time); } // Electromagnetic case: no subcycling or no mesh refinement - else if ( !do_subcycling || (finest_level == 0)) + else if ( !m_do_subcycling || (finest_level == 0)) { OneStep_nosub(cur_time); // E: guard cells are up-to-date @@ -195,14 +212,14 @@ WarpX::Evolve (int numsteps) // F: guard cells are NOT up-to-date } // Electromagnetic case: subcycling with one level of mesh refinement - else if (do_subcycling && (finest_level == 1)) + else if (m_do_subcycling && (finest_level == 1)) { OneStep_sub1(cur_time); } else { WARPX_ABORT_WITH_MESSAGE( - "do_subcycling = " + std::to_string(do_subcycling) + "do_subcycling = " + std::to_string(m_do_subcycling) + " is an unsupported do_subcycling type."); } @@ -310,7 +327,7 @@ WarpX::Evolve (int numsteps) // inputs: unused parameters (e.g. typos) check after step 1 has finished if (!early_params_checked) { - checkEarlyUnusedParams(); + ::checkEarlyUnusedParams(); early_params_checked = true; } @@ -390,7 +407,7 @@ WarpX::OneStep_nosub (Real cur_time) WarpX::Hybrid_QED_Push(dt); FillBoundaryE(guard_cells.ng_alloc_EB); } - PushPSATD(); + PushPSATD(cur_time); if (do_pml) { DampPML(); @@ -418,15 +435,15 @@ WarpX::OneStep_nosub (Real cur_time) FillBoundaryF(guard_cells.ng_FieldSolverF); FillBoundaryG(guard_cells.ng_FieldSolverG); - EvolveB(0.5_rt * dt[0], DtType::FirstHalf); // We now have B^{n+1/2} + EvolveB(0.5_rt * dt[0], DtType::FirstHalf, cur_time); // We now have B^{n+1/2} FillBoundaryB(guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); - if (WarpX::em_solver_medium == MediumForEM::Vacuum) { + if (m_em_solver_medium == MediumForEM::Vacuum) { // vacuum medium - EvolveE(dt[0]); // We now have E^{n+1} - } else if (WarpX::em_solver_medium == MediumForEM::Macroscopic) { + EvolveE(dt[0], cur_time); // We now have E^{n+1} + } else if (m_em_solver_medium == MediumForEM::Macroscopic) { // macroscopic medium - MacroscopicEvolveE(dt[0]); // We now have E^{n+1} + MacroscopicEvolveE(dt[0], cur_time); // We now have E^{n+1} } else { WARPX_ABORT_WITH_MESSAGE("Medium for EM is unknown"); } @@ -434,7 +451,7 @@ WarpX::OneStep_nosub (Real cur_time) EvolveF(0.5_rt * dt[0], DtType::SecondHalf); EvolveG(0.5_rt * dt[0], DtType::SecondHalf); - EvolveB(0.5_rt * dt[0], DtType::SecondHalf); // We now have B^{n+1} + EvolveB(0.5_rt * dt[0], DtType::SecondHalf, cur_time + 0.5_rt * dt[0]); // We now have B^{n+1} if (do_pml) { DampPML(); @@ -446,7 +463,7 @@ WarpX::OneStep_nosub (Real cur_time) // E and B are up-to-date in the domain, but all guard cells are // outdated. - if (safe_guard_cells) { + if (m_safe_guard_cells) { FillBoundaryB(guard_cells.ng_alloc_EB); } } // !PSATD @@ -461,15 +478,6 @@ bool WarpX::checkStopSimulation (amrex::Real cur_time) m_exit_loop_due_to_interrupt_signal; } -void WarpX::checkEarlyUnusedParams () -{ - amrex::Print() << "\n"; // better: conditional \n based on return value - amrex::ParmParse::QueryUnusedInputs(); - - // Print the warning list right after the first step. - amrex::Print() << ablastr::warn_manager::GetWMInstance().PrintGlobalWarnings("FIRST STEP"); -} - void WarpX::ExplicitFillBoundaryEBUpdateAux () { WARPX_ALWAYS_ASSERT_WITH_MESSAGE(evolve_scheme == EvolveScheme::Explicit, @@ -616,7 +624,7 @@ void WarpX::SyncCurrentAndRho () // TODO This works only without mesh refinement const int lev = 0; if (use_filter) { - ApplyFilterJ(m_fields.get_mr_levels_alldirs(FieldType::current_fp_vay, finest_level), lev); + ApplyFilterMF(m_fields.get_mr_levels_alldirs(FieldType::current_fp_vay, finest_level), lev); } } } @@ -663,6 +671,8 @@ WarpX::OneStep_multiJ (const amrex::Real cur_time) using warpx::fields::FieldType; + bool const skip_lev0_coarse_patch = true; + const int rho_mid = spectral_solver_fp[0]->m_spectral_index.rho_mid; const int rho_new = spectral_solver_fp[0]->m_spectral_index.rho_new; @@ -796,8 +806,8 @@ WarpX::OneStep_multiJ (const amrex::Real cur_time) PSATDBackwardTransformEBavg( m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_fp, finest_level), m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level) + m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level, skip_lev0_coarse_patch), + m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level, skip_lev0_coarse_patch) ); } @@ -808,10 +818,10 @@ WarpX::OneStep_multiJ (const amrex::Real cur_time) { pml[lev]->PushPSATD(m_fields, lev); } - ApplyEfieldBoundary(lev, PatchType::fine); - if (lev > 0) { ApplyEfieldBoundary(lev, PatchType::coarse); } - ApplyBfieldBoundary(lev, PatchType::fine, DtType::FirstHalf); - if (lev > 0) { ApplyBfieldBoundary(lev, PatchType::coarse, DtType::FirstHalf); } + ApplyEfieldBoundary(lev, PatchType::fine, cur_time + dt[0]); + if (lev > 0) { ApplyEfieldBoundary(lev, PatchType::coarse, cur_time + dt[0]); } + ApplyBfieldBoundary(lev, PatchType::fine, DtType::FirstHalf, cur_time + dt[0]); + if (lev > 0) { ApplyBfieldBoundary(lev, PatchType::coarse, DtType::FirstHalf, cur_time + dt[0]); } } // Damp fields in PML before exchanging guard cells @@ -868,35 +878,40 @@ WarpX::OneStep_sub1 (Real cur_time) using warpx::fields::FieldType; + bool const skip_lev0_coarse_patch = true; + // i) Push particles and fields on the fine patch (first fine step) PushParticlesandDeposit(fine_lev, cur_time, DtType::FirstHalf); RestrictCurrentFromFineToCoarsePatch( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level), fine_lev); + m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch), fine_lev); RestrictRhoFromFineToCoarsePatch(fine_lev); if (use_filter) { - ApplyFilterJ( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev); + ApplyFilterMF( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev); } SumBoundaryJ( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev, Geom(fine_lev).periodicity()); - ApplyFilterandSumBoundaryRho( - m_fields.get_mr_levels(FieldType::rho_fp, finest_level), - m_fields.get_mr_levels(FieldType::rho_cp, finest_level), - fine_lev, PatchType::fine, 0, 2*ncomps); + if (m_fields.has(FieldType::rho_fp, finest_level) && + m_fields.has(FieldType::rho_cp, finest_level)) { + ApplyFilterandSumBoundaryRho( + m_fields.get_mr_levels(FieldType::rho_fp, finest_level), + m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch), + fine_lev, PatchType::fine, 0, 2*ncomps); + } - EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf); + EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf, cur_time); EvolveF(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf); FillBoundaryB(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); FillBoundaryF(fine_lev, PatchType::fine, guard_cells.ng_alloc_F, WarpX::sync_nodal_points); - EvolveE(fine_lev, PatchType::fine, dt[fine_lev]); + EvolveE(fine_lev, PatchType::fine, dt[fine_lev], cur_time); FillBoundaryE(fine_lev, PatchType::fine, guard_cells.ng_FieldGather); - EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf); + EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf, cur_time + 0.5_rt * dt[fine_lev]); EvolveF(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf); if (do_pml) { @@ -914,30 +929,35 @@ WarpX::OneStep_sub1 (Real cur_time) StoreCurrent(coarse_lev); AddCurrentFromFineLevelandSumBoundary( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level), coarse_lev); - AddRhoFromFineLevelandSumBoundary( - m_fields.get_mr_levels(FieldType::rho_fp, finest_level), - m_fields.get_mr_levels(FieldType::rho_cp, finest_level), - m_fields.get_mr_levels(FieldType::rho_buf, finest_level), - coarse_lev, 0, ncomps); - - EvolveB(fine_lev, PatchType::coarse, dt[fine_lev], DtType::FirstHalf); + m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch), + m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level, skip_lev0_coarse_patch), coarse_lev); + + if (m_fields.has(FieldType::rho_fp, finest_level) && + m_fields.has(FieldType::rho_cp, finest_level) && + m_fields.has(FieldType::rho_buf, finest_level)) { + AddRhoFromFineLevelandSumBoundary( + m_fields.get_mr_levels(FieldType::rho_fp, finest_level), + m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch), + m_fields.get_mr_levels(FieldType::rho_buf, finest_level, skip_lev0_coarse_patch), + coarse_lev, 0, ncomps); + } + + EvolveB(fine_lev, PatchType::coarse, dt[fine_lev], DtType::FirstHalf, cur_time); EvolveF(fine_lev, PatchType::coarse, dt[fine_lev], DtType::FirstHalf); FillBoundaryB(fine_lev, PatchType::coarse, guard_cells.ng_FieldGather); FillBoundaryF(fine_lev, PatchType::coarse, guard_cells.ng_FieldSolverF); - EvolveE(fine_lev, PatchType::coarse, dt[fine_lev]); + EvolveE(fine_lev, PatchType::coarse, dt[fine_lev], cur_time); FillBoundaryE(fine_lev, PatchType::coarse, guard_cells.ng_FieldGather); - EvolveB(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::FirstHalf); + EvolveB(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::FirstHalf, cur_time); EvolveF(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::FirstHalf); FillBoundaryB(coarse_lev, PatchType::fine, guard_cells.ng_FieldGather, WarpX::sync_nodal_points); FillBoundaryF(coarse_lev, PatchType::fine, guard_cells.ng_FieldSolverF, WarpX::sync_nodal_points); - EvolveE(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev]); + EvolveE(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], cur_time); FillBoundaryE(coarse_lev, PatchType::fine, guard_cells.ng_FieldGather); // TODO Remove call to FillBoundaryAux before UpdateAuxilaryData? @@ -950,27 +970,31 @@ WarpX::OneStep_sub1 (Real cur_time) PushParticlesandDeposit(fine_lev, cur_time + dt[fine_lev], DtType::SecondHalf); RestrictCurrentFromFineToCoarsePatch( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level), fine_lev); + m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch), fine_lev); RestrictRhoFromFineToCoarsePatch(fine_lev); if (use_filter) { - ApplyFilterJ( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev); + ApplyFilterMF( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev); } SumBoundaryJ( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), fine_lev, Geom(fine_lev).periodicity()); - ApplyFilterandSumBoundaryRho( - m_fields.get_mr_levels(FieldType::rho_fp, finest_level), - m_fields.get_mr_levels(FieldType::rho_cp, finest_level), - fine_lev, PatchType::fine, 0, ncomps); - EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf); + if (m_fields.has(FieldType::rho_fp, finest_level) && + m_fields.has(FieldType::rho_cp, finest_level)) { + ApplyFilterandSumBoundaryRho( + m_fields.get_mr_levels(FieldType::rho_fp, finest_level), + m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch), + fine_lev, PatchType::fine, 0, ncomps); + } + + EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf, cur_time + dt[fine_lev]); EvolveF(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::FirstHalf); FillBoundaryB(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver); FillBoundaryF(fine_lev, PatchType::fine, guard_cells.ng_FieldSolverF); - EvolveE(fine_lev, PatchType::fine, dt[fine_lev]); + EvolveE(fine_lev, PatchType::fine, dt[fine_lev], cur_time + dt[fine_lev]); FillBoundaryE(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); - EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf); + EvolveB(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf, cur_time + 1.5_rt*dt[fine_lev]); EvolveF(fine_lev, PatchType::fine, 0.5_rt*dt[fine_lev], DtType::SecondHalf); if (do_pml) { @@ -978,7 +1002,7 @@ WarpX::OneStep_sub1 (Real cur_time) FillBoundaryE(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver); } - if ( safe_guard_cells ) { + if ( m_safe_guard_cells ) { FillBoundaryF(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver); } FillBoundaryB(fine_lev, PatchType::fine, guard_cells.ng_FieldSolver); @@ -988,20 +1012,25 @@ WarpX::OneStep_sub1 (Real cur_time) RestoreCurrent(coarse_lev); AddCurrentFromFineLevelandSumBoundary( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level), + m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch), + m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level, skip_lev0_coarse_patch), coarse_lev); - AddRhoFromFineLevelandSumBoundary( - m_fields.get_mr_levels(FieldType::rho_fp, finest_level), - m_fields.get_mr_levels(FieldType::rho_cp, finest_level), - m_fields.get_mr_levels(FieldType::rho_buf, finest_level), - coarse_lev, ncomps, ncomps); - EvolveE(fine_lev, PatchType::coarse, dt[fine_lev]); + if (m_fields.has(FieldType::rho_fp, finest_level) && + m_fields.has(FieldType::rho_cp, finest_level) && + m_fields.has(FieldType::rho_buf, finest_level)) { + AddRhoFromFineLevelandSumBoundary( + m_fields.get_mr_levels(FieldType::rho_fp, finest_level), + m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch), + m_fields.get_mr_levels(FieldType::rho_buf, finest_level, skip_lev0_coarse_patch), + coarse_lev, ncomps, ncomps); + } + + EvolveE(fine_lev, PatchType::coarse, dt[fine_lev], cur_time + 0.5_rt * dt[fine_lev]); FillBoundaryE(fine_lev, PatchType::coarse, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); - EvolveB(fine_lev, PatchType::coarse, dt[fine_lev], DtType::SecondHalf); + EvolveB(fine_lev, PatchType::coarse, dt[fine_lev], DtType::SecondHalf, cur_time + 0.5_rt * dt[fine_lev]); EvolveF(fine_lev, PatchType::coarse, dt[fine_lev], DtType::SecondHalf); if (do_pml) { @@ -1016,11 +1045,11 @@ WarpX::OneStep_sub1 (Real cur_time) FillBoundaryF(fine_lev, PatchType::coarse, guard_cells.ng_FieldSolverF, WarpX::sync_nodal_points); - EvolveE(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev]); + EvolveE(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], cur_time + 0.5_rt*dt[coarse_lev]); FillBoundaryE(coarse_lev, PatchType::fine, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); - EvolveB(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::SecondHalf); + EvolveB(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::SecondHalf, cur_time + 0.5_rt*dt[coarse_lev]); EvolveF(coarse_lev, PatchType::fine, 0.5_rt*dt[coarse_lev], DtType::SecondHalf); if (do_pml) { @@ -1034,12 +1063,12 @@ WarpX::OneStep_sub1 (Real cur_time) WarpX::sync_nodal_points); } DampPML(coarse_lev, PatchType::fine); - if ( safe_guard_cells ) { + if ( m_safe_guard_cells ) { FillBoundaryE(coarse_lev, PatchType::fine, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); } } - if ( safe_guard_cells ) { + if ( m_safe_guard_cells ) { FillBoundaryB(coarse_lev, PatchType::fine, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); } @@ -1047,53 +1076,41 @@ WarpX::OneStep_sub1 (Real cur_time) void WarpX::doFieldIonization () -{ - for (int lev = 0; lev <= finest_level; ++lev) { - doFieldIonization(lev); - } -} - -void -WarpX::doFieldIonization (int lev) { using ablastr::fields::Direction; using warpx::fields::FieldType; - mypc->doFieldIonization( - lev, - *m_fields.get(FieldType::Efield_aux, Direction{0}, lev), - *m_fields.get(FieldType::Efield_aux, Direction{1}, lev), - *m_fields.get(FieldType::Efield_aux, Direction{2}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{2}, lev) - ); -} - -#ifdef WARPX_QED -void -WarpX::doQEDEvents () -{ for (int lev = 0; lev <= finest_level; ++lev) { - doQEDEvents(lev); + mypc->doFieldIonization( + lev, + *m_fields.get(FieldType::Efield_aux, Direction{0}, lev), + *m_fields.get(FieldType::Efield_aux, Direction{1}, lev), + *m_fields.get(FieldType::Efield_aux, Direction{2}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{2}, lev) + ); } } +#ifdef WARPX_QED void -WarpX::doQEDEvents (int lev) +WarpX::doQEDEvents () { using ablastr::fields::Direction; using warpx::fields::FieldType; - mypc->doQedEvents( - lev, - *m_fields.get(FieldType::Efield_aux, Direction{0}, lev), - *m_fields.get(FieldType::Efield_aux, Direction{1}, lev), - *m_fields.get(FieldType::Efield_aux, Direction{2}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), - *m_fields.get(FieldType::Bfield_aux, Direction{2}, lev) - ); + for (int lev = 0; lev <= finest_level; ++lev) { + mypc->doQedEvents( + lev, + *m_fields.get(FieldType::Efield_aux, Direction{0}, lev), + *m_fields.get(FieldType::Efield_aux, Direction{1}, lev), + *m_fields.get(FieldType::Efield_aux, Direction{2}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{0}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{1}, lev), + *m_fields.get(FieldType::Bfield_aux, Direction{2}, lev) + ); + } } #endif @@ -1190,16 +1207,16 @@ WarpX::applyMirrors (Real time) using ablastr::fields::Direction; // something to do? - if (num_mirrors == 0) { + if (m_num_mirrors == 0) { return; } // Loop over the mirrors - for(int i_mirror=0; i_mirror1) @@ -1211,9 +1228,9 @@ WarpX::applyMirrors (Real time) // Loop over levels for(int lev=0; lev<=finest_level; lev++) { - // Mirror must contain at least mirror_z_npoints[i_mirror] cells + // Mirror must contain at least m_mirror_z_npoints[i_mirror] cells const amrex::Real dz = WarpX::CellSize(lev)[2]; - const amrex::Real z_max = std::max(z_max_tmp, z_min+mirror_z_npoints[i_mirror]*dz); + const amrex::Real z_max = std::max(z_max_tmp, z_min+m_mirror_z_npoints[i_mirror]*dz); // Set each field on the fine patch to zero between z_min and z_max NullifyMF(m_fields, "Efield_fp", Direction{0}, lev, z_min, z_max); diff --git a/Source/FieldSolver/ElectrostaticSolvers/CMakeLists.txt b/Source/FieldSolver/ElectrostaticSolvers/CMakeLists.txt index 39c4478c110..db728f6aaba 100644 --- a/Source/FieldSolver/ElectrostaticSolvers/CMakeLists.txt +++ b/Source/FieldSolver/ElectrostaticSolvers/CMakeLists.txt @@ -2,6 +2,7 @@ foreach(D IN LISTS WarpX_DIMS) warpx_set_suffix_dims(SD ${D}) target_sources(lib_${SD} PRIVATE + EffectivePotentialES.cpp ElectrostaticSolver.cpp LabFrameExplicitES.cpp PoissonBoundaryHandler.cpp diff --git a/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.H b/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.H new file mode 100644 index 00000000000..2ade923211c --- /dev/null +++ b/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.H @@ -0,0 +1,71 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: Roelof Groenewald (TAE Technologies) + * + * License: BSD-3-Clause-LBNL + */ + +#ifndef WARPX_EFFECTIVEPOTENTIALES_H_ +#define WARPX_EFFECTIVEPOTENTIALES_H_ + +#include "ElectrostaticSolver.H" + +#include +#include + +class EffectivePotentialES final : public ElectrostaticSolver +{ +public: + + EffectivePotentialES (int nlevs_max) : ElectrostaticSolver (nlevs_max) { + ReadParameters(); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + (nlevs_max == 1), + "Effective potential electrostatic solver only supports one level at present" + ); + } + + void InitData () override; + + void ComputeSpaceChargeField ( + ablastr::fields::MultiFabRegister& fields, + MultiParticleContainer& mpc, + MultiFluidContainer* mfl, + int max_level) override; + + void ComputeSigma ( amrex::MultiFab& sigma ) const; + + /** + * Compute the potential `phi` by solving the semi-implicit Poisson equation using the Effective Potential method + * with `rho` as the source. + * More specifically, this solves the equation + * \f[ + * \vec{\nabla}\cdot(\sigma\vec{\nabla}) \phi = -\frac{\rho}{\epsilon_0} + * \f] + * \param[out] phi The potential to be computed by this function + * \param[in] rho The total charge density + * \param[in] sigma Represents the modified dielectric + * \param[in] required_precision The relative convergence threshold for the MLMG solver + * \param[in] absolute_tolerance The absolute convergence threshold for the MLMG solver + * \param[in] max_iters The maximum number of iterations allowed for the MLMG solver + * \param[in] verbosity The verbosity setting for the MLMG solver + */ + void computePhi ( + ablastr::fields::MultiLevelScalarField const& rho, + ablastr::fields::MultiLevelScalarField const& phi + ) const; + void computePhi ( + ablastr::fields::MultiLevelScalarField const& rho, + ablastr::fields::MultiLevelScalarField const& phi, + amrex::MultiFab const& sigma, + amrex::Real required_precision, + amrex::Real absolute_tolerance, + int max_iters, + int verbosity + ) const; + +}; + +#endif // WARPX_EFFECTIVEPOTENTIALES_H_ diff --git a/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.cpp b/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.cpp new file mode 100644 index 00000000000..b2f93f7e2b3 --- /dev/null +++ b/Source/FieldSolver/ElectrostaticSolvers/EffectivePotentialES.cpp @@ -0,0 +1,260 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: Roelof Groenewald (TAE Technologies) + * + * License: BSD-3-Clause-LBNL + */ + +#include "EffectivePotentialES.H" +#include "Fluids/MultiFluidContainer_fwd.H" +#include "EmbeddedBoundary/Enabled.H" +#include "Fields.H" +#include "Particles/MultiParticleContainer_fwd.H" +#include "Utils/Parser/ParserUtils.H" +#include "WarpX.H" + +using namespace amrex; + +void EffectivePotentialES::InitData() { + auto & warpx = WarpX::GetInstance(); + m_poisson_boundary_handler->DefinePhiBCs(warpx.Geom(0)); +} + +void EffectivePotentialES::ComputeSpaceChargeField ( + ablastr::fields::MultiFabRegister& fields, + MultiParticleContainer& mpc, + [[maybe_unused]] MultiFluidContainer* mfl, + int max_level) +{ + WARPX_PROFILE("EffectivePotentialES::ComputeSpaceChargeField"); + + using ablastr::fields::MultiLevelScalarField; + using ablastr::fields::MultiLevelVectorField; + using warpx::fields::FieldType; + + bool const skip_lev0_coarse_patch = true; + + // grab the simulation fields + const MultiLevelScalarField rho_fp = fields.get_mr_levels(FieldType::rho_fp, max_level); + const MultiLevelScalarField rho_cp = fields.get_mr_levels(FieldType::rho_cp, max_level, skip_lev0_coarse_patch); + const MultiLevelScalarField phi_fp = fields.get_mr_levels(FieldType::phi_fp, max_level); + const MultiLevelVectorField Efield_fp = fields.get_mr_levels_alldirs(FieldType::Efield_fp, max_level); + + mpc.DepositCharge(rho_fp, 0.0_rt); + if (mfl) { + const int lev = 0; + mfl->DepositCharge(fields, *rho_fp[lev], lev); + } + + // Apply filter, perform MPI exchange, interpolate across levels + const Vector > rho_buf(num_levels); + auto & warpx = WarpX::GetInstance(); + warpx.SyncRho( rho_fp, rho_cp, amrex::GetVecOfPtrs(rho_buf) ); + +#ifndef WARPX_DIM_RZ + for (int lev = 0; lev < num_levels; lev++) { + // Reflect density over PEC boundaries, if needed. + warpx.ApplyRhofieldBoundary(lev, rho_fp[lev], PatchType::fine); + } +#endif + + // set the boundary potentials appropriately + setPhiBC(phi_fp, warpx.gett_new(0)); + + // perform phi calculation + computePhi(rho_fp, phi_fp); + + // Compute the electric field. Note that if an EB is used the electric + // field will be calculated in the computePhi call. + const std::array beta = {0._rt}; + if (!EB::enabled()) { computeE( Efield_fp, phi_fp, beta ); } +} + +void EffectivePotentialES::computePhi ( + ablastr::fields::MultiLevelScalarField const& rho, + ablastr::fields::MultiLevelScalarField const& phi) const +{ + // Calculate the mass enhancement factor - see Appendix A of + // Barnes, Journal of Comp. Phys., 424 (2021), 109852. + // The "sigma" multifab stores the dressing of the Poisson equation. It + // is a cell-centered multifab. + auto const& ba = convert(rho[0]->boxArray(), IntVect(AMREX_D_DECL(0,0,0))); + MultiFab sigma(ba, rho[0]->DistributionMap(), 1, rho[0]->nGrowVect()); + ComputeSigma(sigma); + + // Use the AMREX MLMG solver + computePhi(rho, phi, sigma, self_fields_required_precision, + self_fields_absolute_tolerance, self_fields_max_iters, + self_fields_verbosity); +} + +void EffectivePotentialES::ComputeSigma (MultiFab& sigma) const +{ + // Reset sigma to 1 + sigma.setVal(1.0_rt); + + // Get the user set value for C_SI (defaults to 4) + amrex::Real C_SI = 4.0; + const ParmParse pp_warpx("warpx"); + utils::parser::queryWithParser(pp_warpx, "effective_potential_factor", C_SI); + + int const lev = 0; + + // sigma is a cell-centered array + amrex::GpuArray const cell_centered = {0, 0, 0}; + // The "coarsening is just 1 i.e. no coarsening" + amrex::GpuArray const coarsen = {1, 1, 1}; + + // GetChargeDensity returns a nodal multifab + // Below we set all the unused dimensions to have cell-centered values for + // rho since these values will be interpolated onto a cell-centered grid + // - if this is not done the Interp function returns nonsense values. +#if defined(WARPX_DIM_3D) + amrex::GpuArray const nodal = {1, 1, 1}; +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + amrex::GpuArray const nodal = {1, 1, 0}; +#elif defined(WARPX_DIM_1D_Z) + amrex::GpuArray const nodal = {1, 0, 0}; +#endif + + auto& warpx = WarpX::GetInstance(); + auto& mypc = warpx.GetPartContainer(); + + // The effective potential dielectric function is given by + // \varepsilon_{SI} = \varepsilon * (1 + \sum_{i in species} C_{SI}*(w_pi * dt)^2/4) + // Note the use of the plasma frequency in rad/s (not Hz) and the factor of 1/4, + // these choices make it so that C_SI = 1 is the marginal stability threshold. + auto mult_factor = ( + C_SI * warpx.getdt(lev) * warpx.getdt(lev) / (4._rt * PhysConst::ep0) + ); + + // Loop over each species to calculate the Poisson equation dressing + for (auto const& pc : mypc) { + // grab the charge density for this species + auto rho = pc->GetChargeDensity(lev, false); + + // Handle the parallel transfer of guard cells and apply filtering + warpx.ApplyFilterandSumBoundaryRho(lev, lev, *rho, 0, rho->nComp()); + + // get multiplication factor for this species + auto const mult_factor_pc = mult_factor * pc->getCharge() / pc->getMass(); + + // update sigma +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( MFIter mfi(sigma, TilingIfNotGPU()); mfi.isValid(); ++mfi ) { + Array4 const& sigma_arr = sigma.array(mfi); + Array4 const& rho_arr = rho->const_array(mfi); + + // Loop over the cells and update the sigma field + amrex::ParallelFor(mfi.tilebox(), [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Interpolate rho to cell-centered value + auto const rho_cc = ablastr::coarsen::sample::Interp( + rho_arr, nodal, cell_centered, coarsen, i, j, k, 0 + ); + // add species term to sigma: + // C_SI * w_p^2 * dt^2 / 4 = C_SI / 4 * q*rho/(m*eps0) * dt^2 + sigma_arr(i, j, k, 0) += mult_factor_pc * rho_cc; + }); + + } + } +} + + +void EffectivePotentialES::computePhi ( + ablastr::fields::MultiLevelScalarField const& rho, + ablastr::fields::MultiLevelScalarField const& phi, + amrex::MultiFab const& sigma, + amrex::Real required_precision, + amrex::Real absolute_tolerance, + int max_iters, + int verbosity +) const +{ + using ablastr::fields::Direction; + using warpx::fields::FieldType; + + // create a vector to our fields, sorted by level + amrex::Vector sorted_rho; + amrex::Vector sorted_phi; + for (int lev = 0; lev < num_levels; ++lev) { + sorted_rho.emplace_back(rho[lev]); + sorted_phi.emplace_back(phi[lev]); + } + + std::optional post_phi_calculation; +#ifdef AMREX_USE_EB + // TODO: double check no overhead occurs on "m_eb_enabled == false" + std::optional > eb_farray_box_factory; +#else + std::optional > const eb_farray_box_factory; +#endif + auto & warpx = WarpX::GetInstance(); + if (EB::enabled()) + { + // EB: use AMReX to directly calculate the electric field since with EB's the + // simple finite difference scheme in WarpX::computeE sometimes fails + + // TODO: maybe make this a helper function or pass Efield_fp directly + amrex::Vector< + amrex::Array + > e_field; + for (int lev = 0; lev < num_levels; ++lev) { + e_field.push_back( +#if defined(WARPX_DIM_1D_Z) + amrex::Array{ + warpx.m_fields.get(FieldType::Efield_fp, Direction{2}, lev) + } +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + amrex::Array{ + warpx.m_fields.get(FieldType::Efield_fp, Direction{0}, lev), + warpx.m_fields.get(FieldType::Efield_fp, Direction{2}, lev) + } +#elif defined(WARPX_DIM_3D) + amrex::Array{ + warpx.m_fields.get(FieldType::Efield_fp, Direction{0}, lev), + warpx.m_fields.get(FieldType::Efield_fp, Direction{1}, lev), + warpx.m_fields.get(FieldType::Efield_fp, Direction{2}, lev) + } +#endif + ); + } + post_phi_calculation = EBCalcEfromPhiPerLevel(e_field); + +#ifdef AMREX_USE_EB + amrex::Vector< + amrex::EBFArrayBoxFactory const * + > factories; + for (int lev = 0; lev < num_levels; ++lev) { + factories.push_back(&warpx.fieldEBFactory(lev)); + } + eb_farray_box_factory = factories; +#endif + } + + ablastr::fields::computeEffectivePotentialPhi( + sorted_rho, + sorted_phi, + sigma, + required_precision, + absolute_tolerance, + max_iters, + verbosity, + warpx.Geom(), + warpx.DistributionMap(), + warpx.boxArray(), + WarpX::grid_type, + false, + EB::enabled(), + WarpX::do_single_precision_comms, + warpx.refRatio(), + post_phi_calculation, + *m_poisson_boundary_handler, + warpx.gett_new(0), + eb_farray_box_factory + ); +} diff --git a/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H b/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H old mode 100644 new mode 100755 index e58af394a7a..0a0b0e2be48 --- a/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H +++ b/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H @@ -76,14 +76,15 @@ public: * \f[ * \vec{\nabla}^2 r \phi - (\vec{\beta}\cdot\vec{\nabla})^2 r \phi = -\frac{r \rho}{\epsilon_0} * \f] - * \param[out] phi The potential to be computed by this function * \param[in] rho The charge density for a given species (relativistic solver) * or total charge density (labframe solver) + * \param[out] phi The potential to be computed by this function * \param[in] beta Represents the velocity of the source of `phi` * \param[in] required_precision The relative convergence threshold for the MLMG solver * \param[in] absolute_tolerance The absolute convergence threshold for the MLMG solver * \param[in] max_iters The maximum number of iterations allowed for the MLMG solver * \param[in] verbosity The verbosity setting for the MLMG solver + * \param[in] is_igf_2d_slices boolean to select between fully 3D Poisson solver and quasi-3D, i.e. one 2D Poisson solve on every z slice (default: false) */ void computePhi ( ablastr::fields::MultiLevelScalarField const& rho, @@ -92,7 +93,8 @@ public: amrex::Real required_precision, amrex::Real absolute_tolerance, int max_iters, - int verbosity + int verbosity, + bool is_igf_2d_slices ) const; /** @@ -153,6 +155,10 @@ public: * 2 : convergence progress at every MLMG iteration */ int self_fields_verbosity = 2; + + /** Parameters for FFT Poisson solver aka IGF */ + // 0: full 3D, 1: many 2D z-slices (quasi-3D) + bool is_igf_2d_slices = false; }; #endif // WARPX_ELECTROSTATICSOLVER_H_ diff --git a/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.cpp b/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.cpp old mode 100644 new mode 100755 index 0b1dca675be..429e007b4d0 --- a/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.cpp +++ b/Source/FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.cpp @@ -38,7 +38,12 @@ void ElectrostaticSolver::ReadParameters () { pp_warpx, "self_fields_absolute_tolerance", self_fields_absolute_tolerance); utils::parser::queryWithParser( pp_warpx, "self_fields_max_iters", self_fields_max_iters); - pp_warpx.query("self_fields_verbosity", self_fields_verbosity); + utils::parser::queryWithParser( + pp_warpx, "self_fields_verbosity", self_fields_verbosity); + + // FFT solver flags + utils::parser::queryWithParser( + pp_warpx, "use_2d_slices_fft_solver", is_igf_2d_slices); } void @@ -121,7 +126,9 @@ ElectrostaticSolver::computePhi ( Real const required_precision, Real absolute_tolerance, int const max_iters, - int const verbosity) const + int const verbosity, + bool const is_igf_2d +) const { using ablastr::fields::Direction; @@ -202,6 +209,7 @@ ElectrostaticSolver::computePhi ( warpx.boxArray(), WarpX::grid_type, is_solver_igf_on_lev0, + is_igf_2d, EB::enabled(), WarpX::do_single_precision_comms, warpx.refRatio(), diff --git a/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.H b/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.H old mode 100644 new mode 100755 diff --git a/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.cpp b/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.cpp old mode 100644 new mode 100755 index e973ae66975..88a0899a7cb --- a/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.cpp +++ b/Source/FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.cpp @@ -31,8 +31,10 @@ void LabFrameExplicitES::ComputeSpaceChargeField ( using ablastr::fields::MultiLevelVectorField; using warpx::fields::FieldType; + bool const skip_lev0_coarse_patch = true; + const MultiLevelScalarField rho_fp = fields.get_mr_levels(FieldType::rho_fp, max_level); - const MultiLevelScalarField rho_cp = fields.get_mr_levels(FieldType::rho_cp, max_level); + const MultiLevelScalarField rho_cp = fields.get_mr_levels(FieldType::rho_cp, max_level, skip_lev0_coarse_patch); const MultiLevelScalarField phi_fp = fields.get_mr_levels(FieldType::phi_fp, max_level); const MultiLevelVectorField Efield_fp = fields.get_mr_levels_alldirs(FieldType::Efield_fp, max_level); @@ -75,7 +77,7 @@ void LabFrameExplicitES::ComputeSpaceChargeField ( // Use the AMREX MLMG or the FFT (IGF) solver otherwise computePhi(rho_fp, phi_fp, beta, self_fields_required_precision, self_fields_absolute_tolerance, self_fields_max_iters, - self_fields_verbosity); + self_fields_verbosity, is_igf_2d_slices); #endif } diff --git a/Source/FieldSolver/ElectrostaticSolvers/Make.package b/Source/FieldSolver/ElectrostaticSolvers/Make.package index a1d2d78dbb0..673f1c8aa7a 100644 --- a/Source/FieldSolver/ElectrostaticSolvers/Make.package +++ b/Source/FieldSolver/ElectrostaticSolvers/Make.package @@ -1,6 +1,7 @@ CEXE_sources += PoissonBoundaryHandler.cpp CEXE_sources += LabFrameExplicitES.cpp CEXE_sources += RelativisticExplicitES.cpp +CEXE_sources += EffectivePotentialES.cpp CEXE_sources += ElectrostaticSolver.cpp VPATH_LOCATIONS += $(WARPX_HOME)/Source/FieldSolver/ElectrostaticSolvers diff --git a/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.H b/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.H old mode 100644 new mode 100755 diff --git a/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.cpp b/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.cpp old mode 100644 new mode 100755 index 69647da1702..0b1bcecd1e5 --- a/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.cpp +++ b/Source/FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.cpp @@ -130,7 +130,7 @@ void RelativisticExplicitES::AddSpaceChargeField ( computePhi( amrex::GetVecOfPtrs(rho), amrex::GetVecOfPtrs(phi), beta, pc.self_fields_required_precision, pc.self_fields_absolute_tolerance, pc.self_fields_max_iters, - pc.self_fields_verbosity ); + pc.self_fields_verbosity, is_igf_2d_slices); // Compute the corresponding electric and magnetic field, from the potential phi computeE( Efield_fp, amrex::GetVecOfPtrs(phi), beta ); @@ -168,7 +168,7 @@ void RelativisticExplicitES::AddBoundaryField (ablastr::fields::MultiLevelVector computePhi( amrex::GetVecOfPtrs(rho), amrex::GetVecOfPtrs(phi), beta, self_fields_required_precision, self_fields_absolute_tolerance, self_fields_max_iters, - self_fields_verbosity ); + self_fields_verbosity, is_igf_2d_slices); // Compute the corresponding electric field, from the potential phi. computeE( Efield_fp, amrex::GetVecOfPtrs(phi), beta ); diff --git a/Source/FieldSolver/FiniteDifferenceSolver/CMakeLists.txt b/Source/FieldSolver/FiniteDifferenceSolver/CMakeLists.txt index 19c2092d1a6..7539d706632 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/CMakeLists.txt +++ b/Source/FieldSolver/FiniteDifferenceSolver/CMakeLists.txt @@ -3,6 +3,7 @@ foreach(D IN LISTS WarpX_DIMS) target_sources(lib_${SD} PRIVATE ComputeDivE.cpp + ComputeCurlA.cpp EvolveB.cpp EvolveBPML.cpp EvolveE.cpp diff --git a/Source/FieldSolver/FiniteDifferenceSolver/ComputeCurlA.cpp b/Source/FieldSolver/FiniteDifferenceSolver/ComputeCurlA.cpp new file mode 100644 index 00000000000..30cbdb60508 --- /dev/null +++ b/Source/FieldSolver/FiniteDifferenceSolver/ComputeCurlA.cpp @@ -0,0 +1,306 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: S. Eric Clark (Helion Energy) + * + * License: BSD-3-Clause-LBNL + */ + +#include "FiniteDifferenceSolver.H" + +#include "EmbeddedBoundary/Enabled.H" +#ifdef WARPX_DIM_RZ +# include "FiniteDifferenceAlgorithms/CylindricalYeeAlgorithm.H" +#else +# include "FiniteDifferenceAlgorithms/CartesianYeeAlgorithm.H" +#endif + +#include "Utils/TextMsg.H" +#include "WarpX.H" + +using namespace amrex; + +void FiniteDifferenceSolver::ComputeCurlA ( + ablastr::fields::VectorField& Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, + int lev ) +{ + // Select algorithm (The choice of algorithm is a runtime option, + // but we compile code for each algorithm, using templates) + if (m_fdtd_algo == ElectromagneticSolverAlgo::HybridPIC) { +#ifdef WARPX_DIM_RZ + ComputeCurlACylindrical ( + Bfield, Afield, eb_update_B, lev + ); + +#else + ComputeCurlACartesian ( + Bfield, Afield, eb_update_B, lev + ); + +#endif + } else { + amrex::Abort(Utils::TextMsg::Err( + "ComputeCurl: Unknown algorithm choice.")); + } +} + +// /** +// * \brief Calculate B from the curl of A +// * i.e. B = curl(A) output field on B field mesh staggering +// * +// * \param[out] curlField output of curl operation +// * \param[in] field input staggered field, should be on E/J/A mesh staggering +// */ +#ifdef WARPX_DIM_RZ +template +void FiniteDifferenceSolver::ComputeCurlACylindrical ( + ablastr::fields::VectorField& Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, + int lev +) +{ + // for the profiler + amrex::LayoutData* cost = WarpX::getCosts(lev); + + // reset Bfield + Bfield[0]->setVal(0); + Bfield[1]->setVal(0); + Bfield[2]->setVal(0); + + // Loop through the grids, and over the tiles within each grid +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( MFIter mfi(*Afield[0], TilingIfNotGPU()); mfi.isValid(); ++mfi ) { + if (cost && WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) + { + amrex::Gpu::synchronize(); + } + Real wt = static_cast(amrex::second()); + + // Extract field data for this grid/tile + Array4 const& Ar = Afield[0]->const_array(mfi); + Array4 const& At = Afield[1]->const_array(mfi); + Array4 const& Az = Afield[2]->const_array(mfi); + Array4 const& Br = Bfield[0]->array(mfi); + Array4 const& Bt = Bfield[1]->array(mfi); + Array4 const& Bz = Bfield[2]->array(mfi); + + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries. + amrex::Array4 update_Br_arr, update_Bt_arr, update_Bz_arr; + if (EB::enabled()) { + update_Br_arr = eb_update_B[0]->array(mfi); + update_Bt_arr = eb_update_B[1]->array(mfi); + update_Bz_arr = eb_update_B[2]->array(mfi); + } + + // Extract stencil coefficients + Real const * const AMREX_RESTRICT coefs_r = m_stencil_coefs_r.dataPtr(); + int const n_coefs_r = static_cast(m_stencil_coefs_r.size()); + Real const * const AMREX_RESTRICT coefs_z = m_stencil_coefs_z.dataPtr(); + int const n_coefs_z = static_cast(m_stencil_coefs_z.size()); + + // Extract cylindrical specific parameters + Real const dr = m_dr; + int const nmodes = m_nmodes; + Real const rmin = m_rmin; + + // Extract tileboxes for which to loop over + Box const& tbr = mfi.tilebox(Bfield[0]->ixType().toIntVect()); + Box const& tbt = mfi.tilebox(Bfield[1]->ixType().toIntVect()); + Box const& tbz = mfi.tilebox(Bfield[2]->ixType().toIntVect()); + + // Calculate the B-field from the A-field + amrex::ParallelFor(tbr, tbt, tbz, + + // Br calculation + [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ + // Skip field update in the embedded boundaries + if (update_Br_arr && update_Br_arr(i, j, 0) == 0) { return; } + + Real const r = rmin + i*dr; // r on nodal point (Br is nodal in r) + if (r != 0) { // Off-axis, regular Maxwell equations + Br(i, j, 0, 0) = - T_Algo::UpwardDz(At, coefs_z, n_coefs_z, i, j, 0, 0); // Mode m=0 + for (int m=1; m(amrex::second()) - wt; + amrex::HostDevice::Atomic::Add( &(*cost)[mfi.index()], wt); + } + } +} + +#else + +template +void FiniteDifferenceSolver::ComputeCurlACartesian ( + ablastr::fields::VectorField & Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, + int lev +) +{ + using ablastr::fields::Direction; + + // for the profiler + amrex::LayoutData* cost = WarpX::getCosts(lev); + + // reset Bfield + Bfield[0]->setVal(0); + Bfield[1]->setVal(0); + Bfield[2]->setVal(0); + + // Loop through the grids, and over the tiles within each grid +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( MFIter mfi(*Afield[0], TilingIfNotGPU()); mfi.isValid(); ++mfi ) { + if (cost && WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) { + amrex::Gpu::synchronize(); + } + auto wt = static_cast(amrex::second()); + + // Extract field data for this grid/tile + Array4 const &Bx = Bfield[0]->array(mfi); + Array4 const &By = Bfield[1]->array(mfi); + Array4 const &Bz = Bfield[2]->array(mfi); + Array4 const &Ax = Afield[0]->const_array(mfi); + Array4 const &Ay = Afield[1]->const_array(mfi); + Array4 const &Az = Afield[2]->const_array(mfi); + + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries. + amrex::Array4 update_Bx_arr, update_By_arr, update_Bz_arr; + if (EB::enabled()) { + update_Bx_arr = eb_update_B[0]->array(mfi); + update_By_arr = eb_update_B[1]->array(mfi); + update_Bz_arr = eb_update_B[2]->array(mfi); + } + + // Extract stencil coefficients + Real const * const AMREX_RESTRICT coefs_x = m_stencil_coefs_x.dataPtr(); + auto const n_coefs_x = static_cast(m_stencil_coefs_x.size()); + Real const * const AMREX_RESTRICT coefs_y = m_stencil_coefs_y.dataPtr(); + auto const n_coefs_y = static_cast(m_stencil_coefs_y.size()); + Real const * const AMREX_RESTRICT coefs_z = m_stencil_coefs_z.dataPtr(); + auto const n_coefs_z = static_cast(m_stencil_coefs_z.size()); + + // Extract tileboxes for which to loop + Box const& tbx = mfi.tilebox(Bfield[0]->ixType().toIntVect()); + Box const& tby = mfi.tilebox(Bfield[1]->ixType().toIntVect()); + Box const& tbz = mfi.tilebox(Bfield[2]->ixType().toIntVect()); + + // Calculate the curl of A + amrex::ParallelFor(tbx, tby, tbz, + + // Bx calculation + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_Bx_arr && update_Bx_arr(i, j, k) == 0) { return; } + + Bx(i, j, k) = ( + - T_Algo::UpwardDz(Ay, coefs_z, n_coefs_z, i, j, k) + + T_Algo::UpwardDy(Az, coefs_y, n_coefs_y, i, j, k) + ); + }, + + // By calculation + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_By_arr && update_By_arr(i, j, k) == 0) { return; } + + By(i, j, k) = ( + - T_Algo::UpwardDx(Az, coefs_x, n_coefs_x, i, j, k) + + T_Algo::UpwardDz(Ax, coefs_z, n_coefs_z, i, j, k) + ); + }, + + // Bz calculation + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_Bz_arr && update_Bz_arr(i, j, k) == 0) { return; } + + Bz(i, j, k) = ( + - T_Algo::UpwardDy(Ax, coefs_y, n_coefs_y, i, j, k) + + T_Algo::UpwardDx(Ay, coefs_x, n_coefs_x, i, j, k) + ); + } + ); + + if (cost && WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) + { + amrex::Gpu::synchronize(); + wt = static_cast(amrex::second()) - wt; + amrex::HostDevice::Atomic::Add( &(*cost)[mfi.index()], wt); + } + } +} +#endif diff --git a/Source/FieldSolver/FiniteDifferenceSolver/EvolveE.cpp b/Source/FieldSolver/FiniteDifferenceSolver/EvolveE.cpp index fea7471bd25..5b1a88a9da0 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/EvolveE.cpp +++ b/Source/FieldSolver/FiniteDifferenceSolver/EvolveE.cpp @@ -56,6 +56,7 @@ void FiniteDifferenceSolver::EvolveE ( int lev, PatchType patch_type, ablastr::fields::VectorField const& Efield, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real const dt ) { @@ -73,40 +74,23 @@ void FiniteDifferenceSolver::EvolveE ( fields.get(FieldType::F_fp, lev) : fields.get(FieldType::F_cp, lev); } - ablastr::fields::VectorField edge_lengths; - if (fields.has_vector(FieldType::edge_lengths, lev)) { - edge_lengths = fields.get_alldirs(FieldType::edge_lengths, lev); - } - ablastr::fields::VectorField face_areas; - if (fields.has_vector(FieldType::face_areas, lev)) { - face_areas = fields.get_alldirs(FieldType::face_areas, lev); - } - ablastr::fields::VectorField area_mod; - if (fields.has_vector(FieldType::area_mod, lev)) { - area_mod = fields.get_alldirs(FieldType::area_mod, lev); - } - ablastr::fields::VectorField ECTRhofield; - if (fields.has_vector(FieldType::ECTRhofield, lev)) { - ECTRhofield = fields.get_alldirs(FieldType::ECTRhofield, lev); - } - // Select algorithm (The choice of algorithm is a runtime option, // but we compile code for each algorithm, using templates) #ifdef WARPX_DIM_RZ if (m_fdtd_algo == ElectromagneticSolverAlgo::Yee){ - EvolveECylindrical ( Efield, Bfield, Jfield, edge_lengths, Ffield, lev, dt ); + EvolveECylindrical ( Efield, Bfield, Jfield, eb_update_E, Ffield, lev, dt ); #else if (m_grid_type == GridType::Collocated) { - EvolveECartesian ( Efield, Bfield, Jfield, edge_lengths, Ffield, lev, dt ); + EvolveECartesian ( Efield, Bfield, Jfield, eb_update_E, Ffield, lev, dt ); } else if (m_fdtd_algo == ElectromagneticSolverAlgo::Yee || m_fdtd_algo == ElectromagneticSolverAlgo::ECT) { - EvolveECartesian ( Efield, Bfield, Jfield, edge_lengths, Ffield, lev, dt ); + EvolveECartesian ( Efield, Bfield, Jfield, eb_update_E, Ffield, lev, dt ); } else if (m_fdtd_algo == ElectromagneticSolverAlgo::CKC) { - EvolveECartesian ( Efield, Bfield, Jfield, edge_lengths, Ffield, lev, dt ); + EvolveECartesian ( Efield, Bfield, Jfield, eb_update_E, Ffield, lev, dt ); } else if (m_fdtd_algo == ElectromagneticSolverAlgo::CustomCoef) { @@ -127,14 +111,10 @@ void FiniteDifferenceSolver::EvolveECartesian ( ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, amrex::MultiFab const* Ffield, int lev, amrex::Real const dt ) { -#ifndef AMREX_USE_EB - amrex::ignore_unused(edge_lengths); -#endif - amrex::LayoutData* cost = WarpX::getCosts(lev); Real constexpr c2 = PhysConst::c * PhysConst::c; @@ -160,11 +140,12 @@ void FiniteDifferenceSolver::EvolveECartesian ( Array4 const& jy = Jfield[1]->array(mfi); Array4 const& jz = Jfield[2]->array(mfi); - amrex::Array4 lx, ly, lz; + // Extract structures indicating whether the E field should be updated + amrex::Array4 update_Ex_arr, update_Ey_arr, update_Ez_arr; if (EB::enabled()) { - lx = edge_lengths[0]->array(mfi); - ly = edge_lengths[1]->array(mfi); - lz = edge_lengths[2]->array(mfi); + update_Ex_arr = eb_update_E[0]->array(mfi); + update_Ey_arr = eb_update_E[1]->array(mfi); + update_Ez_arr = eb_update_E[2]->array(mfi); } // Extract stencil coefficients @@ -184,8 +165,9 @@ void FiniteDifferenceSolver::EvolveECartesian ( amrex::ParallelFor(tex, tey, tez, [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip field push if this cell is fully covered by embedded boundaries - if (lx && lx(i, j, k) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Ex_arr && update_Ex_arr(i, j, k) == 0) { return; } Ex(i, j, k) += c2 * dt * ( - T_Algo::DownwardDz(By, coefs_z, n_coefs_z, i, j, k) @@ -194,14 +176,9 @@ void FiniteDifferenceSolver::EvolveECartesian ( }, [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip field push if this cell is fully covered by embedded boundaries -#ifdef WARPX_DIM_3D - if (ly && ly(i,j,k) <= 0) { return; } -#elif defined(WARPX_DIM_XZ) - //In XZ Ey is associated with a mesh node, so we need to check if the mesh node is covered - amrex::ignore_unused(ly); - if (lx && (lx(i, j, k)<=0 || lx(i-1, j, k)<=0 || lz(i, j-1, k)<=0 || lz(i, j, k)<=0)) { return; } -#endif + + // Skip field push in the embedded boundaries + if (update_Ey_arr && update_Ey_arr(i, j, k) == 0) { return; } Ey(i, j, k) += c2 * dt * ( - T_Algo::DownwardDx(Bz, coefs_x, n_coefs_x, i, j, k) @@ -210,8 +187,10 @@ void FiniteDifferenceSolver::EvolveECartesian ( }, [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip field push if this cell is fully covered by embedded boundaries - if (lz && lz(i,j,k) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Ez_arr && update_Ez_arr(i, j, k) == 0) { return; } + Ez(i, j, k) += c2 * dt * ( - T_Algo::DownwardDy(Bx, coefs_y, n_coefs_y, i, j, k) + T_Algo::DownwardDx(By, coefs_x, n_coefs_x, i, j, k) @@ -261,14 +240,10 @@ void FiniteDifferenceSolver::EvolveECylindrical ( ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::MultiFab const* Ffield, int lev, amrex::Real const dt ) { -#ifndef AMREX_USE_EB - amrex::ignore_unused(edge_lengths); -#endif - amrex::LayoutData* cost = WarpX::getCosts(lev); // Loop through the grids, and over the tiles within each grid @@ -293,10 +268,12 @@ void FiniteDifferenceSolver::EvolveECylindrical ( Array4 const& jt = Jfield[1]->array(mfi); Array4 const& jz = Jfield[2]->array(mfi); - amrex::Array4 lr, lz; + // Extract structures indicating whether the E field should be updated + amrex::Array4 update_Er_arr, update_Et_arr, update_Ez_arr; if (EB::enabled()) { - lr = edge_lengths[0]->array(mfi); - lz = edge_lengths[2]->array(mfi); + update_Er_arr = eb_update_E[0]->array(mfi); + update_Et_arr = eb_update_E[1]->array(mfi); + update_Ez_arr = eb_update_E[2]->array(mfi); } // Extract stencil coefficients @@ -321,8 +298,9 @@ void FiniteDifferenceSolver::EvolveECylindrical ( amrex::ParallelFor(ter, tet, tez, [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip field push if this cell is fully covered by embedded boundaries - if (lr && lr(i, j, 0) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Er_arr && update_Er_arr(i, j, 0) == 0) { return; } Real const r = rmin + (i + 0.5_rt)*dr; // r on cell-centered point (Er is cell-centered in r) Er(i, j, 0, 0) += c2 * dt*( @@ -341,9 +319,9 @@ void FiniteDifferenceSolver::EvolveECylindrical ( }, [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip field push if this cell is fully covered by embedded boundaries - // The Et field is at a node, so we need to check if the node is covered - if (lr && (lr(i, j, 0)<=0 || lr(i-1, j, 0)<=0 || lz(i, j-1, 0)<=0 || lz(i, j, 0)<=0)) { return; } + + // Skip field push in the embedded boundaries + if (update_Et_arr && update_Et_arr(i, j, 0) == 0) { return; } Real const r = rmin + i*dr; // r on a nodal grid (Et is nodal in r) if (r != 0) { // Off-axis, regular Maxwell equations @@ -386,8 +364,9 @@ void FiniteDifferenceSolver::EvolveECylindrical ( }, [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip field push if this cell is fully covered by embedded boundaries - if (lz && lz(i, j, 0) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Ez_arr && update_Ez_arr(i, j, 0) == 0) { return; } Real const r = rmin + i*dr; // r on a nodal grid (Ez is nodal in r) if (r != 0) { // Off-axis, regular Maxwell equations diff --git a/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceAlgorithms/FieldAccessorFunctors.H b/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceAlgorithms/FieldAccessorFunctors.H index 05b1db1fe94..ba94eab0b66 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceAlgorithms/FieldAccessorFunctors.H +++ b/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceAlgorithms/FieldAccessorFunctors.H @@ -42,9 +42,9 @@ struct FieldAccessorMacroscopic } private: /** Array4 of the source field to be scaled and returned by the operator() */ - amrex::Array4 const m_field; + amrex::Array4 m_field; /** Array4 of the macroscopic parameter used to divide m_field in the operator() */ - amrex::Array4 const m_parameter; + amrex::Array4 m_parameter; }; diff --git a/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H b/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H index 45c06584fda..0d12d104436 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H +++ b/Source/FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H @@ -1,7 +1,10 @@ -/* Copyright 2020 Remi Lehe +/* Copyright 2020-2024 The WarpX Community * * This file is part of WarpX. * + * Authors: Remi Lehe (LBNL) + * S. Eric Clark (Helion Energy) + * * License: BSD-3-Clause-LBNL */ @@ -63,6 +66,7 @@ class FiniteDifferenceSolver int lev, PatchType patch_type, ablastr::fields::VectorField const& Efield, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real dt ); void EvolveF ( amrex::MultiFab* Ffield, @@ -102,7 +106,7 @@ class FiniteDifferenceSolver * \param[out] Efield vector of electric field MultiFabs updated at a given level * \param[in] Bfield vector of magnetic field MultiFabs at a given level * \param[in] Jfield vector of current density MultiFabs at a given level - * \param[in] edge_lengths length of edges along embedded boundaries + * \param[in] eb_update_E indicate in which cell E should be updated (related to embedded boundaries) * \param[in] dt timestep of the simulation * \param[in] macroscopic_properties contains user-defined properties of the medium. */ @@ -110,7 +114,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real dt, std::unique_ptr const& macroscopic_properties); @@ -146,7 +150,7 @@ class FiniteDifferenceSolver * \param[in] Bfield vector of magnetic field MultiFabs at a given level * \param[in] rhofield scalar ion charge density Multifab at a given level * \param[in] Pefield scalar electron pressure MultiFab at a given level - * \param[in] edge_lengths length of edges along embedded boundaries + * \param[in] eb_update_E indicate in which cell E should be updated (related to embedded boundaries) * \param[in] lev level number for the calculation * \param[in] hybrid_model instance of the hybrid-PIC model * \param[in] solve_for_Faraday boolean flag for whether the E-field is solved to be used in Faraday's equation @@ -157,7 +161,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, int lev, HybridPICModel const* hybrid_model, bool solve_for_Faraday ); @@ -167,14 +171,29 @@ class FiniteDifferenceSolver * * \param[out] Jfield vector of current MultiFabs at a given level * \param[in] Bfield vector of magnetic field MultiFabs at a given level - * \param[in] edge_lengths length of edges along embedded boundaries + * \param[in] eb_update_E indicate in which cell E should be updated (related to embedded boundaries) * \param[in] lev level number for the calculation */ void CalculateCurrentAmpere ( - ablastr::fields::VectorField& Jfield, - ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, - int lev ); + ablastr::fields::VectorField& Jfield, + ablastr::fields::VectorField const& Bfield, + std::array< std::unique_ptr,3> const& eb_update_E, + int lev ); + + /** + * \brief Calculation of B field from the vector potential A + * B = (curl x A) / mu0. + * + * \param[out] Bfield vector of current MultiFabs at a given level + * \param[in] Afield vector of magnetic field MultiFabs at a given level + * \param[in] edge_lengths length of edges along embedded boundaries + * \param[in] lev level number for the calculation + */ + void ComputeCurlA ( + ablastr::fields::VectorField& Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, + int lev ); private: @@ -215,7 +234,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::MultiFab const* Ffield, int lev, amrex::Real dt ); @@ -242,7 +261,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, int lev, HybridPICModel const* hybrid_model, bool solve_for_Faraday ); @@ -250,7 +269,15 @@ class FiniteDifferenceSolver void CalculateCurrentAmpereCylindrical ( ablastr::fields::VectorField& Jfield, ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, + int lev + ); + + template + void ComputeCurlACylindrical ( + ablastr::fields::VectorField& Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, int lev ); @@ -267,7 +294,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::MultiFab const* Ffield, int lev, amrex::Real dt ); @@ -312,7 +339,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real dt, std::unique_ptr const& macroscopic_properties); @@ -346,7 +373,7 @@ class FiniteDifferenceSolver ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, int lev, HybridPICModel const* hybrid_model, bool solve_for_Faraday ); @@ -354,7 +381,15 @@ class FiniteDifferenceSolver void CalculateCurrentAmpereCartesian ( ablastr::fields::VectorField& Jfield, ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3> const& eb_update_E, + int lev + ); + + template + void ComputeCurlACartesian ( + ablastr::fields::VectorField & Bfield, + ablastr::fields::VectorField const& Afield, + std::array< std::unique_ptr,3> const& eb_update_B, int lev ); #endif diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/CMakeLists.txt b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/CMakeLists.txt index 1367578b0aa..bb29baefcb9 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/CMakeLists.txt +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/CMakeLists.txt @@ -3,5 +3,6 @@ foreach(D IN LISTS WarpX_DIMS) target_sources(lib_${SD} PRIVATE HybridPICModel.cpp + ExternalVectorPotential.cpp ) endforeach() diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.H b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.H new file mode 100644 index 00000000000..a5088e31b9d --- /dev/null +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.H @@ -0,0 +1,101 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: S. Eric Clark (Helion Energy) + * + * License: BSD-3-Clause-LBNL + */ + +#ifndef WARPX_EXTERNAL_VECTOR_POTENTIAL_H_ +#define WARPX_EXTERNAL_VECTOR_POTENTIAL_H_ + +#include "Fields.H" + +#include "Utils/WarpXAlgorithmSelection.H" + +#include "EmbeddedBoundary/Enabled.H" +#include "FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H" +#include "Utils/Parser/ParserUtils.H" +#include "Utils/WarpXConst.H" +#include "Utils/WarpXProfilerWrapper.H" + +#include + +#include +#include +#include +#include +#include + +#include + +/** + * \brief This class contains the parameters needed to evaluate a + * time varying external vector potential, leading to external E/B + * fields to be applied in Hybrid Solver. This class is used to break up + * the passed in fields into a spatial and time dependent solution. + * + * Eventually this can be used in a list to control independent external + * fields with different time profiles. + * + */ +class ExternalVectorPotential +{ +protected: + int m_nFields; + + std::vector m_field_names; + + std::vector m_Ax_ext_grid_function; + std::vector m_Ay_ext_grid_function; + std::vector m_Az_ext_grid_function; + std::vector, 3>> m_A_external_parser; + std::vector, 3>> m_A_external; + + std::vector m_A_ext_time_function; + std::vector> m_A_external_time_parser; + std::vector> m_A_time_scale; + + std::vector m_read_A_from_file; + std::vector m_external_file_path; + +public: + + // Default Constructor + ExternalVectorPotential (); + + void ReadParameters (); + + void AllocateLevelMFs ( + ablastr::fields::MultiFabRegister & fields, + int lev, const amrex::BoxArray& ba, const amrex::DistributionMapping& dm, + int ncomps, + const amrex::IntVect& ngEB, + const amrex::IntVect& Ex_nodal_flag, + const amrex::IntVect& Ey_nodal_flag, + const amrex::IntVect& Ez_nodal_flag, + const amrex::IntVect& Bx_nodal_flag, + const amrex::IntVect& By_nodal_flag, + const amrex::IntVect& Bz_nodal_flag + ); + + void InitData (); + + void CalculateExternalCurlA (); + void CalculateExternalCurlA (std::string& coil_name); + + AMREX_FORCE_INLINE + void AddExternalFieldFromVectorPotential ( + ablastr::fields::VectorField const& dstField, + amrex::Real scale_factor, + ablastr::fields::VectorField const& srcField, + std::array< std::unique_ptr,3> const& eb_update); + + void UpdateHybridExternalFields ( + amrex::Real t, + amrex::Real dt + ); +}; + +#endif //WARPX_TIME_DEPENDENT_VECTOR_POTENTIAL_H_ diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.cpp b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.cpp new file mode 100644 index 00000000000..22b5a7e2c3f --- /dev/null +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/ExternalVectorPotential.cpp @@ -0,0 +1,384 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: S. Eric Clark (Helion Energy) + * + * License: BSD-3-Clause-LBNL + */ + +#include "ExternalVectorPotential.H" +#include "FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H" +#include "Fields.H" +#include "WarpX.H" + +#include + +using namespace amrex; +using namespace warpx::fields; + +ExternalVectorPotential::ExternalVectorPotential () +{ + ReadParameters(); +} + +void +ExternalVectorPotential::ReadParameters () +{ + const ParmParse pp_ext_A("external_vector_potential"); + + pp_ext_A.queryarr("fields", m_field_names); + + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(!m_field_names.empty(), + "No external field names defined in external_vector_potential.fields"); + + m_nFields = static_cast(m_field_names.size()); + + // Resize vectors and set defaults + m_Ax_ext_grid_function.resize(m_nFields); + m_Ay_ext_grid_function.resize(m_nFields); + m_Az_ext_grid_function.resize(m_nFields); + for (std::string & field : m_Ax_ext_grid_function) { field = "0.0"; } + for (std::string & field : m_Ay_ext_grid_function) { field = "0.0"; } + for (std::string & field : m_Az_ext_grid_function) { field = "0.0"; } + + m_A_external_parser.resize(m_nFields); + m_A_external.resize(m_nFields); + + m_A_ext_time_function.resize(m_nFields); + for (std::string & field_time : m_A_ext_time_function) { field_time = "1.0"; } + + m_A_external_time_parser.resize(m_nFields); + m_A_time_scale.resize(m_nFields); + + m_read_A_from_file.resize(m_nFields); + m_external_file_path.resize(m_nFields); + for (std::string & file_name : m_external_file_path) { file_name = ""; } + + for (int i = 0; i < m_nFields; ++i) { + bool read_from_file = false; + utils::parser::queryWithParser(pp_ext_A, + (m_field_names[i]+".read_from_file").c_str(), read_from_file); + m_read_A_from_file[i] = read_from_file; + + if (m_read_A_from_file[i]) { + pp_ext_A.query((m_field_names[i]+".path").c_str(), m_external_file_path[i]); + } else { + pp_ext_A.query((m_field_names[i]+".Ax_external_grid_function(x,y,z)").c_str(), + m_Ax_ext_grid_function[i]); + pp_ext_A.query((m_field_names[i]+".Ay_external_grid_function(x,y,z)").c_str(), + m_Ay_ext_grid_function[i]); + pp_ext_A.query((m_field_names[i]+".Az_external_grid_function(x,y,z)").c_str(), + m_Az_ext_grid_function[i]); + } + + pp_ext_A.query((m_field_names[i]+".A_time_external_function(t)").c_str(), + m_A_ext_time_function[i]); + } +} + +void +ExternalVectorPotential::AllocateLevelMFs ( + ablastr::fields::MultiFabRegister & fields, + int lev, const BoxArray& ba, const DistributionMapping& dm, + const int ncomps, + const IntVect& ngEB, + const IntVect& Ex_nodal_flag, + const IntVect& Ey_nodal_flag, + const IntVect& Ez_nodal_flag, + const IntVect& Bx_nodal_flag, + const IntVect& By_nodal_flag, + const IntVect& Bz_nodal_flag) +{ + using ablastr::fields::Direction; + for (std::string const & field_name : m_field_names) { + const std::string Aext_field = field_name + std::string{"_Aext"}; + fields.alloc_init(Aext_field, Direction{0}, + lev, amrex::convert(ba, Ex_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(Aext_field, Direction{1}, + lev, amrex::convert(ba, Ey_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(Aext_field, Direction{2}, + lev, amrex::convert(ba, Ez_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + + const std::string curlAext_field = field_name + std::string{"_curlAext"}; + fields.alloc_init(curlAext_field, Direction{0}, + lev, amrex::convert(ba, Bx_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(curlAext_field, Direction{1}, + lev, amrex::convert(ba, By_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(curlAext_field, Direction{2}, + lev, amrex::convert(ba, Bz_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + } + fields.alloc_init(FieldType::hybrid_E_fp_external, Direction{0}, + lev, amrex::convert(ba, Ex_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(FieldType::hybrid_E_fp_external, Direction{1}, + lev, amrex::convert(ba, Ey_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(FieldType::hybrid_E_fp_external, Direction{2}, + lev, amrex::convert(ba, Ez_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(FieldType::hybrid_B_fp_external, Direction{0}, + lev, amrex::convert(ba, Bx_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(FieldType::hybrid_B_fp_external, Direction{1}, + lev, amrex::convert(ba, By_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); + fields.alloc_init(FieldType::hybrid_B_fp_external, Direction{2}, + lev, amrex::convert(ba, Bz_nodal_flag), + dm, ncomps, ngEB, 0.0_rt); +} + +void +ExternalVectorPotential::InitData () +{ + using ablastr::fields::Direction; + auto& warpx = WarpX::GetInstance(); + + int A_time_dep_count = 0; + + for (int i = 0; i < m_nFields; ++i) { + + const std::string Aext_field = m_field_names[i] + std::string{"_Aext"}; + + if (m_read_A_from_file[i]) { + // Read A fields from file + for (auto lev = 0; lev <= warpx.finestLevel(); ++lev) { +#if defined(WARPX_DIM_RZ) + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{0}, lev), + "A", "r"); + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{1}, lev), + "A", "t"); + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{2}, lev), + "A", "z"); +#else + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{0}, lev), + "A", "x"); + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{1}, lev), + "A", "y"); + warpx.ReadExternalFieldFromFile(m_external_file_path[i], + warpx.m_fields.get(Aext_field, Direction{2}, lev), + "A", "z"); +#endif + } + } else { + // Initialize the A fields from expression + m_A_external_parser[i][0] = std::make_unique( + utils::parser::makeParser(m_Ax_ext_grid_function[i],{"x","y","z","t"})); + m_A_external_parser[i][1] = std::make_unique( + utils::parser::makeParser(m_Ay_ext_grid_function[i],{"x","y","z","t"})); + m_A_external_parser[i][2] = std::make_unique( + utils::parser::makeParser(m_Az_ext_grid_function[i],{"x","y","z","t"})); + m_A_external[i][0] = m_A_external_parser[i][0]->compile<4>(); + m_A_external[i][1] = m_A_external_parser[i][1]->compile<4>(); + m_A_external[i][2] = m_A_external_parser[i][2]->compile<4>(); + + // check if the external current parsers depend on time + for (int idim=0; idim<3; idim++) { + const std::set A_ext_symbols = m_A_external_parser[i][idim]->symbols(); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(A_ext_symbols.count("t") == 0, + "Externally Applied Vector potential time variation must be set with A_time_external_function(t)"); + } + + // Initialize data onto grid + for (auto lev = 0; lev <= warpx.finestLevel(); ++lev) { + warpx.ComputeExternalFieldOnGridUsingParser( + Aext_field, + m_A_external[i][0], + m_A_external[i][1], + m_A_external[i][2], + lev, PatchType::fine, + warpx.GetEBUpdateEFlag(), + false); + + for (int idir = 0; idir < 3; ++idir) { + warpx.m_fields.get(Aext_field, Direction{idir}, lev)-> + FillBoundary(warpx.Geom(lev).periodicity()); + } + } + } + + amrex::Gpu::streamSynchronize(); + + CalculateExternalCurlA(m_field_names[i]); + + // Generate parser for time function + m_A_external_time_parser[i] = std::make_unique( + utils::parser::makeParser(m_A_ext_time_function[i],{"t",})); + m_A_time_scale[i] = m_A_external_time_parser[i]->compile<1>(); + + const std::set A_time_ext_symbols = m_A_external_time_parser[i]->symbols(); + A_time_dep_count += static_cast(A_time_ext_symbols.count("t")); + } + + if (A_time_dep_count > 0) { + ablastr::warn_manager::WMRecordWarning( + "HybridPIC ExternalVectorPotential", + "Coulomb Gauge is Expected, please be sure to have a divergence free A. Divergence cleaning of A to be implemented soon.", + ablastr::warn_manager::WarnPriority::low + ); + } + + UpdateHybridExternalFields(warpx.gett_new(0), warpx.getdt(0)); +} + + +void +ExternalVectorPotential::CalculateExternalCurlA () +{ + for (auto fname : m_field_names) { + CalculateExternalCurlA(fname); + } +} + +void +ExternalVectorPotential::CalculateExternalCurlA (std::string& coil_name) +{ + using ablastr::fields::Direction; + auto & warpx = WarpX::GetInstance(); + + // Compute the curl of the reference A field (unscaled by time function) + const std::string Aext_field = coil_name + std::string{"_Aext"}; + const std::string curlAext_field = coil_name + std::string{"_curlAext"}; + + ablastr::fields::MultiLevelVectorField A_ext = + warpx.m_fields.get_mr_levels_alldirs(Aext_field, warpx.finestLevel()); + ablastr::fields::MultiLevelVectorField curlA_ext = + warpx.m_fields.get_mr_levels_alldirs(curlAext_field, warpx.finestLevel()); + + for (int lev = 0; lev <= warpx.finestLevel(); ++lev) { + warpx.get_pointer_fdtd_solver_fp(lev)->ComputeCurlA( + curlA_ext[lev], + A_ext[lev], + warpx.GetEBUpdateBFlag()[lev], + lev); + + for (int idir = 0; idir < 3; ++idir) { + warpx.m_fields.get(curlAext_field, Direction{idir}, lev)-> + FillBoundary(warpx.Geom(lev).periodicity()); + } + } +} + +AMREX_FORCE_INLINE +void +ExternalVectorPotential::AddExternalFieldFromVectorPotential ( + ablastr::fields::VectorField const& dstField, + amrex::Real scale_factor, + ablastr::fields::VectorField const& srcField, + std::array< std::unique_ptr,3> const& eb_update) +{ + // Loop through the grids, and over the tiles within each grid +#ifdef AMREX_USE_OMP +#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) +#endif + for ( MFIter mfi(*dstField[0], TilingIfNotGPU()); mfi.isValid(); ++mfi ) { + // Extract field data for this grid/tile + Array4 const& Fx = dstField[0]->array(mfi); + Array4 const& Fy = dstField[1]->array(mfi); + Array4 const& Fz = dstField[2]->array(mfi); + + Array4 const& Sx = srcField[0]->const_array(mfi); + Array4 const& Sy = srcField[1]->const_array(mfi); + Array4 const& Sz = srcField[2]->const_array(mfi); + + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries. + amrex::Array4 update_Fx_arr, update_Fy_arr, update_Fz_arr; + if (EB::enabled()) { + update_Fx_arr = eb_update[0]->array(mfi); + update_Fy_arr = eb_update[1]->array(mfi); + update_Fz_arr = eb_update[2]->array(mfi); + } + + // Extract tileboxes for which to loop + Box const& tbx = mfi.tilebox(dstField[0]->ixType().toIntVect()); + Box const& tby = mfi.tilebox(dstField[1]->ixType().toIntVect()); + Box const& tbz = mfi.tilebox(dstField[2]->ixType().toIntVect()); + + // Loop over the cells and update the fields + amrex::ParallelFor(tbx, tby, tbz, + + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_Fx_arr && update_Fx_arr(i, j, k) == 0) { return; } + + Fx(i,j,k) += scale_factor * Sx(i,j,k); + }, + + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_Fy_arr && update_Fy_arr(i, j, k) == 0) { return; } + + Fy(i,j,k) += scale_factor * Sy(i,j,k); + }, + + [=] AMREX_GPU_DEVICE (int i, int j, int k){ + // Skip field update in the embedded boundaries + if (update_Fz_arr && update_Fz_arr(i, j, k) == 0) { return; } + + Fz(i,j,k) += scale_factor * Sz(i,j,k); + } + ); + } +} + +void +ExternalVectorPotential::UpdateHybridExternalFields (const amrex::Real t, const amrex::Real dt) +{ + using ablastr::fields::Direction; + auto& warpx = WarpX::GetInstance(); + + ablastr::fields::MultiLevelVectorField B_ext = + warpx.m_fields.get_mr_levels_alldirs(FieldType::hybrid_B_fp_external, warpx.finestLevel()); + ablastr::fields::MultiLevelVectorField E_ext = + warpx.m_fields.get_mr_levels_alldirs(FieldType::hybrid_E_fp_external, warpx.finestLevel()); + + // Zero E and B external fields prior to accumulating external fields + for (int lev = 0; lev <= warpx.finestLevel(); ++lev) { + for (int idir = 0; idir < 3; ++idir) { + B_ext[lev][Direction{idir}]->setVal(0.0_rt); + E_ext[lev][Direction{idir}]->setVal(0.0_rt); + } + } + + // Iterate over external fields and add together with individual time functions. + for (int i = 0; i < m_nFields; ++i) { + const std::string Aext_field = m_field_names[i] + std::string{"_Aext"}; + const std::string curlAext_field = m_field_names[i] + std::string{"_curlAext"}; + + // Get B-field Scaling Factor + const amrex::Real scale_factor_B = m_A_time_scale[i](t); + + // Get dA/dt scaling factor based on time centered FD around t + const amrex::Real sf_l = m_A_time_scale[i](t-0.5_rt*dt); + const amrex::Real sf_r = m_A_time_scale[i](t+0.5_rt*dt); + const amrex::Real scale_factor_E = -(sf_r - sf_l)/dt; + + ablastr::fields::MultiLevelVectorField A_ext = + warpx.m_fields.get_mr_levels_alldirs(Aext_field, warpx.finestLevel()); + ablastr::fields::MultiLevelVectorField curlA_ext = + warpx.m_fields.get_mr_levels_alldirs(curlAext_field, warpx.finestLevel()); + + for (int lev = 0; lev <= warpx.finestLevel(); ++lev) { + AddExternalFieldFromVectorPotential(E_ext[lev], scale_factor_E, A_ext[lev], warpx.GetEBUpdateEFlag()[lev]); + AddExternalFieldFromVectorPotential(B_ext[lev], scale_factor_B, curlA_ext[lev], warpx.GetEBUpdateBFlag()[lev]); + + for (int idir = 0; idir < 3; ++idir) { + E_ext[lev][Direction{idir}]->FillBoundary(warpx.Geom(lev).periodicity()); + B_ext[lev][Direction{idir}]->FillBoundary(warpx.Geom(lev).periodicity()); + } + } + } + amrex::Gpu::streamSynchronize(); +} diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H index 7e8dd260a6e..fabba056733 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H @@ -1,8 +1,9 @@ -/* Copyright 2023 The WarpX Community +/* Copyright 2023-2024 The WarpX Community * * This file is part of WarpX. * * Authors: Roelof Groenewald (TAE Technologies) + * S. Eric Clark (Helion Energy) * * License: BSD-3-Clause-LBNL */ @@ -12,6 +13,9 @@ #include "HybridPICModel_fwd.H" +#include "Fields.H" + +#include "ExternalVectorPotential.H" #include "Utils/WarpXAlgorithmSelection.H" #include "FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H" @@ -23,6 +27,9 @@ #include #include +#include +#include +#include #include @@ -39,11 +46,26 @@ public: void ReadParameters (); /** Allocate hybrid-PIC specific multifabs. Called in constructor. */ - void AllocateLevelMFs (ablastr::fields::MultiFabRegister & fields, - int lev, const amrex::BoxArray& ba, const amrex::DistributionMapping& dm, - int ncomps, const amrex::IntVect& ngJ, const amrex::IntVect& ngRho, - const amrex::IntVect& jx_nodal_flag, const amrex::IntVect& jy_nodal_flag, - const amrex::IntVect& jz_nodal_flag, const amrex::IntVect& rho_nodal_flag); + void AllocateLevelMFs ( + ablastr::fields::MultiFabRegister & fields, + int lev, + const amrex::BoxArray& ba, + const amrex::DistributionMapping& dm, + int ncomps, + const amrex::IntVect& ngJ, + const amrex::IntVect& ngRho, + const amrex::IntVect& ngEB, + const amrex::IntVect& jx_nodal_flag, + const amrex::IntVect& jy_nodal_flag, + const amrex::IntVect& jz_nodal_flag, + const amrex::IntVect& rho_nodal_flag, + const amrex::IntVect& Ex_nodal_flag, + const amrex::IntVect& Ey_nodal_flag, + const amrex::IntVect& Ez_nodal_flag, + const amrex::IntVect& Bx_nodal_flag, + const amrex::IntVect& By_nodal_flag, + const amrex::IntVect& Bz_nodal_flag + ) const; void InitData (); @@ -62,15 +84,15 @@ public: * subtracted as well. Used in the Ohm's law solver (kinetic-fluid hybrid model). * * \param[in] Bfield Magnetic field from which the current is calculated. - * \param[in] edge_lengths Length of cell edges taking embedded boundaries into account + * \param[in] eb_update_E Indicate in which cell J should be calculated (related to embedded boundaries). */ void CalculatePlasmaCurrent ( ablastr::fields::MultiLevelVectorField const& Bfield, - ablastr::fields::MultiLevelVectorField const& edge_lengths + amrex::Vector,3 > >& eb_update_E ); void CalculatePlasmaCurrent ( ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, int lev ); @@ -83,7 +105,7 @@ public: ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelVectorField const& Bfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, bool solve_for_Faraday) const; void HybridPICSolveE ( @@ -91,7 +113,7 @@ public: ablastr::fields::VectorField const& Jfield, ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, int lev, bool solve_for_Faraday) const; void HybridPICSolveE ( @@ -99,7 +121,7 @@ public: ablastr::fields::VectorField const& Jfield, ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, int lev, PatchType patch_type, bool solve_for_Faraday) const; void BfieldEvolveRK ( @@ -107,7 +129,7 @@ public: ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, DtType a_dt_type, amrex::IntVect ng, std::optional nodal_sync); @@ -116,7 +138,7 @@ public: ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, int lev, DtType dt_type, amrex::IntVect ng, std::optional nodal_sync); @@ -125,7 +147,7 @@ public: ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, DtType dt_type, amrex::IntVect ng, std::optional nodal_sync); @@ -142,7 +164,7 @@ public: * charge density (and assumption of quasi-neutrality) using the user * specified electron equation of state. * - * \param[out] Pe_filed scalar electron pressure MultiFab at a given level + * \param[out] Pe_field scalar electron pressure MultiFab at a given level * \param[in] rho_field scalar ion charge density Multifab at a given level */ void FillElectronPressureMF ( @@ -153,6 +175,8 @@ public: /** Number of substeps to take when evolving B */ int m_substeps = 10; + bool m_holmstrom_vacuum_region = false; + /** Electron temperature in eV */ amrex::Real m_elec_temp; /** Reference electron density */ @@ -170,7 +194,11 @@ public: bool m_resistivity_has_J_dependence = false; /** Plasma hyper-resisitivity */ - amrex::Real m_eta_h = 0.0; + std::string m_eta_h_expression = "0.0"; + std::unique_ptr m_hyper_resistivity_parser; + amrex::ParserExecutor<2> m_eta_h; + bool m_include_hyper_resistivity_term = false; + bool m_hyper_resistivity_has_B_dependence = false; /** External current */ std::string m_Jx_ext_grid_function = "0.0"; @@ -178,7 +206,11 @@ public: std::string m_Jz_ext_grid_function = "0.0"; std::array< std::unique_ptr, 3> m_J_external_parser; std::array< amrex::ParserExecutor<4>, 3> m_J_external; - bool m_external_field_has_time_dependence = false; + bool m_external_current_has_time_dependence = false; + + /** External E/B fields */ + bool m_add_external_fields = false; + std::unique_ptr m_external_vector_potential; /** Gpu Vector with index type of the Jx multifab */ amrex::GpuArray Jx_IndexType; diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.cpp b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.cpp index 424f194ff37..87b5be3c0b7 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.cpp +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.cpp @@ -1,8 +1,9 @@ -/* Copyright 2023 The WarpX Community +/* Copyright 2023-2024 The WarpX Community * * This file is part of WarpX. * * Authors: Roelof Groenewald (TAE Technologies) + * S. Eric Clark (Helion Energy) * * License: BSD-3-Clause-LBNL */ @@ -10,7 +11,10 @@ #include "HybridPICModel.H" #include "EmbeddedBoundary/Enabled.H" +#include "Python/callbacks.H" #include "Fields.H" +#include "Particles/MultiParticleContainer.H" +#include "ExternalVectorPotential.H" #include "WarpX.H" using namespace amrex; @@ -29,6 +33,8 @@ void HybridPICModel::ReadParameters () // of sub steps can be specified by the user (defaults to 50). utils::parser::queryWithParser(pp_hybrid, "substeps", m_substeps); + utils::parser::queryWithParser(pp_hybrid, "holmstrom_vacuum_region", m_holmstrom_vacuum_region); + // The hybrid model requires an electron temperature, reference density // and exponent to be given. These values will be used to calculate the // electron pressure according to p = n0 * Te * (n/n0)^gamma @@ -42,9 +48,9 @@ void HybridPICModel::ReadParameters () } pp_hybrid.query("plasma_resistivity(rho,J)", m_eta_expression); - utils::parser::queryWithParser(pp_hybrid, "n_floor", m_n_floor); + pp_hybrid.query("plasma_hyper_resistivity(rho,B)", m_eta_h_expression); - utils::parser::queryWithParser(pp_hybrid, "plasma_hyper_resistivity", m_eta_h); + utils::parser::queryWithParser(pp_hybrid, "n_floor", m_n_floor); // convert electron temperature from eV to J m_elec_temp *= PhysConst::q_e; @@ -53,15 +59,31 @@ void HybridPICModel::ReadParameters () pp_hybrid.query("Jx_external_grid_function(x,y,z,t)", m_Jx_ext_grid_function); pp_hybrid.query("Jy_external_grid_function(x,y,z,t)", m_Jy_ext_grid_function); pp_hybrid.query("Jz_external_grid_function(x,y,z,t)", m_Jz_ext_grid_function); + + // external fields + pp_hybrid.query("add_external_fields", m_add_external_fields); + + if (m_add_external_fields) { + m_external_vector_potential = std::make_unique(); + } } -void HybridPICModel::AllocateLevelMFs (ablastr::fields::MultiFabRegister & fields, - int lev, const BoxArray& ba, const DistributionMapping& dm, - const int ncomps, const IntVect& ngJ, const IntVect& ngRho, - const IntVect& jx_nodal_flag, - const IntVect& jy_nodal_flag, - const IntVect& jz_nodal_flag, - const IntVect& rho_nodal_flag) +void HybridPICModel::AllocateLevelMFs ( + ablastr::fields::MultiFabRegister & fields, + int lev, const BoxArray& ba, const DistributionMapping& dm, + const int ncomps, + const IntVect& ngJ, const IntVect& ngRho, + const IntVect& ngEB, + const IntVect& jx_nodal_flag, + const IntVect& jy_nodal_flag, + const IntVect& jz_nodal_flag, + const IntVect& rho_nodal_flag, + const IntVect& Ex_nodal_flag, + const IntVect& Ey_nodal_flag, + const IntVect& Ez_nodal_flag, + const IntVect& Bx_nodal_flag, + const IntVect& By_nodal_flag, + const IntVect& Bz_nodal_flag) const { using ablastr::fields::Direction; @@ -113,6 +135,16 @@ void HybridPICModel::AllocateLevelMFs (ablastr::fields::MultiFabRegister & field lev, amrex::convert(ba, jz_nodal_flag), dm, ncomps, IntVect(1), 0.0_rt); + if (m_add_external_fields) { + m_external_vector_potential->AllocateLevelMFs( + fields, + lev, ba, dm, + ncomps, ngEB, + Ex_nodal_flag, Ey_nodal_flag, Ez_nodal_flag, + Bx_nodal_flag, By_nodal_flag, Bz_nodal_flag + ); + } + #ifdef WARPX_DIM_RZ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( (ncomps == 1), @@ -128,6 +160,13 @@ void HybridPICModel::InitData () const std::set resistivity_symbols = m_resistivity_parser->symbols(); m_resistivity_has_J_dependence += resistivity_symbols.count("J"); + m_include_hyper_resistivity_term = (m_eta_h_expression != "0.0"); + m_hyper_resistivity_parser = std::make_unique( + utils::parser::makeParser(m_eta_h_expression, {"rho","B"})); + m_eta_h = m_hyper_resistivity_parser->compile<2>(); + const std::set hyper_resistivity_symbols = m_hyper_resistivity_parser->symbols(); + m_hyper_resistivity_has_B_dependence += hyper_resistivity_symbols.count("B"); + m_J_external_parser[0] = std::make_unique( utils::parser::makeParser(m_Jx_ext_grid_function,{"x","y","z","t"})); m_J_external_parser[1] = std::make_unique( @@ -141,7 +180,7 @@ void HybridPICModel::InitData () // check if the external current parsers depend on time for (int i=0; i<3; i++) { const std::set J_ext_symbols = m_J_external_parser[i]->symbols(); - m_external_field_has_time_dependence += J_ext_symbols.count("t"); + m_external_current_has_time_dependence += J_ext_symbols.count("t"); } auto & warpx = WarpX::GetInstance(); @@ -226,15 +265,18 @@ void HybridPICModel::InitData () m_J_external[0], m_J_external[1], m_J_external[2], - lev, PatchType::fine, 'e', - warpx.m_fields.get_alldirs(FieldType::edge_lengths, lev), - warpx.m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, + warpx.GetEBUpdateEFlag()); + } + + if (m_add_external_fields) { + m_external_vector_potential->InitData(); } } void HybridPICModel::GetCurrentExternal () { - if (!m_external_field_has_time_dependence) { return; } + if (!m_external_current_has_time_dependence) { return; } auto& warpx = WarpX::GetInstance(); for (int lev = 0; lev <= warpx.finestLevel(); ++lev) @@ -244,26 +286,25 @@ void HybridPICModel::GetCurrentExternal () m_J_external[0], m_J_external[1], m_J_external[2], - lev, PatchType::fine, 'e', - warpx.m_fields.get_alldirs(FieldType::edge_lengths, lev), - warpx.m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, + warpx.GetEBUpdateEFlag()); } } void HybridPICModel::CalculatePlasmaCurrent ( ablastr::fields::MultiLevelVectorField const& Bfield, - ablastr::fields::MultiLevelVectorField const& edge_lengths) + amrex::Vector,3 > >& eb_update_E) { auto& warpx = WarpX::GetInstance(); for (int lev = 0; lev <= warpx.finestLevel(); ++lev) { - CalculatePlasmaCurrent(Bfield[lev], edge_lengths[lev], lev); + CalculatePlasmaCurrent(Bfield[lev], eb_update_E[lev], lev); } } void HybridPICModel::CalculatePlasmaCurrent ( ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, const int lev) { WARPX_PROFILE("HybridPICModel::CalculatePlasmaCurrent()"); @@ -271,7 +312,7 @@ void HybridPICModel::CalculatePlasmaCurrent ( auto& warpx = WarpX::GetInstance(); ablastr::fields::VectorField current_fp_plasma = warpx.m_fields.get_alldirs(FieldType::hybrid_current_fp_plasma, lev); warpx.get_pointer_fdtd_solver_fp(lev)->CalculateCurrentAmpere( - current_fp_plasma, Bfield, edge_lengths, lev + current_fp_plasma, Bfield, eb_update_E, lev ); // we shouldn't apply the boundary condition to J since J = J_i - J_e but @@ -295,7 +336,7 @@ void HybridPICModel::HybridPICSolveE ( ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelVectorField const& Bfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, const bool solve_for_Faraday) const { auto& warpx = WarpX::GetInstance(); @@ -303,9 +344,11 @@ void HybridPICModel::HybridPICSolveE ( { HybridPICSolveE( Efield[lev], Jfield[lev], Bfield[lev], *rhofield[lev], - edge_lengths[lev], lev, solve_for_Faraday + eb_update_E[lev], lev, solve_for_Faraday ); } + // Allow execution of Python callback after E-field push + ExecutePythonCallback("afterEpush"); } void HybridPICModel::HybridPICSolveE ( @@ -313,13 +356,13 @@ void HybridPICModel::HybridPICSolveE ( ablastr::fields::VectorField const& Jfield, ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, const int lev, const bool solve_for_Faraday) const { WARPX_PROFILE("WarpX::HybridPICSolveE()"); HybridPICSolveE( - Efield, Jfield, Bfield, rhofield, edge_lengths, lev, + Efield, Jfield, Bfield, rhofield, eb_update_E, lev, PatchType::fine, solve_for_Faraday ); if (lev > 0) @@ -334,21 +377,22 @@ void HybridPICModel::HybridPICSolveE ( ablastr::fields::VectorField const& Jfield, ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 >& eb_update_E, const int lev, PatchType patch_type, const bool solve_for_Faraday) const { auto& warpx = WarpX::GetInstance(); ablastr::fields::VectorField current_fp_plasma = warpx.m_fields.get_alldirs(FieldType::hybrid_current_fp_plasma, lev); - const ablastr::fields::ScalarField electron_pressure_fp = warpx.m_fields.get(FieldType::hybrid_electron_pressure_fp, lev); + auto* const electron_pressure_fp = warpx.m_fields.get(FieldType::hybrid_electron_pressure_fp, lev); // Solve E field in regular cells warpx.get_pointer_fdtd_solver_fp(lev)->HybridPICSolveE( Efield, current_fp_plasma, Jfield, Bfield, rhofield, - *electron_pressure_fp, edge_lengths, lev, this, solve_for_Faraday + *electron_pressure_fp, eb_update_E, lev, this, solve_for_Faraday ); - warpx.ApplyEfieldBoundary(lev, patch_type); + amrex::Real const time = warpx.gett_old(0) + warpx.getdt(0); + warpx.ApplyEfieldBoundary(lev, patch_type, time); } void HybridPICModel::CalculateElectronPressure() const @@ -412,7 +456,7 @@ void HybridPICModel::BfieldEvolveRK ( ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, DtType dt_type, IntVect ng, std::optional nodal_sync ) { @@ -420,7 +464,7 @@ void HybridPICModel::BfieldEvolveRK ( for (int lev = 0; lev <= warpx.finestLevel(); ++lev) { BfieldEvolveRK( - Bfield, Efield, Jfield, rhofield, edge_lengths, dt, lev, dt_type, + Bfield, Efield, Jfield, rhofield, eb_update_E, dt, lev, dt_type, ng, nodal_sync ); } @@ -431,7 +475,7 @@ void HybridPICModel::BfieldEvolveRK ( ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, int lev, DtType dt_type, IntVect ng, std::optional nodal_sync ) { @@ -458,7 +502,7 @@ void HybridPICModel::BfieldEvolveRK ( // The Runge-Kutta scheme begins here. // Step 1: FieldPush( - Bfield, Efield, Jfield, rhofield, edge_lengths, + Bfield, Efield, Jfield, rhofield, eb_update_E, 0.5_rt*dt, dt_type, ng, nodal_sync ); @@ -474,7 +518,7 @@ void HybridPICModel::BfieldEvolveRK ( // Step 2: FieldPush( - Bfield, Efield, Jfield, rhofield, edge_lengths, + Bfield, Efield, Jfield, rhofield, eb_update_E, 0.5_rt*dt, dt_type, ng, nodal_sync ); @@ -494,7 +538,7 @@ void HybridPICModel::BfieldEvolveRK ( // Step 3: FieldPush( - Bfield, Efield, Jfield, rhofield, edge_lengths, + Bfield, Efield, Jfield, rhofield, eb_update_E, dt, dt_type, ng, nodal_sync ); @@ -510,7 +554,7 @@ void HybridPICModel::BfieldEvolveRK ( // Step 4: FieldPush( - Bfield, Efield, Jfield, rhofield, edge_lengths, + Bfield, Efield, Jfield, rhofield, eb_update_E, 0.5_rt*dt, dt_type, ng, nodal_sync ); @@ -539,23 +583,27 @@ void HybridPICModel::BfieldEvolveRK ( } } + void HybridPICModel::FieldPush ( ablastr::fields::MultiLevelVectorField const& Bfield, ablastr::fields::MultiLevelVectorField const& Efield, ablastr::fields::MultiLevelVectorField const& Jfield, ablastr::fields::MultiLevelScalarField const& rhofield, - ablastr::fields::MultiLevelVectorField const& edge_lengths, + amrex::Vector,3 > >& eb_update_E, amrex::Real dt, DtType dt_type, IntVect ng, std::optional nodal_sync ) { auto& warpx = WarpX::GetInstance(); + amrex::Real const t_old = warpx.gett_old(0); + // Calculate J = curl x B / mu0 - J_ext - CalculatePlasmaCurrent(Bfield, edge_lengths); + CalculatePlasmaCurrent(Bfield, eb_update_E); // Calculate the E-field from Ohm's law - HybridPICSolveE(Efield, Jfield, Bfield, rhofield, edge_lengths, true); + HybridPICSolveE(Efield, Jfield, Bfield, rhofield, eb_update_E, true); warpx.FillBoundaryE(ng, nodal_sync); + // Push forward the B-field using Faraday's law - warpx.EvolveB(dt, dt_type); + warpx.EvolveB(dt, dt_type, t_old); warpx.FillBoundaryB(ng, nodal_sync); } diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/Make.package b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/Make.package index 8145cfcef2f..d4fa9bfc390 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/Make.package +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel/Make.package @@ -1,3 +1,4 @@ CEXE_sources += HybridPICModel.cpp +CEXE_sources += ExternalVectorPotential.cpp VPATH_LOCATIONS += $(WARPX_HOME)/Source/FieldSolver/FiniteDifferenceSolver/HybridPICModel diff --git a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICSolveE.cpp b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICSolveE.cpp index 76fedbf4dea..e3f46c686ea 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/HybridPICSolveE.cpp +++ b/Source/FieldSolver/FiniteDifferenceSolver/HybridPICSolveE.cpp @@ -1,8 +1,9 @@ -/* Copyright 2023 The WarpX Community +/* Copyright 2023-2024 The WarpX Community * * This file is part of WarpX. * * Authors: Roelof Groenewald (TAE Technologies) + * S. Eric Clark (Helion Energy) * * License: BSD-3-Clause-LBNL */ @@ -22,11 +23,12 @@ #include using namespace amrex; +using warpx::fields::FieldType; void FiniteDifferenceSolver::CalculateCurrentAmpere ( ablastr::fields::VectorField & Jfield, ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev ) { // Select algorithm (The choice of algorithm is a runtime option, @@ -34,12 +36,12 @@ void FiniteDifferenceSolver::CalculateCurrentAmpere ( if (m_fdtd_algo == ElectromagneticSolverAlgo::HybridPIC) { #ifdef WARPX_DIM_RZ CalculateCurrentAmpereCylindrical ( - Jfield, Bfield, edge_lengths, lev + Jfield, Bfield, eb_update_E, lev ); #else CalculateCurrentAmpereCartesian ( - Jfield, Bfield, edge_lengths, lev + Jfield, Bfield, eb_update_E, lev ); #endif @@ -61,7 +63,7 @@ template void FiniteDifferenceSolver::CalculateCurrentAmpereCylindrical ( ablastr::fields::VectorField& Jfield, ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev ) { @@ -92,12 +94,16 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCylindrical ( Array4 const& Bt = Bfield[1]->array(mfi); Array4 const& Bz = Bfield[2]->array(mfi); - amrex::Array4 lr, lt, lz; - + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries. + // The plasma current is stored at the same locations as the E-field, + // therefore the `eb_update_E` multifab also appropriately specifies + // where the plasma current should be calculated. + amrex::Array4 update_Jr_arr, update_Jt_arr, update_Jz_arr; if (EB::enabled()) { - lr = edge_lengths[0]->array(mfi); - lt = edge_lengths[1]->array(mfi); - lz = edge_lengths[2]->array(mfi); + update_Jr_arr = eb_update_E[0]->array(mfi); + update_Jt_arr = eb_update_E[1]->array(mfi); + update_Jz_arr = eb_update_E[2]->array(mfi); } // Extract stencil coefficients @@ -124,8 +130,10 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCylindrical ( // Jr calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip if this cell is fully covered by embedded boundaries - if (lr && lr(i, j, 0) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Jr_arr && update_Jr_arr(i, j, 0) == 0) { return; } + // Mode m=0 Jr(i, j, 0, 0) = one_over_mu0 * ( - T_Algo::DownwardDz(Bt, coefs_z, n_coefs_z, i, j, 0, 0) @@ -148,8 +156,9 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCylindrical ( // Jt calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // In RZ Jt is associated with a mesh node, so we need to check if the mesh node is covered - if (lr && (lr(i, j, 0)<=0 || lr(i-1, j, 0)<=0 || lz(i, j-1, 0)<=0 || lz(i, j, 0)<=0)) { return; } + + // Skip field update in the embedded boundaries + if (update_Jt_arr && update_Jt_arr(i, j, 0) == 0) { return; } // r on a nodal point (Jt is nodal in r) Real const r = rmin + i*dr; @@ -194,8 +203,10 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCylindrical ( // Jz calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip if this cell is fully covered by embedded boundaries - if (lz && lz(i, j, 0) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Jz_arr && update_Jz_arr(i, j, 0) == 0) { return; } + // r on a nodal point (Jz is nodal in r) Real const r = rmin + i*dr; // Off-axis, regular curl @@ -244,7 +255,7 @@ template void FiniteDifferenceSolver::CalculateCurrentAmpereCartesian ( ablastr::fields::VectorField& Jfield, ablastr::fields::VectorField const& Bfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev ) { @@ -274,11 +285,16 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCartesian ( Array4 const &By = Bfield[1]->const_array(mfi); Array4 const &Bz = Bfield[2]->const_array(mfi); - amrex::Array4 lx, ly, lz; + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries. + // The plasma current is stored at the same locations as the E-field, + // therefore the `eb_update_E` multifab also appropriately specifies + // where the plasma current should be calculated. + amrex::Array4 update_Jx_arr, update_Jy_arr, update_Jz_arr; if (EB::enabled()) { - lx = edge_lengths[0]->array(mfi); - ly = edge_lengths[1]->array(mfi); - lz = edge_lengths[2]->array(mfi); + update_Jx_arr = eb_update_E[0]->array(mfi); + update_Jy_arr = eb_update_E[1]->array(mfi); + update_Jz_arr = eb_update_E[2]->array(mfi); } // Extract stencil coefficients @@ -302,8 +318,9 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCartesian ( // Jx calculation [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip if this cell is fully covered by embedded boundaries - if (lx && lx(i, j, k) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Jx_arr && update_Jx_arr(i, j, k) == 0) { return; } Jx(i, j, k) = one_over_mu0 * ( - T_Algo::DownwardDz(By, coefs_z, n_coefs_z, i, j, k) @@ -313,14 +330,10 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCartesian ( // Jy calculation [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip if this cell is fully covered by embedded boundaries -#ifdef WARPX_DIM_3D - if (ly && ly(i,j,k) <= 0) { return; } -#elif defined(WARPX_DIM_XZ) - // In XZ Jy is associated with a mesh node, so we need to check if the mesh node is covered - amrex::ignore_unused(ly); - if (lx && (lx(i, j, k)<=0 || lx(i-1, j, k)<=0 || lz(i, j-1, k)<=0 || lz(i, j, k)<=0)) { return; } -#endif + + // Skip field update in the embedded boundaries + if (update_Jy_arr && update_Jy_arr(i, j, k) == 0) { return; } + Jy(i, j, k) = one_over_mu0 * ( - T_Algo::DownwardDx(Bz, coefs_x, n_coefs_x, i, j, k) + T_Algo::DownwardDz(Bx, coefs_z, n_coefs_z, i, j, k) @@ -329,8 +342,9 @@ void FiniteDifferenceSolver::CalculateCurrentAmpereCartesian ( // Jz calculation [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip if this cell is fully covered by embedded boundaries - if (lz && lz(i,j,k) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Jz_arr && update_Jz_arr(i, j, k) == 0) { return; } Jz(i, j, k) = one_over_mu0 * ( - T_Algo::DownwardDy(Bx, coefs_y, n_coefs_y, i, j, k) @@ -357,7 +371,7 @@ void FiniteDifferenceSolver::HybridPICSolveE ( ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev, HybridPICModel const* hybrid_model, const bool solve_for_Faraday) { @@ -368,14 +382,14 @@ void FiniteDifferenceSolver::HybridPICSolveE ( HybridPICSolveECylindrical ( Efield, Jfield, Jifield, Bfield, rhofield, Pefield, - edge_lengths, lev, hybrid_model, solve_for_Faraday + eb_update_E, lev, hybrid_model, solve_for_Faraday ); #else HybridPICSolveECartesian ( Efield, Jfield, Jifield, Bfield, rhofield, Pefield, - edge_lengths, lev, hybrid_model, solve_for_Faraday + eb_update_E, lev, hybrid_model, solve_for_Faraday ); #endif @@ -394,7 +408,7 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev, HybridPICModel const* hybrid_model, const bool solve_for_Faraday ) { @@ -414,8 +428,19 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( const auto eta_h = hybrid_model->m_eta_h; const auto rho_floor = hybrid_model->m_n_floor * PhysConst::q_e; const auto resistivity_has_J_dependence = hybrid_model->m_resistivity_has_J_dependence; + const auto hyper_resistivity_has_B_dependence = hybrid_model->m_hyper_resistivity_has_B_dependence; + const bool include_hyper_resistivity_term = hybrid_model->m_include_hyper_resistivity_term; + + const bool include_external_fields = hybrid_model->m_add_external_fields; - const bool include_hyper_resistivity_term = (eta_h > 0.0) && solve_for_Faraday; + const bool holmstrom_vacuum_region = hybrid_model->m_holmstrom_vacuum_region; + + auto & warpx = WarpX::GetInstance(); + ablastr::fields::VectorField Bfield_external, Efield_external; + if (include_external_fields) { + Bfield_external = warpx.m_fields.get_alldirs(FieldType::hybrid_B_fp_external, 0); // lev=0 + Efield_external = warpx.m_fields.get_alldirs(FieldType::hybrid_E_fp_external, 0); // lev=0 + } // Index type required for interpolating fields from their respective // staggering to the Ex, Ey, Ez locations @@ -473,6 +498,13 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( Array4 const& Bt = Bfield[1]->const_array(mfi); Array4 const& Bz = Bfield[2]->const_array(mfi); + Array4 Br_ext, Bt_ext, Bz_ext; + if (include_external_fields) { + Br_ext = Bfield_external[0]->array(mfi); + Bt_ext = Bfield_external[1]->array(mfi); + Bz_ext = Bfield_external[2]->array(mfi); + } + // Loop over the cells and update the nodal E field amrex::ParallelFor(mfi.tilebox(), [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ @@ -487,9 +519,15 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( auto const jiz_interp = Interp(Jiz, Jz_stag, nodal, coarsen, i, j, 0, 0); // interpolate the B field to a nodal grid - auto const Br_interp = Interp(Br, Br_stag, nodal, coarsen, i, j, 0, 0); - auto const Bt_interp = Interp(Bt, Bt_stag, nodal, coarsen, i, j, 0, 0); - auto const Bz_interp = Interp(Bz, Bz_stag, nodal, coarsen, i, j, 0, 0); + auto Br_interp = Interp(Br, Br_stag, nodal, coarsen, i, j, 0, 0); + auto Bt_interp = Interp(Bt, Bt_stag, nodal, coarsen, i, j, 0, 0); + auto Bz_interp = Interp(Bz, Bz_stag, nodal, coarsen, i, j, 0, 0); + + if (include_external_fields) { + Br_interp += Interp(Br_ext, Br_stag, nodal, coarsen, i, j, 0, 0); + Bt_interp += Interp(Bt_ext, Bt_stag, nodal, coarsen, i, j, 0, 0); + Bz_interp += Interp(Bz_ext, Bz_stag, nodal, coarsen, i, j, 0, 0); + } // calculate enE = (J - Ji) x B enE_nodal(i, j, 0, 0) = ( @@ -536,12 +574,24 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( Array4 const& enE = enE_nodal_mf.const_array(mfi); Array4 const& rho = rhofield.const_array(mfi); Array4 const& Pe = Pefield.const_array(mfi); + Array4 const& Br = Bfield[0]->array(mfi); + Array4 const& Bt = Bfield[1]->array(mfi); + Array4 const& Bz = Bfield[2]->array(mfi); - amrex::Array4 lr, lz; + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries + amrex::Array4 update_Er_arr, update_Et_arr, update_Ez_arr; if (EB::enabled()) { - lr = edge_lengths[0]->array(mfi); - // edge_lengths[1] is `lt` and is not needed - lz = edge_lengths[2]->array(mfi); + update_Er_arr = eb_update_E[0]->array(mfi); + update_Et_arr = eb_update_E[1]->array(mfi); + update_Ez_arr = eb_update_E[2]->array(mfi); + } + + Array4 Er_ext, Et_ext, Ez_ext; + if (include_external_fields) { + Er_ext = Efield_external[0]->array(mfi); + Et_ext = Efield_external[1]->array(mfi); + Ez_ext = Efield_external[2]->array(mfi); } // Extract stencil coefficients @@ -563,50 +613,74 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( // Er calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip if this cell is fully covered by embedded boundaries - if (lr && lr(i, j, 0) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Er_arr && update_Er_arr(i, j, 0) == 0) { return; } // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Er_stag, coarsen, i, j, 0, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jr_val = Interp(Jr, Jr_stag, Er_stag, coarsen, i, j, 0, 0); - const Real jt_val = Interp(Jt, Jt_stag, Er_stag, coarsen, i, j, 0, 0); - const Real jz_val = Interp(Jz, Jz_stag, Er_stag, coarsen, i, j, 0, 0); - jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Er_stag, coarsen, i, j, 0, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Er(i, j, 0) = 0._rt; + } else { + // Get the gradient of the electron pressure if the longitudinal part of + // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 + const Real grad_Pe = (!solve_for_Faraday) ? + T_Algo::UpwardDr(Pe, coefs_r, n_coefs_r, i, j, 0, 0) + : 0._rt; - // Get the gradient of the electron pressure if the longitudinal part of - // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 - Real grad_Pe = 0._rt; - if (!solve_for_Faraday) { grad_Pe = T_Algo::UpwardDr(Pe, coefs_r, n_coefs_r, i, j, 0, 0); } + // interpolate the nodal neE values to the Yee grid + const auto enE_r = Interp(enE, nodal, Er_stag, coarsen, i, j, 0, 0); - // interpolate the nodal neE values to the Yee grid - auto enE_r = Interp(enE, nodal, Er_stag, coarsen, i, j, 0, 0); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Er(i, j, 0) = (enE_r - grad_Pe) / rho_val; + Er(i, j, 0) = (enE_r - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Er(i, j, 0) += eta(rho_val, jtot_val) * Jr(i, j, 0); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if (resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jr_val = Jr(i, j, 0); + const Real jt_val = Interp(Jt, Jt_stag, Er_stag, coarsen, i, j, 0, 0); + const Real jz_val = Interp(Jz, Jz_stag, Er_stag, coarsen, i, j, 0, 0); + jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); + } + + Er(i, j, 0) += eta(rho_val, jtot_val) * Jr(i, j, 0); + + if (include_hyper_resistivity_term) { - if (include_hyper_resistivity_term) { - // r on cell-centered point (Jr is cell-centered in r) - Real const r = rmin + (i + 0.5_rt)*dr; + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real br_val = Interp(Br, Br_stag, Er_stag, coarsen, i, j, 0, 0); + const Real bt_val = Interp(Bt, Bt_stag, Er_stag, coarsen, i, j, 0, 0); + const Real bz_val = Interp(Bz, Bz_stag, Er_stag, coarsen, i, j, 0, 0); + btot_val = std::sqrt(br_val*br_val + bt_val*bt_val + bz_val*bz_val); + } + + // r on cell-centered point (Jr is cell-centered in r) + const Real r = rmin + (i + 0.5_rt)*dr; + auto nabla2Jr = T_Algo::Dr_rDr_over_r(Jr, r, dr, coefs_r, n_coefs_r, i, j, 0, 0) + + T_Algo::Dzz(Jr, coefs_z, n_coefs_z, i, j, 0, 0) - Jr(i, j, 0)/(r*r); + + Er(i, j, 0) -= eta_h(rho_val, btot_val) * nabla2Jr; + } + } - auto nabla2Jr = T_Algo::Dr_rDr_over_r(Jr, r, dr, coefs_r, n_coefs_r, i, j, 0, 0); - Er(i, j, 0) -= eta_h * nabla2Jr; + if (include_external_fields && (rho_val >= rho_floor)) { + Er(i, j, 0) -= Er_ext(i, j, 0); } }, // Et calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // In RZ Et is associated with a mesh node, so we need to check if the mesh node is covered - if (lr && (lr(i, j, 0)<=0 || lr(i-1, j, 0)<=0 || lz(i, j-1, 0)<=0 || lz(i, j, 0)<=0)) { return; } + + // Skip field update in the embedded boundaries + if (update_Et_arr && update_Et_arr(i, j, 0) == 0) { return; } // r on a nodal grid (Et is nodal in r) Real const r = rmin + i*dr; @@ -617,71 +691,125 @@ void FiniteDifferenceSolver::HybridPICSolveECylindrical ( } // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Er_stag, coarsen, i, j, 0, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jr_val = Interp(Jr, Jr_stag, Et_stag, coarsen, i, j, 0, 0); - const Real jt_val = Interp(Jt, Jt_stag, Et_stag, coarsen, i, j, 0, 0); - const Real jz_val = Interp(Jz, Jz_stag, Et_stag, coarsen, i, j, 0, 0); - jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Et_stag, coarsen, i, j, 0, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Et(i, j, 0) = 0._rt; + } else { + // Get the gradient of the electron pressure + // -> d/dt = 0 for m = 0 + const auto grad_Pe = 0.0_rt; - // Get the gradient of the electron pressure - // -> d/dt = 0 for m = 0 - auto grad_Pe = 0.0_rt; + // interpolate the nodal neE values to the Yee grid + const auto enE_t = Interp(enE, nodal, Et_stag, coarsen, i, j, 0, 1); - // interpolate the nodal neE values to the Yee grid - auto enE_t = Interp(enE, nodal, Et_stag, coarsen, i, j, 0, 1); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Et(i, j, 0) = (enE_t - grad_Pe) / rho_val; + Et(i, j, 0) = (enE_t - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Et(i, j, 0) += eta(rho_val, jtot_val) * Jt(i, j, 0); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if(resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jr_val = Interp(Jr, Jr_stag, Et_stag, coarsen, i, j, 0, 0); + const Real jt_val = Jt(i, j, 0); + const Real jz_val = Interp(Jz, Jz_stag, Et_stag, coarsen, i, j, 0, 0); + jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); + } + + Et(i, j, 0) += eta(rho_val, jtot_val) * Jt(i, j, 0); + + if (include_hyper_resistivity_term) { + + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real br_val = Interp(Br, Br_stag, Et_stag, coarsen, i, j, 0, 0); + const Real bt_val = Interp(Bt, Bt_stag, Et_stag, coarsen, i, j, 0, 0); + const Real bz_val = Interp(Bz, Bz_stag, Et_stag, coarsen, i, j, 0, 0); + btot_val = std::sqrt(br_val*br_val + bt_val*bt_val + bz_val*bz_val); + } + + auto nabla2Jt = T_Algo::Dr_rDr_over_r(Jt, r, dr, coefs_r, n_coefs_r, i, j, 0, 0) + + T_Algo::Dzz(Jt, coefs_z, n_coefs_z, i, j, 0, 0) - Jt(i, j, 0)/(r*r); - // Note: Hyper-resisitivity should be revisited here when modal decomposition is implemented + Et(i, j, 0) -= eta_h(rho_val, btot_val) * nabla2Jt; + } + } + + if (include_external_fields && (rho_val >= rho_floor)) { + Et(i, j, 0) -= Et_ext(i, j, 0); + } }, // Ez calculation [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/){ - // Skip field solve if this cell is fully covered by embedded boundaries - if (lz && lz(i,j,0) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Ez_arr && update_Ez_arr(i, j, 0) == 0) { return; } // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Ez_stag, coarsen, i, j, 0, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jr_val = Interp(Jr, Jr_stag, Ez_stag, coarsen, i, j, 0, 0); - const Real jt_val = Interp(Jt, Jt_stag, Ez_stag, coarsen, i, j, 0, 0); - const Real jz_val = Interp(Jz, Jz_stag, Ez_stag, coarsen, i, j, 0, 0); - jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Ez_stag, coarsen, i, j, 0, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Ez(i, j, 0) = 0._rt; + } else { + // Get the gradient of the electron pressure if the longitudinal part of + // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 + const Real grad_Pe = (!solve_for_Faraday) ? + T_Algo::UpwardDz(Pe, coefs_z, n_coefs_z, i, j, 0, 0) + : 0._rt; - // Get the gradient of the electron pressure if the longitudinal part of - // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 - Real grad_Pe = 0._rt; - if (!solve_for_Faraday) { grad_Pe = T_Algo::UpwardDz(Pe, coefs_z, n_coefs_z, i, j, 0, 0); } + // interpolate the nodal neE values to the Yee grid + const auto enE_z = Interp(enE, nodal, Ez_stag, coarsen, i, j, 0, 2); - // interpolate the nodal neE values to the Yee grid - auto enE_z = Interp(enE, nodal, Ez_stag, coarsen, i, j, 0, 2); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Ez(i, j, 0) = (enE_z - grad_Pe) / rho_val; + Ez(i, j, 0) = (enE_z - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Ez(i, j, 0) += eta(rho_val, jtot_val) * Jz(i, j, 0); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if (resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jr_val = Interp(Jr, Jr_stag, Ez_stag, coarsen, i, j, 0, 0); + const Real jt_val = Interp(Jt, Jt_stag, Ez_stag, coarsen, i, j, 0, 0); + const Real jz_val = Jz(i, j, 0); + jtot_val = std::sqrt(jr_val*jr_val + jt_val*jt_val + jz_val*jz_val); + } + + Ez(i, j, 0) += eta(rho_val, jtot_val) * Jz(i, j, 0); + + if (include_hyper_resistivity_term) { + + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real br_val = Interp(Br, Br_stag, Ez_stag, coarsen, i, j, 0, 0); + const Real bt_val = Interp(Bt, Bt_stag, Ez_stag, coarsen, i, j, 0, 0); + const Real bz_val = Interp(Bz, Bz_stag, Ez_stag, coarsen, i, j, 0, 0); + btot_val = std::sqrt(br_val*br_val + bt_val*bt_val + bz_val*bz_val); + } + + // r on nodal point (Jz is nodal in r) + const Real r = rmin + i*dr; - if (include_hyper_resistivity_term) { - auto nabla2Jz = T_Algo::Dzz(Jz, coefs_z, n_coefs_z, i, j, 0, 0); - Ez(i, j, 0) -= eta_h * nabla2Jz; + auto nabla2Jz = T_Algo::Dzz(Jz, coefs_z, n_coefs_z, i, j, 0, 0); + if (r > 0.5_rt*dr) { + nabla2Jz += T_Algo::Dr_rDr_over_r(Jz, r, dr, coefs_r, n_coefs_r, i, j, 0, 0); + } + + Ez(i, j, 0) -= eta_h(rho_val, btot_val) * nabla2Jz; + } + } + + if (include_external_fields && (rho_val >= rho_floor)) { + Ez(i, j, 0) -= Ez_ext(i, j, 0); } } ); @@ -705,7 +833,7 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( ablastr::fields::VectorField const& Bfield, amrex::MultiFab const& rhofield, amrex::MultiFab const& Pefield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, int lev, HybridPICModel const* hybrid_model, const bool solve_for_Faraday ) { @@ -719,8 +847,19 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( const auto eta_h = hybrid_model->m_eta_h; const auto rho_floor = hybrid_model->m_n_floor * PhysConst::q_e; const auto resistivity_has_J_dependence = hybrid_model->m_resistivity_has_J_dependence; + const auto hyper_resistivity_has_B_dependence = hybrid_model->m_hyper_resistivity_has_B_dependence; + const bool include_hyper_resistivity_term = hybrid_model->m_include_hyper_resistivity_term; + + const bool include_external_fields = hybrid_model->m_add_external_fields; - const bool include_hyper_resistivity_term = (eta_h > 0.) && solve_for_Faraday; + const bool holmstrom_vacuum_region = hybrid_model->m_holmstrom_vacuum_region; + + auto & warpx = WarpX::GetInstance(); + ablastr::fields::VectorField Bfield_external, Efield_external; + if (include_external_fields) { + Bfield_external = warpx.m_fields.get_alldirs(FieldType::hybrid_B_fp_external, 0); // lev=0 + Efield_external = warpx.m_fields.get_alldirs(FieldType::hybrid_E_fp_external, 0); // lev=0 + } // Index type required for interpolating fields from their respective // staggering to the Ex, Ey, Ez locations @@ -778,6 +917,13 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( Array4 const& By = Bfield[1]->const_array(mfi); Array4 const& Bz = Bfield[2]->const_array(mfi); + Array4 Bx_ext, By_ext, Bz_ext; + if (include_external_fields) { + Bx_ext = Bfield_external[0]->array(mfi); + By_ext = Bfield_external[1]->array(mfi); + Bz_ext = Bfield_external[2]->array(mfi); + } + // Loop over the cells and update the nodal E field amrex::ParallelFor(mfi.tilebox(), [=] AMREX_GPU_DEVICE (int i, int j, int k){ @@ -792,9 +938,15 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( auto const jiz_interp = Interp(Jiz, Jz_stag, nodal, coarsen, i, j, k, 0); // interpolate the B field to a nodal grid - auto const Bx_interp = Interp(Bx, Bx_stag, nodal, coarsen, i, j, k, 0); - auto const By_interp = Interp(By, By_stag, nodal, coarsen, i, j, k, 0); - auto const Bz_interp = Interp(Bz, Bz_stag, nodal, coarsen, i, j, k, 0); + auto Bx_interp = Interp(Bx, Bx_stag, nodal, coarsen, i, j, k, 0); + auto By_interp = Interp(By, By_stag, nodal, coarsen, i, j, k, 0); + auto Bz_interp = Interp(Bz, Bz_stag, nodal, coarsen, i, j, k, 0); + + if (include_external_fields) { + Bx_interp += Interp(Bx_ext, Bx_stag, nodal, coarsen, i, j, k, 0); + By_interp += Interp(By_ext, By_stag, nodal, coarsen, i, j, k, 0); + Bz_interp += Interp(Bz_ext, Bz_stag, nodal, coarsen, i, j, k, 0); + } // calculate enE = (J - Ji) x B enE_nodal(i, j, k, 0) = ( @@ -841,12 +993,24 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( Array4 const& enE = enE_nodal_mf.const_array(mfi); Array4 const& rho = rhofield.const_array(mfi); Array4 const& Pe = Pefield.array(mfi); + Array4 const& Bx = Bfield[0]->array(mfi); + Array4 const& By = Bfield[1]->array(mfi); + Array4 const& Bz = Bfield[2]->array(mfi); - amrex::Array4 lx, ly, lz; + // Extract structures indicating where the fields + // should be updated, given the position of the embedded boundaries + amrex::Array4 update_Ex_arr, update_Ey_arr, update_Ez_arr; if (EB::enabled()) { - lx = edge_lengths[0]->array(mfi); - ly = edge_lengths[1]->array(mfi); - lz = edge_lengths[2]->array(mfi); + update_Ex_arr = eb_update_E[0]->array(mfi); + update_Ey_arr = eb_update_E[1]->array(mfi); + update_Ez_arr = eb_update_E[2]->array(mfi); + } + + Array4 Ex_ext, Ey_ext, Ez_ext; + if (include_external_fields) { + Ex_ext = Efield_external[0]->array(mfi); + Ey_ext = Efield_external[1]->array(mfi); + Ez_ext = Efield_external[2]->array(mfi); } // Extract stencil coefficients @@ -866,124 +1030,193 @@ void FiniteDifferenceSolver::HybridPICSolveECartesian ( // Ex calculation [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip if this cell is fully covered by embedded boundaries - if (lx && lx(i, j, k) <= 0) { return; } + + // Skip field update in the embedded boundaries + if (update_Ex_arr && update_Ex_arr(i, j, k) == 0) { return; } // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Ex_stag, coarsen, i, j, k, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jx_val = Interp(Jx, Jx_stag, Ex_stag, coarsen, i, j, k, 0); - const Real jy_val = Interp(Jy, Jy_stag, Ex_stag, coarsen, i, j, k, 0); - const Real jz_val = Interp(Jz, Jz_stag, Ex_stag, coarsen, i, j, k, 0); - jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Ex_stag, coarsen, i, j, k, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Ex(i, j, k) = 0._rt; + } else { + // Get the gradient of the electron pressure if the longitudinal part of + // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 + const Real grad_Pe = (!solve_for_Faraday) ? + T_Algo::UpwardDx(Pe, coefs_x, n_coefs_x, i, j, k) + : 0._rt; - // Get the gradient of the electron pressure if the longitudinal part of - // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 - Real grad_Pe = 0._rt; - if (!solve_for_Faraday) { grad_Pe = T_Algo::UpwardDx(Pe, coefs_x, n_coefs_x, i, j, k); } + // interpolate the nodal neE values to the Yee grid + const auto enE_x = Interp(enE, nodal, Ex_stag, coarsen, i, j, k, 0); - // interpolate the nodal neE values to the Yee grid - auto enE_x = Interp(enE, nodal, Ex_stag, coarsen, i, j, k, 0); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Ex(i, j, k) = (enE_x - grad_Pe) / rho_val; + Ex(i, j, k) = (enE_x - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Ex(i, j, k) += eta(rho_val, jtot_val) * Jx(i, j, k); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if (resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jx_val = Jx(i, j, k); + const Real jy_val = Interp(Jy, Jy_stag, Ex_stag, coarsen, i, j, k, 0); + const Real jz_val = Interp(Jz, Jz_stag, Ex_stag, coarsen, i, j, k, 0); + jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); + } + + Ex(i, j, k) += eta(rho_val, jtot_val) * Jx(i, j, k); + + if (include_hyper_resistivity_term) { + + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real bx_val = Interp(Bx, Bx_stag, Ex_stag, coarsen, i, j, k, 0); + const Real by_val = Interp(By, By_stag, Ex_stag, coarsen, i, j, k, 0); + const Real bz_val = Interp(Bz, Bz_stag, Ex_stag, coarsen, i, j, k, 0); + btot_val = std::sqrt(bx_val*bx_val + by_val*by_val + bz_val*bz_val); + } + + auto nabla2Jx = T_Algo::Dxx(Jx, coefs_x, n_coefs_x, i, j, k) + + T_Algo::Dyy(Jx, coefs_y, n_coefs_y, i, j, k) + + T_Algo::Dzz(Jx, coefs_z, n_coefs_z, i, j, k); - if (include_hyper_resistivity_term) { - auto nabla2Jx = T_Algo::Dxx(Jx, coefs_x, n_coefs_x, i, j, k); - Ex(i, j, k) -= eta_h * nabla2Jx; + Ex(i, j, k) -= eta_h(rho_val, btot_val) * nabla2Jx; + } + } + + if (include_external_fields && (rho_val >= rho_floor)) { + Ex(i, j, k) -= Ex_ext(i, j, k); } }, // Ey calculation [=] AMREX_GPU_DEVICE (int i, int j, int k) { - // Skip field solve if this cell is fully covered by embedded boundaries -#ifdef WARPX_DIM_3D - if (ly && ly(i,j,k) <= 0) { return; } -#elif defined(WARPX_DIM_XZ) - //In XZ Ey is associated with a mesh node, so we need to check if the mesh node is covered - amrex::ignore_unused(ly); - if (lx && (lx(i, j, k)<=0 || lx(i-1, j, k)<=0 || lz(i, j-1, k)<=0 || lz(i, j, k)<=0)) { return; } -#endif + + // Skip field update in the embedded boundaries + if (update_Ey_arr && update_Ey_arr(i, j, k) == 0) { return; } + // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Ey_stag, coarsen, i, j, k, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jx_val = Interp(Jx, Jx_stag, Ey_stag, coarsen, i, j, k, 0); - const Real jy_val = Interp(Jy, Jy_stag, Ey_stag, coarsen, i, j, k, 0); - const Real jz_val = Interp(Jz, Jz_stag, Ey_stag, coarsen, i, j, k, 0); - jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Ey_stag, coarsen, i, j, k, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Ey(i, j, k) = 0._rt; + } else { + // Get the gradient of the electron pressure if the longitudinal part of + // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 + const Real grad_Pe = (!solve_for_Faraday) ? + T_Algo::UpwardDy(Pe, coefs_y, n_coefs_y, i, j, k) + : 0._rt; - // Get the gradient of the electron pressure if the longitudinal part of - // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 - Real grad_Pe = 0._rt; - if (!solve_for_Faraday) { grad_Pe = T_Algo::UpwardDy(Pe, coefs_y, n_coefs_y, i, j, k); } + // interpolate the nodal neE values to the Yee grid + const auto enE_y = Interp(enE, nodal, Ey_stag, coarsen, i, j, k, 1); - // interpolate the nodal neE values to the Yee grid - auto enE_y = Interp(enE, nodal, Ey_stag, coarsen, i, j, k, 1); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Ey(i, j, k) = (enE_y - grad_Pe) / rho_val; + Ey(i, j, k) = (enE_y - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Ey(i, j, k) += eta(rho_val, jtot_val) * Jy(i, j, k); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if (resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jx_val = Interp(Jx, Jx_stag, Ey_stag, coarsen, i, j, k, 0); + const Real jy_val = Jy(i, j, k); + const Real jz_val = Interp(Jz, Jz_stag, Ey_stag, coarsen, i, j, k, 0); + jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); + } + + Ey(i, j, k) += eta(rho_val, jtot_val) * Jy(i, j, k); + + if (include_hyper_resistivity_term) { - if (include_hyper_resistivity_term) { - auto nabla2Jy = T_Algo::Dyy(Jy, coefs_y, n_coefs_y, i, j, k); - Ey(i, j, k) -= eta_h * nabla2Jy; + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real bx_val = Interp(Bx, Bx_stag, Ey_stag, coarsen, i, j, k, 0); + const Real by_val = Interp(By, By_stag, Ey_stag, coarsen, i, j, k, 0); + const Real bz_val = Interp(Bz, Bz_stag, Ey_stag, coarsen, i, j, k, 0); + btot_val = std::sqrt(bx_val*bx_val + by_val*by_val + bz_val*bz_val); + } + + auto nabla2Jy = T_Algo::Dxx(Jy, coefs_x, n_coefs_x, i, j, k) + + T_Algo::Dyy(Jy, coefs_y, n_coefs_y, i, j, k) + + T_Algo::Dzz(Jy, coefs_z, n_coefs_z, i, j, k); + + Ey(i, j, k) -= eta_h(rho_val, btot_val) * nabla2Jy; + } + } + + if (include_external_fields && (rho_val >= rho_floor)) { + Ey(i, j, k) -= Ey_ext(i, j, k); } }, // Ez calculation [=] AMREX_GPU_DEVICE (int i, int j, int k){ -#ifdef AMREX_USE_EB - // Skip field solve if this cell is fully covered by embedded boundaries - if (lz && lz(i,j,k) <= 0) { return; } -#endif + + // Skip field update in the embedded boundaries + if (update_Ez_arr && update_Ez_arr(i, j, k) == 0) { return; } + // Interpolate to get the appropriate charge density in space - Real rho_val = Interp(rho, nodal, Ez_stag, coarsen, i, j, k, 0); - - // Interpolate current to appropriate staggering to match E field - Real jtot_val = 0._rt; - if (solve_for_Faraday && resistivity_has_J_dependence) { - const Real jx_val = Interp(Jx, Jx_stag, Ez_stag, coarsen, i, j, k, 0); - const Real jy_val = Interp(Jy, Jy_stag, Ez_stag, coarsen, i, j, k, 0); - const Real jz_val = Interp(Jz, Jz_stag, Ez_stag, coarsen, i, j, k, 0); - jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); - } + const Real rho_val = Interp(rho, nodal, Ez_stag, coarsen, i, j, k, 0); - // safety condition since we divide by rho_val later - if (rho_val < rho_floor) { rho_val = rho_floor; } + if (rho_val < rho_floor && holmstrom_vacuum_region) { + Ez(i, j, k) = 0._rt; + } else { + // Get the gradient of the electron pressure if the longitudinal part of + // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 + const Real grad_Pe = (!solve_for_Faraday) ? + T_Algo::UpwardDz(Pe, coefs_z, n_coefs_z, i, j, k) + : 0._rt; - // Get the gradient of the electron pressure if the longitudinal part of - // the E-field should be included, otherwise ignore it since curl x (grad Pe) = 0 - Real grad_Pe = 0._rt; - if (!solve_for_Faraday) { grad_Pe = T_Algo::UpwardDz(Pe, coefs_z, n_coefs_z, i, j, k); } + // interpolate the nodal neE values to the Yee grid + const auto enE_z = Interp(enE, nodal, Ez_stag, coarsen, i, j, k, 2); - // interpolate the nodal neE values to the Yee grid - auto enE_z = Interp(enE, nodal, Ez_stag, coarsen, i, j, k, 2); + // safety condition since we divide by rho + const auto rho_val_limited = std::max(rho_val, rho_floor); - Ez(i, j, k) = (enE_z - grad_Pe) / rho_val; + Ez(i, j, k) = (enE_z - grad_Pe) / rho_val_limited; + } // Add resistivity only if E field value is used to update B - if (solve_for_Faraday) { Ez(i, j, k) += eta(rho_val, jtot_val) * Jz(i, j, k); } + if (solve_for_Faraday) { + Real jtot_val = 0._rt; + if (resistivity_has_J_dependence) { + // Interpolate current to appropriate staggering to match E field + const Real jx_val = Interp(Jx, Jx_stag, Ez_stag, coarsen, i, j, k, 0); + const Real jy_val = Interp(Jy, Jy_stag, Ez_stag, coarsen, i, j, k, 0); + const Real jz_val = Jz(i, j, k); + jtot_val = std::sqrt(jx_val*jx_val + jy_val*jy_val + jz_val*jz_val); + } + + Ez(i, j, k) += eta(rho_val, jtot_val) * Jz(i, j, k); + + if (include_hyper_resistivity_term) { + + // Interpolate B field to appropriate staggering to match E field + Real btot_val = 0._rt; + if (hyper_resistivity_has_B_dependence) { + const Real bx_val = Interp(Bx, Bx_stag, Ez_stag, coarsen, i, j, k, 0); + const Real by_val = Interp(By, By_stag, Ez_stag, coarsen, i, j, k, 0); + const Real bz_val = Interp(Bz, Bz_stag, Ez_stag, coarsen, i, j, k, 0); + btot_val = std::sqrt(bx_val*bx_val + by_val*by_val + bz_val*bz_val); + } + + auto nabla2Jz = T_Algo::Dxx(Jz, coefs_x, n_coefs_x, i, j, k) + + T_Algo::Dyy(Jz, coefs_y, n_coefs_y, i, j, k) + + T_Algo::Dzz(Jz, coefs_z, n_coefs_z, i, j, k); + + Ez(i, j, k) -= eta_h(rho_val, btot_val) * nabla2Jz; + } + } - if (include_hyper_resistivity_term) { - auto nabla2Jz = T_Algo::Dzz(Jz, coefs_z, n_coefs_z, i, j, k); - Ez(i, j, k) -= eta_h * nabla2Jz; + if (include_external_fields && (rho_val >= rho_floor)) { + Ez(i, j, k) -= Ez_ext(i, j, k); } } ); diff --git a/Source/FieldSolver/FiniteDifferenceSolver/MacroscopicEvolveE.cpp b/Source/FieldSolver/FiniteDifferenceSolver/MacroscopicEvolveE.cpp index 708728c4e5b..33d368925f7 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/MacroscopicEvolveE.cpp +++ b/Source/FieldSolver/FiniteDifferenceSolver/MacroscopicEvolveE.cpp @@ -40,7 +40,7 @@ void FiniteDifferenceSolver::MacroscopicEvolveE ( ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real const dt, std::unique_ptr const& macroscopic_properties) { @@ -48,7 +48,7 @@ void FiniteDifferenceSolver::MacroscopicEvolveE ( // Select algorithm (The choice of algorithm is a runtime option, // but we compile code for each algorithm, using templates) #ifdef WARPX_DIM_RZ - amrex::ignore_unused(Efield, Bfield, Jfield, edge_lengths, dt, macroscopic_properties); + amrex::ignore_unused(Efield, Bfield, Jfield, eb_update_E, dt, macroscopic_properties); WARPX_ABORT_WITH_MESSAGE("currently macro E-push does not work for RZ"); #else @@ -61,13 +61,13 @@ void FiniteDifferenceSolver::MacroscopicEvolveE ( if (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::LaxWendroff) { MacroscopicEvolveECartesian - ( Efield, Bfield, Jfield, edge_lengths, dt, macroscopic_properties); + ( Efield, Bfield, Jfield, eb_update_E, dt, macroscopic_properties); } if (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::BackwardEuler) { MacroscopicEvolveECartesian - ( Efield, Bfield, Jfield, edge_lengths, dt, macroscopic_properties); + ( Efield, Bfield, Jfield, eb_update_E, dt, macroscopic_properties); } @@ -78,12 +78,12 @@ void FiniteDifferenceSolver::MacroscopicEvolveE ( if (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::LaxWendroff) { MacroscopicEvolveECartesian - ( Efield, Bfield, Jfield, edge_lengths, dt, macroscopic_properties); + ( Efield, Bfield, Jfield, eb_update_E, dt, macroscopic_properties); } else if (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::BackwardEuler) { MacroscopicEvolveECartesian - ( Efield, Bfield, Jfield, edge_lengths, dt, macroscopic_properties); + ( Efield, Bfield, Jfield, eb_update_E, dt, macroscopic_properties); } @@ -103,14 +103,10 @@ void FiniteDifferenceSolver::MacroscopicEvolveECartesian ( ablastr::fields::VectorField const& Efield, ablastr::fields::VectorField const& Bfield, ablastr::fields::VectorField const& Jfield, - ablastr::fields::VectorField const& edge_lengths, + std::array< std::unique_ptr,3 > const& eb_update_E, amrex::Real const dt, std::unique_ptr const& macroscopic_properties) { -#ifndef AMREX_USE_EB - amrex::ignore_unused(edge_lengths); -#endif - amrex::MultiFab& sigma_mf = macroscopic_properties->getsigma_mf(); amrex::MultiFab& epsilon_mf = macroscopic_properties->getepsilon_mf(); amrex::MultiFab& mu_mf = macroscopic_properties->getmu_mf(); @@ -141,15 +137,12 @@ void FiniteDifferenceSolver::MacroscopicEvolveECartesian ( Array4 const& jy = Jfield[1]->array(mfi); Array4 const& jz = Jfield[2]->array(mfi); - amrex::Array4 eb_lx, eb_ly, eb_lz; + amrex::Array4 update_Ex_arr, update_Ey_arr, update_Ez_arr; if (EB::enabled()) { - eb_lx = edge_lengths[0]->array(mfi); - eb_ly = edge_lengths[1]->array(mfi); - eb_lz = edge_lengths[2]->array(mfi); + update_Ex_arr = eb_update_E[0]->array(mfi); + update_Ey_arr = eb_update_E[1]->array(mfi); + update_Ez_arr = eb_update_E[2]->array(mfi); } -#ifdef WARPX_DIM_XZ - amrex::ignore_unused(eb_ly); -#endif // material prop // amrex::Array4 const& sigma_arr = sigma_mf.array(mfi); @@ -180,8 +173,9 @@ void FiniteDifferenceSolver::MacroscopicEvolveECartesian ( // Loop over the cells and update the fields amrex::ParallelFor(tex, tey, tez, [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip field push if this cell is fully covered by embedded boundaries - if (eb_lx && eb_lx(i, j, k) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Ex_arr && update_Ex_arr(i, j, k) == 0) { return; } // Interpolate conductivity, sigma, to Ex position on the grid amrex::Real const sigma_interp = ablastr::coarsen::sample::Interp(sigma_arr, sigma_stag, @@ -198,12 +192,9 @@ void FiniteDifferenceSolver::MacroscopicEvolveECartesian ( }, [=] AMREX_GPU_DEVICE (int i, int j, int k){ -#ifdef WARPX_DIM_3D - if (eb_ly && eb_ly(i,j,k) <= 0) { return; } -#elif defined(WARPX_DIM_XZ) - //In XZ Ey is associated with a mesh node, so we need to check if the mesh node is covered - if (eb_lx && (eb_lx(i, j, k)<=0 || eb_lx(i-1, j, k)<=0 || eb_lz(i, j, k)<=0 || eb_lz(i, j-1, k)<=0)) { return; } -#endif + + // Skip field push in the embedded boundaries + if (update_Ey_arr && update_Ey_arr(i, j, k) == 0) { return; } // Interpolate conductivity, sigma, to Ey position on the grid amrex::Real const sigma_interp = ablastr::coarsen::sample::Interp(sigma_arr, sigma_stag, @@ -221,8 +212,9 @@ void FiniteDifferenceSolver::MacroscopicEvolveECartesian ( }, [=] AMREX_GPU_DEVICE (int i, int j, int k){ - // Skip field push if this cell is fully covered by embedded boundaries - if (eb_lz && eb_lz(i, j, k) <= 0) { return; } + + // Skip field push in the embedded boundaries + if (update_Ez_arr && update_Ez_arr(i, j, k) == 0) { return; } // Interpolate conductivity, sigma, to Ez position on the grid amrex::Real const sigma_interp = ablastr::coarsen::sample::Interp(sigma_arr, sigma_stag, diff --git a/Source/FieldSolver/FiniteDifferenceSolver/Make.package b/Source/FieldSolver/FiniteDifferenceSolver/Make.package index b3708c411fa..bc71b9b51a2 100644 --- a/Source/FieldSolver/FiniteDifferenceSolver/Make.package +++ b/Source/FieldSolver/FiniteDifferenceSolver/Make.package @@ -5,6 +5,7 @@ CEXE_sources += EvolveF.cpp CEXE_sources += EvolveG.cpp CEXE_sources += EvolveECTRho.cpp CEXE_sources += ComputeDivE.cpp +CEXE_sources += ComputeCurlA.cpp CEXE_sources += MacroscopicEvolveE.cpp CEXE_sources += EvolveBPML.cpp CEXE_sources += EvolveEPML.cpp diff --git a/Source/FieldSolver/ImplicitSolvers/CMakeLists.txt b/Source/FieldSolver/ImplicitSolvers/CMakeLists.txt index 6e16f19084c..529336c4d7c 100644 --- a/Source/FieldSolver/ImplicitSolvers/CMakeLists.txt +++ b/Source/FieldSolver/ImplicitSolvers/CMakeLists.txt @@ -2,8 +2,10 @@ foreach(D IN LISTS WarpX_DIMS) warpx_set_suffix_dims(SD ${D}) target_sources(lib_${SD} PRIVATE + ImplicitSolver.cpp SemiImplicitEM.cpp ThetaImplicitEM.cpp + StrangImplicitSpectralEM.cpp WarpXImplicitOps.cpp WarpXSolverVec.cpp ) diff --git a/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.H b/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.H index 88ad6a058fd..0d2083793ac 100644 --- a/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.H +++ b/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.H @@ -1,4 +1,4 @@ -/* Copyright 2024 Justin Angus +/* Copyright 2024 Justin Angus, Debojyoti Ghosh * * This file is part of WarpX. * @@ -9,9 +9,11 @@ #include "FieldSolver/ImplicitSolvers/WarpXSolverVec.H" #include "NonlinearSolvers/NonlinearSolverLibrary.H" +#include "Utils/WarpXAlgorithmSelection.H" #include #include +#include /** * \brief Base class for implicit time solvers. The base functions are those @@ -55,6 +57,8 @@ public: a_particle_tol = m_particle_tolerance; } + void CreateParticleAttributes () const; + /** * \brief Advance fields and particles by one time step using the specified implicit algorithm */ @@ -81,10 +85,17 @@ public: virtual void ComputeRHS ( WarpXSolverVec& a_RHS, const WarpXSolverVec& a_E, amrex::Real a_time, - amrex::Real a_dt, int a_nl_iter, bool a_from_jacobian ) = 0; + [[nodiscard]] int numAMRLevels () const { return m_num_amr_levels; } + + [[nodiscard]] const amrex::Geometry& GetGeometry (int) const; + [[nodiscard]] const amrex::Array& GetFieldBoundaryLo () const; + [[nodiscard]] const amrex::Array& GetFieldBoundaryHi () const; + [[nodiscard]] amrex::Array GetLinOpBCLo () const; + [[nodiscard]] amrex::Array GetLinOpBCHi () const; + protected: /** @@ -94,6 +105,16 @@ protected: bool m_is_defined = false; + /** + * \brief Number of AMR levels + */ + int m_num_amr_levels = 1; + + /** + * \brief Time step + */ + mutable amrex::Real m_dt = 0.0; + /** * \brief Nonlinear solver type and object */ @@ -140,6 +161,11 @@ protected: } + /** + * \brief Convert from WarpX FieldBoundaryType to amrex::LinOpBCType + */ + [[nodiscard]] amrex::Array convertFieldBCToLinOpBC ( const amrex::Array& ) const; + }; #endif diff --git a/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.cpp b/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.cpp new file mode 100644 index 00000000000..0a934693710 --- /dev/null +++ b/Source/FieldSolver/ImplicitSolvers/ImplicitSolver.cpp @@ -0,0 +1,86 @@ +#include "ImplicitSolver.H" +#include "WarpX.H" +#include "Particles/MultiParticleContainer.H" + +using namespace amrex; + +void ImplicitSolver::CreateParticleAttributes () const +{ + // Set comm to false to that the attributes are not communicated + // nor written to the checkpoint files + int const comm = 0; + + // Add space to save the positions and velocities at the start of the time steps + for (auto const& pc : m_WarpX->GetPartContainer()) { +#if (AMREX_SPACEDIM >= 2) + pc->AddRealComp("x_n", comm); +#endif +#if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) + pc->AddRealComp("y_n", comm); +#endif + pc->AddRealComp("z_n", comm); + pc->AddRealComp("ux_n", comm); + pc->AddRealComp("uy_n", comm); + pc->AddRealComp("uz_n", comm); + } +} + +const Geometry& ImplicitSolver::GetGeometry (const int a_lvl) const +{ + AMREX_ASSERT((a_lvl >= 0) && (a_lvl < m_num_amr_levels)); + return m_WarpX->Geom(a_lvl); +} + +const Array& ImplicitSolver::GetFieldBoundaryLo () const +{ + return m_WarpX->GetFieldBoundaryLo(); +} + +const Array& ImplicitSolver::GetFieldBoundaryHi () const +{ + return m_WarpX->GetFieldBoundaryHi(); +} + +Array ImplicitSolver::GetLinOpBCLo () const +{ + return convertFieldBCToLinOpBC(m_WarpX->GetFieldBoundaryLo()); +} + +Array ImplicitSolver::GetLinOpBCHi () const +{ + return convertFieldBCToLinOpBC(m_WarpX->GetFieldBoundaryHi()); +} + +Array ImplicitSolver::convertFieldBCToLinOpBC (const Array& a_fbc) const +{ + Array lbc; + for (auto& bc : lbc) { bc = LinOpBCType::interior; } + for (int i = 0; i < AMREX_SPACEDIM; i++) { + if (a_fbc[i] == FieldBoundaryType::PML) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else if (a_fbc[i] == FieldBoundaryType::Periodic) { + lbc[i] = LinOpBCType::Periodic; + } else if (a_fbc[i] == FieldBoundaryType::PEC) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else if (a_fbc[i] == FieldBoundaryType::Damped) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else if (a_fbc[i] == FieldBoundaryType::Absorbing_SilverMueller) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else if (a_fbc[i] == FieldBoundaryType::Neumann) { + // Also for FieldBoundaryType::PMC + lbc[i] = LinOpBCType::symmetry; + } else if (a_fbc[i] == FieldBoundaryType::PECInsulator) { + ablastr::warn_manager::WMRecordWarning("Implicit solver", + "With PECInsulator, in the Curl-Curl preconditioner Neumann boundary will be used since the full boundary is not yet implemented.", + ablastr::warn_manager::WarnPriority::medium); + lbc[i] = LinOpBCType::symmetry; + } else if (a_fbc[i] == FieldBoundaryType::None) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else if (a_fbc[i] == FieldBoundaryType::Open) { + WARPX_ABORT_WITH_MESSAGE("LinOpBCType not set for this FieldBoundaryType"); + } else { + WARPX_ABORT_WITH_MESSAGE("Invalid value for FieldBoundaryType"); + } + } + return lbc; +} diff --git a/Source/FieldSolver/ImplicitSolvers/ImplicitSolverLibrary.H b/Source/FieldSolver/ImplicitSolvers/ImplicitSolverLibrary.H index 423957ef061..586c7163742 100644 --- a/Source/FieldSolver/ImplicitSolvers/ImplicitSolverLibrary.H +++ b/Source/FieldSolver/ImplicitSolvers/ImplicitSolverLibrary.H @@ -9,5 +9,6 @@ #include "SemiImplicitEM.H" // IWYU pragma: export #include "ThetaImplicitEM.H" // IWYU pragma: export +#include "StrangImplicitSpectralEM.H" // IWYU pragma: export #endif diff --git a/Source/FieldSolver/ImplicitSolvers/Make.package b/Source/FieldSolver/ImplicitSolvers/Make.package index a4543f94dd3..8f39824d875 100644 --- a/Source/FieldSolver/ImplicitSolvers/Make.package +++ b/Source/FieldSolver/ImplicitSolvers/Make.package @@ -1,5 +1,7 @@ +CEXE_sources += ImplicitSolver.cpp CEXE_sources += SemiImplicitEM.cpp CEXE_sources += ThetaImplicitEM.cpp +CEXE_sources += StrangImplicitSpectralEM.cpp CEXE_sources += WarpXImplicitOps.cpp CEXE_sources += WarpXSolverVec.cpp diff --git a/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.H b/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.H index 6e3e5db2c74..62401d7b48f 100644 --- a/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.H +++ b/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.H @@ -57,14 +57,13 @@ public: void PrintParameters () const override; - void OneStep ( amrex::Real a_time, + void OneStep ( amrex::Real start_time, amrex::Real a_dt, int a_step ) override; void ComputeRHS ( WarpXSolverVec& a_RHS, const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt, + amrex::Real half_time, int a_nl_iter, bool a_from_jacobian ) override; diff --git a/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.cpp b/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.cpp index 2236118a30c..aae10b978ee 100644 --- a/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.cpp +++ b/Source/FieldSolver/ImplicitSolvers/SemiImplicitEM.cpp @@ -5,6 +5,7 @@ * License: BSD-3-Clause-LBNL */ #include "SemiImplicitEM.H" +#include "Diagnostics/ReducedDiags/MultiReducedDiags.H" #include "WarpX.H" using warpx::fields::FieldType; @@ -52,13 +53,16 @@ void SemiImplicitEM::PrintParameters () const amrex::Print() << "-----------------------------------------------------------\n\n"; } -void SemiImplicitEM::OneStep ( amrex::Real a_time, +void SemiImplicitEM::OneStep ( amrex::Real start_time, amrex::Real a_dt, int a_step ) { amrex::ignore_unused(a_step); - // Fields have Eg^{n}, Bg^{n-1/2} + // Set the member time step + m_dt = a_dt; + + // Fields have Eg^{n}, Bg^{n} // Particles have up^{n} and xp^{n}. // Save up and xp at the start of the time step @@ -67,19 +71,20 @@ void SemiImplicitEM::OneStep ( amrex::Real a_time, // Save Eg at the start of the time step m_Eold.Copy( FieldType::Efield_fp ); - // Advance WarpX owned Bfield_fp to t_{n+1/2} - m_WarpX->EvolveB(a_dt, DtType::Full); - m_WarpX->ApplyMagneticFieldBCs(); + // Advance WarpX owned Bfield_fp from t_{n} to t_{n+1/2} + m_WarpX->EvolveB(0.5_rt*m_dt, DtType::FirstHalf, start_time); + m_WarpX->FillBoundaryB(m_WarpX->getngEB(), true); - const amrex::Real half_time = a_time + 0.5_rt*a_dt; + const amrex::Real half_time = start_time + 0.5_rt*m_dt; // Solve nonlinear system for Eg at t_{n+1/2} // Particles will be advanced to t_{n+1/2} m_E.Copy(m_Eold); // initial guess for Eg^{n+1/2} - m_nlsolver->Solve( m_E, m_Eold, half_time, a_dt ); + m_nlsolver->Solve( m_E, m_Eold, half_time, 0.5_rt*m_dt, a_step ); // Update WarpX owned Efield_fp to t_{n+1/2} - m_WarpX->SetElectricFieldAndApplyBCs( m_E ); + m_WarpX->SetElectricFieldAndApplyBCs( m_E, half_time ); + m_WarpX->reduced_diags->ComputeDiagsMidStep(a_step); // Advance particles from time n+1/2 to time n+1 m_WarpX->FinishImplicitParticleUpdate(); @@ -87,25 +92,29 @@ void SemiImplicitEM::OneStep ( amrex::Real a_time, // Advance Eg from time n+1/2 to time n+1 // Eg^{n+1} = 2.0*Eg^{n+1/2} - Eg^n m_E.linComb( 2._rt, m_E, -1._rt, m_Eold ); - m_WarpX->SetElectricFieldAndApplyBCs( m_E ); + const amrex::Real new_time = start_time + m_dt; + m_WarpX->SetElectricFieldAndApplyBCs( m_E, new_time ); + + // Advance WarpX owned Bfield_fp from t_{n+1/2} to t_{n+1} + m_WarpX->EvolveB(0.5_rt*m_dt, DtType::SecondHalf, half_time); + m_WarpX->FillBoundaryB(m_WarpX->getngEB(), true); } void SemiImplicitEM::ComputeRHS ( WarpXSolverVec& a_RHS, const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt, + amrex::Real half_time, int a_nl_iter, bool a_from_jacobian ) { // Update WarpX-owned Efield_fp using current state of Eg from // the nonlinear solver at time n+theta - m_WarpX->SetElectricFieldAndApplyBCs( a_E ); + m_WarpX->SetElectricFieldAndApplyBCs( a_E, half_time ); // Update particle positions and velocities using the current state // of Eg and Bg. Deposit current density at time n+1/2 - m_WarpX->ImplicitPreRHSOp( a_time, a_dt, a_nl_iter, a_from_jacobian ); + m_WarpX->ImplicitPreRHSOp( half_time, m_dt, a_nl_iter, a_from_jacobian ); // RHS = cvac^2*0.5*dt*( curl(Bg^{n+1/2}) - mu0*Jg^{n+1/2} ) - m_WarpX->ImplicitComputeRHSE(0.5_rt*a_dt, a_RHS); + m_WarpX->ImplicitComputeRHSE(0.5_rt*m_dt, a_RHS); } diff --git a/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.H b/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.H new file mode 100644 index 00000000000..fcfcb9821a7 --- /dev/null +++ b/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.H @@ -0,0 +1,105 @@ +/* Copyright 2024 David Grote + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ +#ifndef STRANG_IMPLICIT_SPECTRALEM_H_ +#define STRANG_IMPLICIT_SPECTRALEM_H_ + +#include "FieldSolver/ImplicitSolvers/WarpXSolverVec.H" + +#include +#include +#include + +#include "ImplicitSolver.H" + +/** @file + * Implicit spectral electromagnetic time solver class. This is a fully implicit + * algorithm where both the fields and particles are treated implicitly. + * + * The time stencil is + * Advance (Eg^n, Bg^n) -> (Eg^{n+1/2}, Bg^{n+1/2}) source free // E transverse + * Iterate: + * Eg^{n+1} = Eg^n + c^2*dt*( - mu0*Jg^{n+1/2} ) // E longitudinal + * xp^{n+1} = xp^n + dt*up^{n+1/2}/(0.5*(gammap^n + gammap^{n+1})) + * up^{n+1} = up^n + dt*qp/mp*(Ep^{n+1/2} + up^{n+1/2}/gammap^{n+1/2} x Bp^{n+1/2}) + * Advance (Eg^n+1/2, Bg^n+1/2) -> (Eg^{n+1}, Bg^{n+1}) source free // E transverse + * + * The algorithm is exactly energy conserving only with a single box, periodic fft (psatd.periodic_single_box_fft = 1). + * With multiple boxes, energy is not conserved since the ffts in each box assumes periodic in the box which + * is not consistent with the current. + * The algorithm is numerially stable for any time step. + * I.e., the CFL condition for light waves does not + * have to be satisifed and the time step is not limited by the plasma period. However, how + * efficiently the algorithm can use large time steps depends strongly on the nonlinear solver. + * Furthermore, the time step should always be such that particles do not travel outside the + * ghost region of the box they live in, which is an MPI-related limitation. The time step + * is always limited by the need to resolve the appropriate physics. + * + */ + +class StrangImplicitSpectralEM : public ImplicitSolver +{ +public: + + StrangImplicitSpectralEM() = default; + + ~StrangImplicitSpectralEM() override = default; + + // Prohibit Move and Copy operations + StrangImplicitSpectralEM(const StrangImplicitSpectralEM&) = delete; + StrangImplicitSpectralEM& operator=(const StrangImplicitSpectralEM&) = delete; + StrangImplicitSpectralEM(StrangImplicitSpectralEM&&) = delete; + StrangImplicitSpectralEM& operator=(StrangImplicitSpectralEM&&) = delete; + + void Define ( WarpX* a_WarpX ) override; + + void PrintParameters () const override; + + void OneStep ( amrex::Real start_time, + amrex::Real a_dt, + int a_step ) override; + + void ComputeRHS ( WarpXSolverVec& a_RHS, + const WarpXSolverVec& a_E, + amrex::Real half_time, + int a_nl_iter, + bool a_from_jacobian ) override; + +private: + + /** + * \brief Solver vectors to be used in the nonlinear solver to solve for the + * electric field E. The main logic for determining which variables should be + * WarpXSolverVec type is that it must have the same size and have the same + * centering of the data as the variable being solved for, which is E here. + * For example, if using a Yee grid then a container for curlB could be a + * WarpXSovlerVec, but magnetic field B should not be. + */ + WarpXSolverVec m_E, m_Eold; + + /** + * \brief B is a derived variable from E. Need to save Bold to update B during + * the iterative nonlinear solve for E. Bold is owned here, but only used by WarpX. + * It is not used directly by the nonlinear solver, nor is it the same size as the + * solver vector (size E), and so it should not be WarpXSolverVec type. + */ + amrex::Vector, 3 > > m_Bold; + + /** + * \brief Update the E and B fields owned by WarpX + */ + void UpdateWarpXFields ( WarpXSolverVec const& a_E, + amrex::Real half_time ); + + /** + * \brief Nonlinear solver is for the time-centered values of E. After + * the solver, need to use m_E and m_Eold to compute E^{n+1} + */ + void FinishFieldUpdate ( amrex::Real a_new_time ); + +}; + +#endif diff --git a/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.cpp b/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.cpp new file mode 100644 index 00000000000..debbff1b35e --- /dev/null +++ b/Source/FieldSolver/ImplicitSolvers/StrangImplicitSpectralEM.cpp @@ -0,0 +1,141 @@ +/* Copyright 2024 David Grote + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ +#include "Fields.H" +#include "StrangImplicitSpectralEM.H" +#include "Diagnostics/ReducedDiags/MultiReducedDiags.H" +#include "WarpX.H" + +using namespace warpx::fields; +using namespace amrex::literals; + +void StrangImplicitSpectralEM::Define ( WarpX* const a_WarpX ) +{ + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + !m_is_defined, + "StrangImplicitSpectralEM object is already defined!"); + + // Retain a pointer back to main WarpX class + m_WarpX = a_WarpX; + + // Define E and Eold vectors + m_E.Define( m_WarpX, "Efield_fp" ); + m_Eold.Define( m_E ); + + + // Parse nonlinear solver parameters + const amrex::ParmParse pp_implicit_evolve("implicit_evolve"); + parseNonlinearSolverParams( pp_implicit_evolve ); + + // Define the nonlinear solver + m_nlsolver->Define(m_E, this); + m_is_defined = true; + +} + +void StrangImplicitSpectralEM::PrintParameters () const +{ + if (!m_WarpX->Verbose()) { return; } + amrex::Print() << "\n"; + amrex::Print() << "------------------------------------------------------------------------" << "\n"; + amrex::Print() << "----------- STRANG SPLIT IMPLICIT SPECTRAL EM SOLVER PARAMETERS --------" << "\n"; + amrex::Print() << "------------------------------------------------------------------------" << "\n"; + amrex::Print() << "max particle iterations: " << m_max_particle_iterations << "\n"; + amrex::Print() << "particle tolerance: " << m_particle_tolerance << "\n"; + if (m_nlsolver_type==NonlinearSolverType::Picard) { + amrex::Print() << "Nonlinear solver type: Picard\n"; + } + else if (m_nlsolver_type==NonlinearSolverType::Newton) { + amrex::Print() << "Nonlinear solver type: Newton\n"; + } + m_nlsolver->PrintParams(); + amrex::Print() << "-----------------------------------------------------------\n\n"; +} + +void StrangImplicitSpectralEM::OneStep ( amrex::Real start_time, + amrex::Real a_dt, + int a_step ) +{ + amrex::ignore_unused(a_step); + + // Fields have E^{n} and B^{n} + // Particles have p^{n} and x^{n}. + + // Set the member time step + m_dt = a_dt; + + // Save the values at the start of the time step, + m_WarpX->SaveParticlesAtImplicitStepStart(); + + // Advance the fields to time n+1/2 source free + m_WarpX->SpectralSourceFreeFieldAdvance(start_time); + + // Save the fields at the start of the step + m_Eold.Copy( FieldType::Efield_fp ); + m_E.Copy(m_Eold); // initial guess for E + + amrex::Real const half_time = start_time + 0.5_rt*m_dt; + + // Solve nonlinear system for E at t_{n+1/2} + // Particles will be advanced to t_{n+1/2} + m_nlsolver->Solve( m_E, m_Eold, half_time, 0.5_rt*m_dt, a_step ); + + // Update WarpX owned Efield_fp and Bfield_fp to t_{n+1/2} + UpdateWarpXFields( m_E, half_time ); + m_WarpX->reduced_diags->ComputeDiagsMidStep(a_step); + + // Advance particles from time n+1/2 to time n+1 + m_WarpX->FinishImplicitParticleUpdate(); + + // Advance E and B fields from time n+1/2 to time n+1 + amrex::Real const new_time = start_time + m_dt; + FinishFieldUpdate( new_time ); + + // Advance the fields to time n+1 source free + m_WarpX->SpectralSourceFreeFieldAdvance(half_time); + +} + +void StrangImplicitSpectralEM::ComputeRHS ( WarpXSolverVec& a_RHS, + WarpXSolverVec const & a_E, + amrex::Real half_time, + int a_nl_iter, + bool a_from_jacobian ) +{ + // Update WarpX-owned Efield_fp and Bfield_fp using current state of + // E from the nonlinear solver at time n+1/2 + UpdateWarpXFields( a_E, half_time ); + + // Self consistently update particle positions and velocities using the + // current state of the fields E and B. Deposit current density at time n+1/2. + m_WarpX->ImplicitPreRHSOp( half_time, m_dt, a_nl_iter, a_from_jacobian ); + + // For Strang split implicit PSATD, the RHS = -dt*mu*c**2*J + bool const allow_type_mismatch = true; + a_RHS.Copy(FieldType::current_fp, warpx::fields::FieldType::None, allow_type_mismatch); + amrex::Real constexpr coeff = PhysConst::c * PhysConst::c * PhysConst::mu0; + a_RHS.scale(-coeff * 0.5_rt*m_dt); + +} + +void StrangImplicitSpectralEM::UpdateWarpXFields (WarpXSolverVec const & a_E, + amrex::Real half_time ) +{ + + // Update Efield_fp owned by WarpX + m_WarpX->SetElectricFieldAndApplyBCs( a_E, half_time ); + +} + +void StrangImplicitSpectralEM::FinishFieldUpdate ( amrex::Real a_new_time ) +{ + // Eg^{n+1} = 2*E_g^{n+1/2} - E_g^n + amrex::Real const c0 = 1._rt/0.5_rt; + amrex::Real const c1 = 1._rt - c0; + m_E.linComb( c0, m_E, c1, m_Eold ); + m_WarpX->SetElectricFieldAndApplyBCs( m_E, a_new_time ); + +} diff --git a/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.H b/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.H index aba66782154..c9de6b82a00 100644 --- a/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.H +++ b/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.H @@ -8,13 +8,12 @@ #define THETA_IMPLICIT_EM_H_ #include "FieldSolver/ImplicitSolvers/WarpXSolverVec.H" +#include "ImplicitSolver.H" #include #include #include -#include "ImplicitSolver.H" - /** @file * Theta-implicit electromagnetic time solver class. This is a fully implicit * algorithm where both the fields and particles are treated implicitly. @@ -68,19 +67,23 @@ public: void PrintParameters () const override; - void OneStep ( amrex::Real a_time, + /** + * \brief Advances the simulation one time step + * + * \param[in] start_time The time at the start of the time step + * \param[in] a_dt The time step size + * \param[in] a_step The time step number + */ + void OneStep ( amrex::Real start_time, amrex::Real a_dt, int a_step ) override; void ComputeRHS ( WarpXSolverVec& a_RHS, const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt, + amrex::Real start_time, int a_nl_iter, bool a_from_jacobian ) override; - [[nodiscard]] amrex::Real theta () const { return m_theta; } - private: /** @@ -102,14 +105,13 @@ private: * \brief Update the E and B fields owned by WarpX */ void UpdateWarpXFields ( const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt ); + amrex::Real start_time ); /** * \brief Nonlinear solver is for the time-centered values of E. After * the solver, need to use m_E and m_Eold to compute E^{n+1} */ - void FinishFieldUpdate ( amrex::Real a_new_time ); + void FinishFieldUpdate ( amrex::Real end_time ); }; diff --git a/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.cpp b/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.cpp index 4cd5de4f24f..54644d357d2 100644 --- a/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.cpp +++ b/Source/FieldSolver/ImplicitSolvers/ThetaImplicitEM.cpp @@ -6,6 +6,7 @@ */ #include "Fields.H" #include "ThetaImplicitEM.H" +#include "Diagnostics/ReducedDiags/MultiReducedDiags.H" #include "WarpX.H" using warpx::fields::FieldType; @@ -19,6 +20,7 @@ void ThetaImplicitEM::Define ( WarpX* const a_WarpX ) // Retain a pointer back to main WarpX class m_WarpX = a_WarpX; + m_num_amr_levels = 1; // Define E and Eold vectors m_E.Define( m_WarpX, "Efield_fp" ); @@ -26,8 +28,7 @@ void ThetaImplicitEM::Define ( WarpX* const a_WarpX ) // Define B_old MultiFabs using ablastr::fields::Direction; - const int num_levels = 1; - for (int lev = 0; lev < num_levels; ++lev) { + for (int lev = 0; lev < m_num_amr_levels; ++lev) { const auto& ba_Bx = m_WarpX->m_fields.get(FieldType::Bfield_fp, Direction{0}, lev)->boxArray(); const auto& ba_By = m_WarpX->m_fields.get(FieldType::Bfield_fp, Direction{1}, lev)->boxArray(); const auto& ba_Bz = m_WarpX->m_fields.get(FieldType::Bfield_fp, Direction{2}, lev)->boxArray(); @@ -74,7 +75,7 @@ void ThetaImplicitEM::PrintParameters () const amrex::Print() << "-----------------------------------------------------------\n\n"; } -void ThetaImplicitEM::OneStep ( const amrex::Real a_time, +void ThetaImplicitEM::OneStep ( const amrex::Real start_time, const amrex::Real a_dt, const int a_step ) { @@ -83,6 +84,9 @@ void ThetaImplicitEM::OneStep ( const amrex::Real a_time, // Fields have Eg^{n} and Bg^{n} // Particles have up^{n} and xp^{n}. + // Set the member time step + m_dt = a_dt; + // Save up and xp at the start of the time step m_WarpX->SaveParticlesAtImplicitStepStart ( ); @@ -99,62 +103,59 @@ void ThetaImplicitEM::OneStep ( const amrex::Real a_time, } } - const amrex::Real theta_time = a_time + m_theta*a_dt; - // Solve nonlinear system for Eg at t_{n+theta} // Particles will be advanced to t_{n+1/2} m_E.Copy(m_Eold); // initial guess for Eg^{n+theta} - m_nlsolver->Solve( m_E, m_Eold, theta_time, a_dt ); + m_nlsolver->Solve( m_E, m_Eold, start_time, m_theta*m_dt, a_step ); // Update WarpX owned Efield_fp and Bfield_fp to t_{n+theta} - UpdateWarpXFields( m_E, theta_time, a_dt ); + UpdateWarpXFields( m_E, start_time ); + m_WarpX->reduced_diags->ComputeDiagsMidStep(a_step); // Advance particles from time n+1/2 to time n+1 m_WarpX->FinishImplicitParticleUpdate(); // Advance Eg and Bg from time n+theta to time n+1 - const amrex::Real new_time = a_time + a_dt; - FinishFieldUpdate( new_time ); + const amrex::Real end_time = start_time + m_dt; + FinishFieldUpdate( end_time ); } void ThetaImplicitEM::ComputeRHS ( WarpXSolverVec& a_RHS, const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt, + amrex::Real start_time, int a_nl_iter, bool a_from_jacobian ) { // Update WarpX-owned Efield_fp and Bfield_fp using current state of // Eg from the nonlinear solver at time n+theta - UpdateWarpXFields( a_E, a_time, a_dt ); + UpdateWarpXFields( a_E, start_time ); // Update particle positions and velocities using the current state // of Eg and Bg. Deposit current density at time n+1/2 - m_WarpX->ImplicitPreRHSOp( a_time, a_dt, a_nl_iter, a_from_jacobian ); + const amrex::Real theta_time = start_time + m_theta*m_dt; + m_WarpX->ImplicitPreRHSOp( theta_time, m_dt, a_nl_iter, a_from_jacobian ); // RHS = cvac^2*m_theta*dt*( curl(Bg^{n+theta}) - mu0*Jg^{n+1/2} ) - m_WarpX->ImplicitComputeRHSE(m_theta*a_dt, a_RHS); + m_WarpX->ImplicitComputeRHSE( m_theta*m_dt, a_RHS); } void ThetaImplicitEM::UpdateWarpXFields ( const WarpXSolverVec& a_E, - amrex::Real a_time, - amrex::Real a_dt ) + amrex::Real start_time ) { - amrex::ignore_unused(a_time); // Update Efield_fp owned by WarpX - m_WarpX->SetElectricFieldAndApplyBCs( a_E ); + const amrex::Real theta_time = start_time + m_theta*m_dt; + m_WarpX->SetElectricFieldAndApplyBCs( a_E, theta_time ); // Update Bfield_fp owned by WarpX ablastr::fields::MultiLevelVectorField const& B_old = m_WarpX->m_fields.get_mr_levels_alldirs(FieldType::B_old, 0); - m_WarpX->UpdateMagneticFieldAndApplyBCs(B_old, m_theta * a_dt ); + m_WarpX->UpdateMagneticFieldAndApplyBCs( B_old, m_theta*m_dt, start_time ); } -void ThetaImplicitEM::FinishFieldUpdate ( amrex::Real a_new_time ) +void ThetaImplicitEM::FinishFieldUpdate ( amrex::Real end_time ) { - amrex::ignore_unused(a_new_time); // Eg^{n+1} = (1/theta)*Eg^{n+theta} + (1-1/theta)*Eg^n // Bg^{n+1} = (1/theta)*Bg^{n+theta} + (1-1/theta)*Bg^n @@ -162,8 +163,8 @@ void ThetaImplicitEM::FinishFieldUpdate ( amrex::Real a_new_time ) const amrex::Real c0 = 1._rt/m_theta; const amrex::Real c1 = 1._rt - c0; m_E.linComb( c0, m_E, c1, m_Eold ); - m_WarpX->SetElectricFieldAndApplyBCs( m_E ); + m_WarpX->SetElectricFieldAndApplyBCs( m_E, end_time ); ablastr::fields::MultiLevelVectorField const & B_old = m_WarpX->m_fields.get_mr_levels_alldirs(FieldType::B_old, 0); - m_WarpX->FinishMagneticFieldAndApplyBCs(B_old, m_theta ); + m_WarpX->FinishMagneticFieldAndApplyBCs( B_old, m_theta, end_time ); } diff --git a/Source/FieldSolver/ImplicitSolvers/WarpXImplicitOps.cpp b/Source/FieldSolver/ImplicitSolvers/WarpXImplicitOps.cpp index 806c3412990..06e1820854c 100644 --- a/Source/FieldSolver/ImplicitSolvers/WarpXImplicitOps.cpp +++ b/Source/FieldSolver/ImplicitSolvers/WarpXImplicitOps.cpp @@ -52,8 +52,11 @@ WarpX::ImplicitPreRHSOp ( amrex::Real a_cur_time, bool a_from_jacobian ) { using namespace amrex::literals; + using warpx::fields::FieldType; amrex::ignore_unused( a_full_dt, a_nl_iter, a_from_jacobian ); + if (use_filter) { ApplyFilterMF(m_fields.get_mr_levels_alldirs(FieldType::Efield_fp, finest_level), 0); } + // Advance the particle positions by 1/2 dt, // particle velocities by dt, then take average of old and new v, // deposit currents, giving J at n+1/2 @@ -67,7 +70,7 @@ WarpX::ImplicitPreRHSOp ( amrex::Real a_cur_time, } void -WarpX::SetElectricFieldAndApplyBCs ( const WarpXSolverVec& a_E ) +WarpX::SetElectricFieldAndApplyBCs ( const WarpXSolverVec& a_E, amrex::Real a_time ) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( a_E.getArrayVecType()==warpx::fields::FieldType::Efield_fp, @@ -81,12 +84,12 @@ WarpX::SetElectricFieldAndApplyBCs ( const WarpXSolverVec& a_E ) amrex::MultiFab::Copy(*Efield_fp[0][1], *Evec[0][1], 0, 0, ncomps, Evec[0][1]->nGrowVect()); amrex::MultiFab::Copy(*Efield_fp[0][2], *Evec[0][2], 0, 0, ncomps, Evec[0][2]->nGrowVect()); FillBoundaryE(guard_cells.ng_alloc_EB, WarpX::sync_nodal_points); - ApplyEfieldBoundary(0, PatchType::fine); + ApplyEfieldBoundary(0, PatchType::fine, a_time); } void -WarpX::UpdateMagneticFieldAndApplyBCs( ablastr::fields::MultiLevelVectorField const& a_Bn, - amrex::Real a_thetadt ) +WarpX::UpdateMagneticFieldAndApplyBCs( ablastr::fields::MultiLevelVectorField const& a_Bn, + amrex::Real a_thetadt, amrex::Real start_time ) { using ablastr::fields::Direction; using warpx::fields::FieldType; @@ -97,25 +100,57 @@ WarpX::UpdateMagneticFieldAndApplyBCs( ablastr::fields::MultiLevelVectorField co amrex::MultiFab::Copy(*Bfp[1], *a_Bn[lev][1], 0, 0, ncomps, a_Bn[lev][1]->nGrowVect()); amrex::MultiFab::Copy(*Bfp[2], *a_Bn[lev][2], 0, 0, ncomps, a_Bn[lev][2]->nGrowVect()); } - EvolveB(a_thetadt, DtType::Full); - ApplyMagneticFieldBCs(); + EvolveB(a_thetadt, DtType::Full, start_time); + FillBoundaryB(guard_cells.ng_alloc_EB, WarpX::sync_nodal_points); } void -WarpX::FinishMagneticFieldAndApplyBCs( ablastr::fields::MultiLevelVectorField const& a_Bn, - amrex::Real a_theta ) +WarpX::FinishMagneticFieldAndApplyBCs( ablastr::fields::MultiLevelVectorField const& a_Bn, + amrex::Real a_theta, amrex::Real a_time ) { using warpx::fields::FieldType; FinishImplicitField(m_fields.get_mr_levels_alldirs(FieldType::Bfield_fp, 0), a_Bn, a_theta); - ApplyMagneticFieldBCs(); + ApplyBfieldBoundary(0, PatchType::fine, DtType::Full, a_time); + FillBoundaryB(guard_cells.ng_alloc_EB, WarpX::sync_nodal_points); } void -WarpX::ApplyMagneticFieldBCs() +WarpX::SpectralSourceFreeFieldAdvance (amrex::Real start_time) { + using namespace amrex::literals; + using warpx::fields::FieldType; + // Do the first piece of the Strang splitting, source free advance of E and B + // It would be more efficient to write a specialized PSATD advance that does not use J, + // but this works for now. + + // Create temporary MultiFabs to hold J + int const lev = 0; + ablastr::fields::VectorField current_fp = m_fields.get_alldirs(FieldType::current_fp, lev); + amrex::MultiFab* rho_fp = m_fields.get(FieldType::rho_fp, lev); + amrex::MultiFab j0(current_fp[0]->boxArray(), current_fp[0]->DistributionMap(), + current_fp[0]->nComp(), current_fp[0]->nGrowVect()); + amrex::MultiFab j1(current_fp[1]->boxArray(), current_fp[1]->DistributionMap(), + current_fp[1]->nComp(), current_fp[1]->nGrowVect()); + amrex::MultiFab j2(current_fp[2]->boxArray(), current_fp[2]->DistributionMap(), + current_fp[2]->nComp(), current_fp[2]->nGrowVect()); + amrex::MultiFab::Copy(j0, *(current_fp[0]), 0, 0, current_fp[0]->nComp(), current_fp[0]->nGrowVect()); + amrex::MultiFab::Copy(j1, *(current_fp[1]), 0, 0, current_fp[1]->nComp(), current_fp[1]->nGrowVect()); + amrex::MultiFab::Copy(j2, *(current_fp[2]), 0, 0, current_fp[2]->nComp(), current_fp[2]->nGrowVect()); + + current_fp[0]->setVal(0._rt); + current_fp[1]->setVal(0._rt); + current_fp[2]->setVal(0._rt); + if (rho_fp) { rho_fp->setVal(0._rt); } + PushPSATD(start_time); // Note that this does dt/2 + FillBoundaryE(guard_cells.ng_alloc_EB, WarpX::sync_nodal_points); FillBoundaryB(guard_cells.ng_alloc_EB, WarpX::sync_nodal_points); - ApplyBfieldBoundary(0, PatchType::fine, DtType::Full); + + // Restore the current_fp MultiFab. Note that this is only needed for diagnostics when + // J is being written out (since current_fp is not otherwise used). + amrex::MultiFab::Copy(*(current_fp[0]), j0, 0, 0, current_fp[0]->nComp(), current_fp[0]->nGrowVect()); + amrex::MultiFab::Copy(*(current_fp[1]), j1, 0, 0, current_fp[1]->nComp(), current_fp[1]->nGrowVect()); + amrex::MultiFab::Copy(*(current_fp[2]), j2, 0, 0, current_fp[2]->nComp(), current_fp[2]->nGrowVect()); } void @@ -134,7 +169,7 @@ WarpX::SaveParticlesAtImplicitStepStart ( ) #endif { - auto particle_comps = pc->getParticleComps(); + auto particle_comps = pc->GetRealSoANames(); for (WarpXParIter pti(*pc, lev); pti.isValid(); ++pti) { @@ -146,15 +181,15 @@ WarpX::SaveParticlesAtImplicitStepStart ( ) amrex::ParticleReal* const AMREX_RESTRICT uz = attribs[PIdx::uz].dataPtr(); #if (AMREX_SPACEDIM >= 2) - amrex::ParticleReal* x_n = pti.GetAttribs(particle_comps["x_n"]).dataPtr(); + amrex::ParticleReal* x_n = pti.GetAttribs("x_n").dataPtr(); #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - amrex::ParticleReal* y_n = pti.GetAttribs(particle_comps["y_n"]).dataPtr(); + amrex::ParticleReal* y_n = pti.GetAttribs("y_n").dataPtr(); #endif - amrex::ParticleReal* z_n = pti.GetAttribs(particle_comps["z_n"]).dataPtr(); - amrex::ParticleReal* ux_n = pti.GetAttribs(particle_comps["ux_n"]).dataPtr(); - amrex::ParticleReal* uy_n = pti.GetAttribs(particle_comps["uy_n"]).dataPtr(); - amrex::ParticleReal* uz_n = pti.GetAttribs(particle_comps["uz_n"]).dataPtr(); + amrex::ParticleReal* z_n = pti.GetAttribs("z_n").dataPtr(); + amrex::ParticleReal* ux_n = pti.GetAttribs("ux_n").dataPtr(); + amrex::ParticleReal* uy_n = pti.GetAttribs("uy_n").dataPtr(); + amrex::ParticleReal* uz_n = pti.GetAttribs("uz_n").dataPtr(); const long np = pti.numParticles(); @@ -204,7 +239,7 @@ WarpX::FinishImplicitParticleUpdate () #endif { - auto particle_comps = pc->getParticleComps(); + auto particle_comps = pc->GetRealSoANames(); for (WarpXParIter pti(*pc, lev); pti.isValid(); ++pti) { @@ -217,15 +252,15 @@ WarpX::FinishImplicitParticleUpdate () amrex::ParticleReal* const AMREX_RESTRICT uz = attribs[PIdx::uz].dataPtr(); #if (AMREX_SPACEDIM >= 2) - amrex::ParticleReal* x_n = pti.GetAttribs(particle_comps["x_n"]).dataPtr(); + amrex::ParticleReal* x_n = pti.GetAttribs("x_n").dataPtr(); #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - amrex::ParticleReal* y_n = pti.GetAttribs(particle_comps["y_n"]).dataPtr(); + amrex::ParticleReal* y_n = pti.GetAttribs("y_n").dataPtr(); #endif - amrex::ParticleReal* z_n = pti.GetAttribs(particle_comps["z_n"]).dataPtr(); - amrex::ParticleReal* ux_n = pti.GetAttribs(particle_comps["ux_n"]).dataPtr(); - amrex::ParticleReal* uy_n = pti.GetAttribs(particle_comps["uy_n"]).dataPtr(); - amrex::ParticleReal* uz_n = pti.GetAttribs(particle_comps["uz_n"]).dataPtr(); + amrex::ParticleReal* z_n = pti.GetAttribs("z_n").dataPtr(); + amrex::ParticleReal* ux_n = pti.GetAttribs("ux_n").dataPtr(); + amrex::ParticleReal* uy_n = pti.GetAttribs("uy_n").dataPtr(); + amrex::ParticleReal* uz_n = pti.GetAttribs("uz_n").dataPtr(); const long np = pti.numParticles(); @@ -259,8 +294,8 @@ WarpX::FinishImplicitParticleUpdate () } void -WarpX::FinishImplicitField( ablastr::fields::MultiLevelVectorField const& Field_fp, - ablastr::fields::MultiLevelVectorField const& Field_n, +WarpX::FinishImplicitField( ablastr::fields::MultiLevelVectorField const& Field_fp, + ablastr::fields::MultiLevelVectorField const& Field_n, amrex::Real theta ) { using namespace amrex::literals; @@ -310,7 +345,7 @@ WarpX::FinishImplicitField( ablastr::fields::MultiLevelVectorField const& Field } void -WarpX::ImplicitComputeRHSE (amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) +WarpX::ImplicitComputeRHSE (amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) { for (int lev = 0; lev <= finest_level; ++lev) { @@ -319,7 +354,7 @@ WarpX::ImplicitComputeRHSE (amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) } void -WarpX::ImplicitComputeRHSE (int lev, amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) +WarpX::ImplicitComputeRHSE (int lev, amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) { WARPX_PROFILE("WarpX::ImplicitComputeRHSE()"); ImplicitComputeRHSE(lev, PatchType::fine, a_dt, a_Erhs_vec); @@ -330,7 +365,7 @@ WarpX::ImplicitComputeRHSE (int lev, amrex::Real a_dt, WarpXSolverVec& a_Erhs_v } void -WarpX::ImplicitComputeRHSE (int lev, PatchType patch_type, amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) +WarpX::ImplicitComputeRHSE (int lev, PatchType patch_type, amrex::Real a_dt, WarpXSolverVec& a_Erhs_vec) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( a_Erhs_vec.getArrayVecType()==warpx::fields::FieldType::Efield_fp, @@ -350,12 +385,14 @@ WarpX::ImplicitComputeRHSE (int lev, PatchType patch_type, amrex::Real a_dt, War lev, patch_type, a_Erhs_vec.getArrayVec()[lev], + m_eb_update_E[lev], a_dt ); } else { m_fdtd_solver_cp[lev]->EvolveE( m_fields, lev, patch_type, a_Erhs_vec.getArrayVec()[lev], + m_eb_update_E[lev], a_dt ); } diff --git a/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.H b/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.H index 29c808b48cd..a4bbbe99f75 100644 --- a/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.H +++ b/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.H @@ -75,6 +75,7 @@ public: void Define ( const WarpXSolverVec& a_solver_vec ) { assertIsDefined( a_solver_vec ); + m_num_amr_levels = a_solver_vec.m_num_amr_levels; Define( WarpXSolverVec::m_WarpX, a_solver_vec.getVectorType(), a_solver_vec.getScalarType() ); @@ -83,7 +84,8 @@ public: [[nodiscard]] RT dotProduct( const WarpXSolverVec& a_X ) const; void Copy ( warpx::fields::FieldType a_array_type, - warpx::fields::FieldType a_scalar_type = warpx::fields::FieldType::None ); + warpx::fields::FieldType a_scalar_type = warpx::fields::FieldType::None, + bool allow_type_mismatch = false); inline void Copy ( const WarpXSolverVec& a_solver_vec ) @@ -300,7 +302,7 @@ private: std::string m_scalar_type_name = "none"; static constexpr int m_ncomp = 1; - static constexpr int m_num_amr_levels = 1; + int m_num_amr_levels = 1; inline static bool m_warpx_ptr_defined = false; inline static WarpX* m_WarpX = nullptr; diff --git a/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.cpp b/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.cpp index 6a0e6bb8a91..05b5f1caa0c 100644 --- a/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.cpp +++ b/Source/FieldSolver/ImplicitSolvers/WarpXSolverVec.cpp @@ -34,6 +34,8 @@ void WarpXSolverVec::Define ( WarpX* a_WarpX, m_warpx_ptr_defined = true; } + m_num_amr_levels = 1; + m_vector_type_name = a_vector_type_name; m_scalar_type_name = a_scalar_type_name; @@ -110,26 +112,27 @@ void WarpXSolverVec::Define ( WarpX* a_WarpX, } void WarpXSolverVec::Copy ( FieldType a_array_type, - FieldType a_scalar_type ) + FieldType a_scalar_type, + bool allow_type_mismatch) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( IsDefined(), "WarpXSolverVec::Copy() called on undefined WarpXSolverVec"); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( - a_array_type==m_array_type && - a_scalar_type==m_scalar_type, + (a_array_type==m_array_type && + a_scalar_type==m_scalar_type) || allow_type_mismatch, "WarpXSolverVec::Copy() called with vecs of different types"); for (int lev = 0; lev < m_num_amr_levels; ++lev) { if (m_array_type != FieldType::None) { - const ablastr::fields::VectorField this_array = m_WarpX->m_fields.get_alldirs(m_vector_type_name, lev); + const ablastr::fields::VectorField this_array = m_WarpX->m_fields.get_alldirs(a_array_type, lev); for (int n = 0; n < 3; ++n) { amrex::MultiFab::Copy( *m_array_vec[lev][n], *this_array[n], 0, 0, m_ncomp, amrex::IntVect::TheZeroVector() ); } } if (m_scalar_type != FieldType::None) { - const amrex::MultiFab* this_mf = m_WarpX->m_fields.get(m_scalar_type_name,lev); + const amrex::MultiFab* this_mf = m_WarpX->m_fields.get(a_scalar_type,lev); amrex::MultiFab::Copy( *m_scalar_vec[lev], *this_mf, 0, 0, m_ncomp, amrex::IntVect::TheZeroVector() ); } @@ -146,7 +149,7 @@ void WarpXSolverVec::Copy ( FieldType a_array_type, for (int lev = 0; lev < m_num_amr_levels; ++lev) { if (m_array_type != FieldType::None) { for (int n = 0; n < 3; ++n) { - const amrex::iMultiFab* dotMask = m_WarpX->getFieldDotMaskPointer(m_array_type,lev,n); + const amrex::iMultiFab* dotMask = m_WarpX->getFieldDotMaskPointer(m_array_type, lev, ablastr::fields::Direction{n}); auto rtmp = amrex::MultiFab::Dot( *dotMask, *m_array_vec[lev][n], 0, *a_X.getArrayVec()[lev][n], 0, 1, 0, local); @@ -154,7 +157,7 @@ void WarpXSolverVec::Copy ( FieldType a_array_type, } } if (m_scalar_type != FieldType::None) { - const amrex::iMultiFab* dotMask = m_WarpX->getFieldDotMaskPointer(m_scalar_type,lev,0); + const amrex::iMultiFab* dotMask = m_WarpX->getFieldDotMaskPointer(m_scalar_type,lev, ablastr::fields::Direction{0}); auto rtmp = amrex::MultiFab::Dot( *dotMask, *m_scalar_vec[lev], 0, *a_X.getScalarVec()[lev], 0, 1, 0, local); diff --git a/Source/FieldSolver/MagnetostaticSolver/MagnetostaticSolver.cpp b/Source/FieldSolver/MagnetostaticSolver/MagnetostaticSolver.cpp index 5c28ff1f3c7..2a744f3f902 100644 --- a/Source/FieldSolver/MagnetostaticSolver/MagnetostaticSolver.cpp +++ b/Source/FieldSolver/MagnetostaticSolver/MagnetostaticSolver.cpp @@ -65,7 +65,8 @@ WarpX::ComputeMagnetostaticField() // Fields have been reset in Electrostatic solver for this time step, these fields // are added into the B fields after electrostatic solve - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(this->max_level == 0, "Magnetostatic solver not implemented with mesh refinement."); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(this->max_level == 0, + "Magnetostatic solver not implemented with mesh refinement."); AddMagnetostaticFieldLabFrame(); } @@ -127,16 +128,21 @@ WarpX::AddMagnetostaticFieldLabFrame() // const amrex::Real magnetostatic_absolute_tolerance = self_fields_absolute_tolerance*PhysConst::c; // temporary fix!!! - const amrex::Real magnetostatic_absolute_tolerance = 0.0; - const amrex::Real self_fields_required_precision = 1e-12; - const int self_fields_max_iters = 200; - const int self_fields_verbosity = 2; + const amrex::Real absolute_tolerance = 0.0; + amrex::Real required_precision; + if constexpr (std::is_same_v) { + required_precision = 1e-5; + } + else { + required_precision = 1e-11; + } computeVectorPotential( m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), m_fields.get_mr_levels_alldirs(FieldType::vector_potential_fp_nodal, finest_level), - self_fields_required_precision, magnetostatic_absolute_tolerance, self_fields_max_iters, - self_fields_verbosity); + required_precision, absolute_tolerance, magnetostatic_solver_max_iters, + magnetostatic_solver_verbosity + ); } /* Compute the vector potential `A` by solving the Poisson equation with `J` as @@ -187,11 +193,16 @@ WarpX::computeVectorPotential (ablastr::fields::MultiLevelVectorField const& cur }); #if defined(AMREX_USE_EB) - amrex::Vector factories; - for (int lev = 0; lev <= finest_level; ++lev) { - factories.push_back(&WarpX::fieldEBFactory(lev)); + std::optional > eb_farray_box_factory; + auto &warpx = WarpX::GetInstance(); + + if (EB::enabled()) { + amrex::Vector factories; + for (int lev = 0; lev <= finest_level; ++lev) { + factories.push_back(&warpx.fieldEBFactory(lev)); + } + eb_farray_box_factory = factories; } - const std::optional > eb_farray_box_factory({factories}); #else const std::optional > eb_farray_box_factory; #endif diff --git a/Source/FieldSolver/SpectralSolver/SpectralKSpace.H b/Source/FieldSolver/SpectralSolver/SpectralKSpace.H index 16f93d8292a..fcf1a2ccd02 100644 --- a/Source/FieldSolver/SpectralSolver/SpectralKSpace.H +++ b/Source/FieldSolver/SpectralSolver/SpectralKSpace.H @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -35,9 +36,9 @@ using SpectralShiftFactor = amrex::LayoutData< // Indicate the type of correction "shift" factor to apply // when the FFT is performed from/to a cell-centered grid in real space. -struct ShiftType { - enum{ TransformFromCellCentered=0, TransformToCellCentered=1 }; -}; +AMREX_ENUM(ShiftType, + TransformFromCellCentered, + TransformToCellCentered); /** * \brief Class that represents the spectral space. @@ -69,7 +70,7 @@ class SpectralKSpace SpectralShiftFactor getSpectralShiftFactor( const amrex::DistributionMapping& dm, int i_dim, - int shift_type ) const; + ShiftType shift_type ) const; protected: amrex::Array k_vec; diff --git a/Source/FieldSolver/SpectralSolver/SpectralKSpace.cpp b/Source/FieldSolver/SpectralSolver/SpectralKSpace.cpp index 94bd384f265..5313409553f 100644 --- a/Source/FieldSolver/SpectralSolver/SpectralKSpace.cpp +++ b/Source/FieldSolver/SpectralSolver/SpectralKSpace.cpp @@ -7,10 +7,12 @@ */ #include "SpectralKSpace.H" -#include "WarpX.H" #include "Utils/TextMsg.H" #include "Utils/WarpXConst.H" +#include +#include + #include #include #include @@ -143,7 +145,7 @@ SpectralKSpace::getKComponent( const DistributionMapping& dm, SpectralShiftFactor SpectralKSpace::getSpectralShiftFactor( const DistributionMapping& dm, const int i_dim, - const int shift_type ) const + const ShiftType shift_type ) const { // Initialize an empty DeviceVector in each box SpectralShiftFactor shift_factor( spectralspace_ba, dm ); @@ -211,7 +213,8 @@ SpectralKSpace::getModifiedKComponent (const DistributionMapping& dm, } else { // Compute real-space stencil coefficients - Vector h_stencil_coef = WarpX::getFornbergStencilCoefficients(n_order, grid_type); + Vector h_stencil_coef = + ablastr::math::getFornbergStencilCoefficients(n_order, grid_type); Gpu::DeviceVector d_stencil_coef(h_stencil_coef.size()); Gpu::copyAsync(Gpu::hostToDevice, h_stencil_coef.begin(), h_stencil_coef.end(), d_stencil_coef.begin()); @@ -237,7 +240,7 @@ SpectralKSpace::getModifiedKComponent (const DistributionMapping& dm, { p_modified_k[i] = 0; for (int n=0; nm_spectral_index.rho_old; const int rho_new = spectral_solver_fp[0]->m_spectral_index.rho_new; @@ -852,33 +855,35 @@ WarpX::PushPSATD () if (WarpX::fft_do_time_averaging) { auto Efield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_fp, finest_level); auto Bfield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_fp, finest_level); - auto Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level); - auto Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level); + auto Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level, skip_lev0_coarse_patch); + auto Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level, skip_lev0_coarse_patch); PSATDBackwardTransformEBavg(Efield_avg_fp, Bfield_avg_fp, Efield_avg_cp, Bfield_avg_cp); } if (WarpX::do_dive_cleaning) { PSATDBackwardTransformF(); } if (WarpX::do_divb_cleaning) { PSATDBackwardTransformG(); } - // Evolve the fields in the PML boxes for (int lev = 0; lev <= finest_level; ++lev) { + // Evolve the fields in the PML boxes if (pml[lev] && pml[lev]->ok()) { pml[lev]->PushPSATD(m_fields, lev); } - ApplyEfieldBoundary(lev, PatchType::fine); - if (lev > 0) { ApplyEfieldBoundary(lev, PatchType::coarse); } - ApplyBfieldBoundary(lev, PatchType::fine, DtType::FirstHalf); - if (lev > 0) { ApplyBfieldBoundary(lev, PatchType::coarse, DtType::FirstHalf); } + + amrex::Real const new_time = start_time + spectral_solver_fp[lev]->m_dt; + ApplyEfieldBoundary(lev, PatchType::fine, new_time); + if (lev > 0) { ApplyEfieldBoundary(lev, PatchType::coarse, new_time); } + ApplyBfieldBoundary(lev, PatchType::fine, DtType::FirstHalf, new_time); + if (lev > 0) { ApplyBfieldBoundary(lev, PatchType::coarse, DtType::FirstHalf, new_time); } } #endif } void -WarpX::EvolveB (amrex::Real a_dt, DtType a_dt_type) +WarpX::EvolveB (amrex::Real a_dt, DtType a_dt_type, amrex::Real start_time) { for (int lev = 0; lev <= finest_level; ++lev) { - EvolveB(lev, a_dt, a_dt_type); + EvolveB(lev, a_dt, a_dt_type, start_time); } // Allow execution of Python callback after B-field push @@ -886,18 +891,18 @@ WarpX::EvolveB (amrex::Real a_dt, DtType a_dt_type) } void -WarpX::EvolveB (int lev, amrex::Real a_dt, DtType a_dt_type) +WarpX::EvolveB (int lev, amrex::Real a_dt, DtType a_dt_type, amrex::Real start_time) { WARPX_PROFILE("WarpX::EvolveB()"); - EvolveB(lev, PatchType::fine, a_dt, a_dt_type); + EvolveB(lev, PatchType::fine, a_dt, a_dt_type, start_time); if (lev > 0) { - EvolveB(lev, PatchType::coarse, a_dt, a_dt_type); + EvolveB(lev, PatchType::coarse, a_dt, a_dt_type, start_time); } } void -WarpX::EvolveB (int lev, PatchType patch_type, amrex::Real a_dt, DtType a_dt_type) +WarpX::EvolveB (int lev, PatchType patch_type, amrex::Real a_dt, DtType a_dt_type, amrex::Real start_time) { // Evolve B field in regular cells if (patch_type == PatchType::fine) { @@ -923,16 +928,17 @@ WarpX::EvolveB (int lev, PatchType patch_type, amrex::Real a_dt, DtType a_dt_typ } } - ApplyBfieldBoundary(lev, patch_type, a_dt_type); + amrex::Real const new_time = start_time + a_dt; + ApplyBfieldBoundary(lev, patch_type, a_dt_type, new_time); } void -WarpX::EvolveE (amrex::Real a_dt) +WarpX::EvolveE (amrex::Real a_dt, amrex::Real start_time) { for (int lev = 0; lev <= finest_level; ++lev) { - EvolveE(lev, a_dt); + EvolveE(lev, a_dt, start_time); } // Allow execution of Python callback after E-field push @@ -940,18 +946,18 @@ WarpX::EvolveE (amrex::Real a_dt) } void -WarpX::EvolveE (int lev, amrex::Real a_dt) +WarpX::EvolveE (int lev, amrex::Real a_dt, amrex::Real start_time) { WARPX_PROFILE("WarpX::EvolveE()"); - EvolveE(lev, PatchType::fine, a_dt); + EvolveE(lev, PatchType::fine, a_dt, start_time); if (lev > 0) { - EvolveE(lev, PatchType::coarse, a_dt); + EvolveE(lev, PatchType::coarse, a_dt, start_time); } } void -WarpX::EvolveE (int lev, PatchType patch_type, amrex::Real a_dt) +WarpX::EvolveE (int lev, PatchType patch_type, amrex::Real a_dt, amrex::Real start_time) { // Evolve E field in regular cells if (patch_type == PatchType::fine) { @@ -959,12 +965,14 @@ WarpX::EvolveE (int lev, PatchType patch_type, amrex::Real a_dt) lev, patch_type, m_fields.get_alldirs(FieldType::Efield_fp, lev), + m_eb_update_E[lev], a_dt ); } else { m_fdtd_solver_cp[lev]->EvolveE( m_fields, lev, patch_type, m_fields.get_alldirs(FieldType::Efield_cp, lev), + m_eb_update_E[lev], a_dt ); } @@ -987,7 +995,8 @@ WarpX::EvolveE (int lev, PatchType patch_type, amrex::Real a_dt) } } - ApplyEfieldBoundary(lev, patch_type); + amrex::Real const new_time = start_time + a_dt; + ApplyEfieldBoundary(lev, patch_type, new_time); // ECTRhofield must be recomputed at the very end of the Efield update to ensure // that ECTRhofield is consistent with Efield @@ -1098,6 +1107,8 @@ WarpX::EvolveG (int lev, PatchType patch_type, amrex::Real a_dt, DtType /*a_dt_t WARPX_PROFILE("WarpX::EvolveG()"); + bool const skip_lev0_coarse_patch = true; + // Evolve G field in regular cells if (patch_type == PatchType::fine) { @@ -1108,7 +1119,7 @@ WarpX::EvolveG (int lev, PatchType patch_type, amrex::Real a_dt, DtType /*a_dt_t } else // coarse patch { - ablastr::fields::MultiLevelVectorField const& Bfield_cp_new = m_fields.get_mr_levels_alldirs(FieldType::Bfield_cp, finest_level); + ablastr::fields::MultiLevelVectorField const& Bfield_cp_new = m_fields.get_mr_levels_alldirs(FieldType::Bfield_cp, finest_level, skip_lev0_coarse_patch); m_fdtd_solver_cp[lev]->EvolveG( m_fields.get(FieldType::G_cp, lev), Bfield_cp_new[lev], a_dt); @@ -1118,15 +1129,15 @@ WarpX::EvolveG (int lev, PatchType patch_type, amrex::Real a_dt, DtType /*a_dt_t } void -WarpX::MacroscopicEvolveE (amrex::Real a_dt) +WarpX::MacroscopicEvolveE (amrex::Real a_dt, amrex::Real start_time) { for (int lev = 0; lev <= finest_level; ++lev ) { - MacroscopicEvolveE(lev, a_dt); + MacroscopicEvolveE(lev, a_dt, start_time); } } void -WarpX::MacroscopicEvolveE (int lev, amrex::Real a_dt) { +WarpX::MacroscopicEvolveE (int lev, amrex::Real a_dt, amrex::Real start_time) { WARPX_PROFILE("WarpX::MacroscopicEvolveE()"); @@ -1135,11 +1146,11 @@ WarpX::MacroscopicEvolveE (int lev, amrex::Real a_dt) { "Macroscopic EvolveE is not implemented for lev>0, yet." ); - MacroscopicEvolveE(lev, PatchType::fine, a_dt); + MacroscopicEvolveE(lev, PatchType::fine, a_dt, start_time); } void -WarpX::MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real a_dt) { +WarpX::MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real a_dt, amrex::Real start_time) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( patch_type == PatchType::fine, @@ -1150,7 +1161,7 @@ WarpX::MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real a_dt) { m_fields.get_alldirs(FieldType::Efield_fp, lev), m_fields.get_alldirs(FieldType::Bfield_fp, lev), m_fields.get_alldirs(FieldType::current_fp, lev), - m_fields.get_alldirs(FieldType::edge_lengths, lev), + m_eb_update_E[lev], a_dt, m_macroscopic_properties); if (do_pml && pml[lev]->ok()) { @@ -1171,7 +1182,8 @@ WarpX::MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real a_dt) { } } - ApplyEfieldBoundary(lev, patch_type); + amrex::Real const new_time = start_time + a_dt; + ApplyEfieldBoundary(lev, patch_type, new_time); } void @@ -1323,7 +1335,7 @@ void WarpX::DampFieldsInGuards(const int lev, amrex::MultiFab* mf) // It is faster to apply this on the grid than to do it particle by particle. // It is put here since there isn't another nice place for it. void -WarpX::ApplyInverseVolumeScalingToCurrentDensity (MultiFab* Jx, MultiFab* Jy, MultiFab* Jz, int lev) +WarpX::ApplyInverseVolumeScalingToCurrentDensity (MultiFab* Jx, MultiFab* Jy, MultiFab* Jz, int lev) const { const amrex::IntVect ngJ = Jx->nGrowVect(); const std::array& dx = WarpX::CellSize(lev); @@ -1332,7 +1344,7 @@ WarpX::ApplyInverseVolumeScalingToCurrentDensity (MultiFab* Jx, MultiFab* Jy, Mu constexpr int NODE = amrex::IndexType::NODE; // See Verboncoeur JCP 174, 421-427 (2001) for the modified volume factor - const amrex::Real axis_volume_factor = (verboncoeur_axis_correction ? 1._rt/3._rt : 1._rt/4._rt); + const amrex::Real axis_volume_factor = (m_verboncoeur_axis_correction ? 1._rt/3._rt : 1._rt/4._rt); for ( MFIter mfi(*Jx, TilingIfNotGPU()); mfi.isValid(); ++mfi ) { @@ -1496,7 +1508,7 @@ WarpX::ApplyInverseVolumeScalingToCurrentDensity (MultiFab* Jx, MultiFab* Jy, Mu } void -WarpX::ApplyInverseVolumeScalingToChargeDensity (MultiFab* Rho, int lev) +WarpX::ApplyInverseVolumeScalingToChargeDensity (MultiFab* Rho, int lev) const { const amrex::IntVect ngRho = Rho->nGrowVect(); const std::array& dx = WarpX::CellSize(lev); @@ -1505,7 +1517,7 @@ WarpX::ApplyInverseVolumeScalingToChargeDensity (MultiFab* Rho, int lev) constexpr int NODE = amrex::IndexType::NODE; // See Verboncoeur JCP 174, 421-427 (2001) for the modified volume factor - const amrex::Real axis_volume_factor = (verboncoeur_axis_correction ? 1._rt/3._rt : 1._rt/4._rt); + const amrex::Real axis_volume_factor = (m_verboncoeur_axis_correction ? 1._rt/3._rt : 1._rt/4._rt); Box tilebox; diff --git a/Source/FieldSolver/WarpXPushFieldsHybridPIC.cpp b/Source/FieldSolver/WarpXPushFieldsHybridPIC.cpp index 5220419f822..b57def5c4fe 100644 --- a/Source/FieldSolver/WarpXPushFieldsHybridPIC.cpp +++ b/Source/FieldSolver/WarpXPushFieldsHybridPIC.cpp @@ -1,8 +1,9 @@ -/* Copyright 2023 The WarpX Community +/* Copyright 2023-2024 The WarpX Community * * This file is part of WarpX. * * Authors: Roelof Groenewald (TAE Technologies) + * S. Eric Clark (Helion Energy) * * License: BSD-3-Clause-LBNL */ @@ -33,6 +34,31 @@ void WarpX::HybridPICEvolveFields () finest_level == 0, "Ohm's law E-solve only works with a single level."); + // Get requested number of substeps to use + const int sub_steps = m_hybrid_pic_model->m_substeps; + + // Get flag to include external fields. + const bool add_external_fields = m_hybrid_pic_model->m_add_external_fields; + + // Handle field splitting for Hybrid field push + if (add_external_fields) { + // Get the external fields + m_hybrid_pic_model->m_external_vector_potential->UpdateHybridExternalFields( + gett_old(0), + 0.5_rt*dt[0]); + + // If using split fields, subtract the external field at the old time + for (int lev = 0; lev <= finest_level; ++lev) { + for (int idim = 0; idim < 3; ++idim) { + MultiFab::Subtract( + *m_fields.get(FieldType::Bfield_fp, Direction{idim}, lev), + *m_fields.get(FieldType::hybrid_B_fp_external, Direction{idim}, lev), + 0, 0, 1, + m_fields.get(FieldType::Bfield_fp, Direction{idim}, lev)->nGrowVect()); + } + } + } + // The particles have now been pushed to their t_{n+1} positions. // Perform charge deposition in component 0 of rho_fp at t_{n+1}. mypc->DepositCharge(m_fields.get_mr_levels(FieldType::rho_fp, finest_level), 0._rt); @@ -64,9 +90,6 @@ void WarpX::HybridPICEvolveFields () } } - // Get requested number of substeps to use - const int sub_steps = m_hybrid_pic_model->m_substeps; - // Get the external current m_hybrid_pic_model->GetCurrentExternal(); @@ -108,7 +131,7 @@ void WarpX::HybridPICEvolveFields () m_fields.get_mr_levels_alldirs(FieldType::Bfield_fp, finest_level), m_fields.get_mr_levels_alldirs(FieldType::Efield_fp, finest_level), current_fp_temp, rho_fp_temp, - m_fields.get_mr_levels_alldirs(FieldType::edge_lengths, finest_level), + m_eb_update_E, 0.5_rt/sub_steps*dt[0], DtType::FirstHalf, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points @@ -127,6 +150,13 @@ void WarpX::HybridPICEvolveFields () ); } + if (add_external_fields) { + // Get the external fields at E^{n+1/2} + m_hybrid_pic_model->m_external_vector_potential->UpdateHybridExternalFields( + gett_old(0) + 0.5_rt*dt[0], + 0.5_rt*dt[0]); + } + // Now push the B field from t=n+1/2 to t=n+1 using the n+1/2 quantities for (int sub_step = 0; sub_step < sub_steps; sub_step++) { @@ -135,7 +165,7 @@ void WarpX::HybridPICEvolveFields () m_fields.get_mr_levels_alldirs(FieldType::Efield_fp, finest_level), m_fields.get_mr_levels_alldirs(FieldType::current_fp, finest_level), rho_fp_temp, - m_fields.get_mr_levels_alldirs(FieldType::edge_lengths, finest_level), + m_eb_update_E, 0.5_rt/sub_steps*dt[0], DtType::SecondHalf, guard_cells.ng_FieldSolver, WarpX::sync_nodal_points @@ -160,22 +190,46 @@ void WarpX::HybridPICEvolveFields () } } + if (add_external_fields) { + m_hybrid_pic_model->m_external_vector_potential->UpdateHybridExternalFields( + gett_new(0), + 0.5_rt*dt[0]); + } + // Calculate the electron pressure at t=n+1 m_hybrid_pic_model->CalculateElectronPressure(); // Update the E field to t=n+1 using the extrapolated J_i^n+1 value m_hybrid_pic_model->CalculatePlasmaCurrent( m_fields.get_mr_levels_alldirs(FieldType::Bfield_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::edge_lengths, finest_level)); + m_eb_update_E); m_hybrid_pic_model->HybridPICSolveE( m_fields.get_mr_levels_alldirs(FieldType::Efield_fp, finest_level), current_fp_temp, m_fields.get_mr_levels_alldirs(FieldType::Bfield_fp, finest_level), m_fields.get_mr_levels(FieldType::rho_fp, finest_level), - m_fields.get_mr_levels_alldirs(FieldType::edge_lengths, finest_level), false - ); + m_eb_update_E, false); FillBoundaryE(guard_cells.ng_FieldSolver, WarpX::sync_nodal_points); + // Handle field splitting for Hybrid field push + if (add_external_fields) { + // If using split fields, add the external field at the new time + for (int lev = 0; lev <= finest_level; ++lev) { + for (int idim = 0; idim < 3; ++idim) { + MultiFab::Add( + *m_fields.get(FieldType::Bfield_fp, Direction{idim}, lev), + *m_fields.get(FieldType::hybrid_B_fp_external, Direction{idim}, lev), + 0, 0, 1, + m_fields.get(FieldType::Bfield_fp, Direction{idim}, lev)->nGrowVect()); + MultiFab::Add( + *m_fields.get(FieldType::Efield_fp, Direction{idim}, lev), + *m_fields.get(FieldType::hybrid_E_fp_external, Direction{idim}, lev), + 0, 0, 1, + m_fields.get(FieldType::Efield_fp, Direction{idim}, lev)->nGrowVect()); + } + } + } + // Copy the rho^{n+1} values to rho_fp_temp and the J_i^{n+1/2} values to // current_fp_temp since at the next step those values will be needed as // rho^{n} and J_i^{n-1/2}. @@ -189,17 +243,31 @@ void WarpX::HybridPICEvolveFields () 0, 0, 1, current_fp_temp[lev][idim]->nGrowVect()); } } + + // Check that the E-field does not have nan or inf values, otherwise print a clear message + ablastr::fields::MultiLevelVectorField Efield_fp = m_fields.get_mr_levels_alldirs(FieldType::Efield_fp, finest_level); + for (int lev = 0; lev <= finest_level; ++lev) + { + for (int idim = 0; idim < 3; ++idim) { + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + Efield_fp[lev][idim]->is_finite(), + "Non-finite value detected in E-field; this indicates more substeps should be used in the field solver." + ); + } + } } void WarpX::HybridPICDepositInitialRhoAndJ () { using warpx::fields::FieldType; + bool const skip_lev0_coarse_patch = true; + ablastr::fields::MultiLevelScalarField rho_fp_temp = m_fields.get_mr_levels(FieldType::hybrid_rho_fp_temp, finest_level); ablastr::fields::MultiLevelVectorField current_fp_temp = m_fields.get_mr_levels_alldirs(FieldType::hybrid_current_fp_temp, finest_level); mypc->DepositCharge(rho_fp_temp, 0._rt); mypc->DepositCurrent(current_fp_temp, dt[0], 0._rt); - SyncRho(rho_fp_temp, m_fields.get_mr_levels(FieldType::rho_cp, finest_level), m_fields.get_mr_levels(FieldType::rho_buf, finest_level)); + SyncRho(rho_fp_temp, m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch), m_fields.get_mr_levels(FieldType::rho_buf, finest_level, skip_lev0_coarse_patch)); SyncCurrent("hybrid_current_fp_temp"); for (int lev=0; lev <= finest_level; ++lev) { // SyncCurrent does not include a call to FillBoundary, but it is needed @@ -219,3 +287,15 @@ void WarpX::HybridPICDepositInitialRhoAndJ () ); } } + +void +WarpX::CalculateExternalCurlA() { + WARPX_PROFILE("WarpX::CalculateExternalCurlA()"); + + auto & warpx = WarpX::GetInstance(); + + // Get reference to External Field Object + auto* ext_vector = warpx.m_hybrid_pic_model->m_external_vector_potential.get(); + ext_vector->CalculateExternalCurlA(); + +} diff --git a/Source/Fields.H b/Source/Fields.H index b07661254c4..271d5a835a3 100644 --- a/Source/Fields.H +++ b/Source/Fields.H @@ -50,6 +50,8 @@ namespace warpx::fields hybrid_current_fp_temp, /**< Used with Ohm's law solver. Stores the time interpolated/extrapolated current density */ hybrid_current_fp_plasma, /**< Used with Ohm's law solver. Stores plasma current calculated as J_plasma = curl x B / mu0 - J_ext */ hybrid_current_fp_external, /**< Used with Ohm's law solver. Stores external current */ + hybrid_B_fp_external, /**< Used with Ohm's law solver. Stores external B field */ + hybrid_E_fp_external, /**< Used with Ohm's law solver. Stores external E field */ Efield_cp, /**< Only used with MR. The field that is updated by the field solver at each timestep, on the coarse patch of each level */ Bfield_cp, /**< Only used with MR. The field that is updated by the field solver at each timestep, on the coarse patch of each level */ current_cp, /**< Only used with MR. The current that is used as a source for the field solver, on the coarse patch of each level */ @@ -61,8 +63,8 @@ namespace warpx::fields E_external_particle_field, /**< Stores external particle fields provided by the user as through an openPMD file */ B_external_particle_field, /**< Stores external particle fields provided by the user as through an openPMD file */ distance_to_eb, /**< Only used with embedded boundaries (EB). Stores the distance to the nearest EB */ - edge_lengths, /**< Only used with embedded boundaries (EB). Indicates the length of the cell edge that is covered by the EB, in SI units */ - face_areas, /**< Only used with embedded boundaries (EB). Indicates the area of the cell face that is covered by the EB, in SI units */ + edge_lengths, /**< Only used with the ECT solver. Indicates the length of the cell edge that is covered by the EB, in SI units */ + face_areas, /**< Only used with the ECT solver. Indicates the area of the cell face that is covered by the EB, in SI units */ area_mod, pml_E_fp, pml_B_fp, @@ -102,6 +104,8 @@ namespace warpx::fields FieldType::hybrid_current_fp_temp, FieldType::hybrid_current_fp_plasma, FieldType::hybrid_current_fp_external, + FieldType::hybrid_B_fp_external, + FieldType::hybrid_E_fp_external, FieldType::Efield_cp, FieldType::Bfield_cp, FieldType::current_cp, diff --git a/Source/Initialization/DivCleaner/ProjectionDivCleaner.cpp b/Source/Initialization/DivCleaner/ProjectionDivCleaner.cpp index 670f962f7c3..d7a3bb3ac92 100644 --- a/Source/Initialization/DivCleaner/ProjectionDivCleaner.cpp +++ b/Source/Initialization/DivCleaner/ProjectionDivCleaner.cpp @@ -104,7 +104,7 @@ void ProjectionDivCleaner::ReadParameters () { // Initialize tolerance based on field precision - if constexpr (std::is_same::value) { + if constexpr (std::is_same_v) { m_rtol = 5e-5; m_atol = 0.0; } @@ -141,7 +141,7 @@ ProjectionDivCleaner::solve () std::map bcmap{ {FieldBoundaryType::PEC, LinOpBCType::Dirichlet}, - {FieldBoundaryType::Neumann, LinOpBCType::Neumann}, + {FieldBoundaryType::Neumann, LinOpBCType::Neumann}, // Note that PMC is the same as Neumann {FieldBoundaryType::Periodic, LinOpBCType::Periodic}, {FieldBoundaryType::None, LinOpBCType::Neumann} }; @@ -151,7 +151,7 @@ ProjectionDivCleaner::solve () auto ithi = bcmap.find(WarpX::field_boundary_hi[idim]); if (itlo == bcmap.end() || ithi == bcmap.end()) { WARPX_ABORT_WITH_MESSAGE( - "Field boundary conditions have to be either periodic, PEC or neumann " + "Field boundary conditions have to be either periodic, PEC, PMC, or neumann " "when using the MLMG projection based divergence cleaner solver." ); } @@ -337,7 +337,7 @@ WarpX::ProjectionCleanDivB() { && WarpX::poisson_solver_id == PoissonSolverAlgo::Multigrid)) { amrex::Print() << Utils::TextMsg::Info( "Starting Projection B-Field divergence cleaner."); - if constexpr (!std::is_same::value) { + if constexpr (!std::is_same_v) { ablastr::warn_manager::WMRecordWarning("Projection Div Cleaner", "WarpX is running with a field precision of SINGLE." "Convergence of projection based div cleaner is not optimal and may fail.", diff --git a/Source/Initialization/PlasmaInjector.cpp b/Source/Initialization/PlasmaInjector.cpp index 76bb7a5be42..468d9e7e336 100644 --- a/Source/Initialization/PlasmaInjector.cpp +++ b/Source/Initialization/PlasmaInjector.cpp @@ -305,6 +305,9 @@ void PlasmaInjector::setupNFluxPerCell (amrex::ParmParse const& pp_species) } #endif + utils::parser::queryWithParser(pp_species, source_name, "flux_tmin", flux_tmin); + utils::parser::queryWithParser(pp_species, source_name, "flux_tmax", flux_tmax); + // Check whether injection from the embedded boundary is requested utils::parser::queryWithParser(pp_species, source_name, "inject_from_embedded_boundary", m_inject_from_eb); if (m_inject_from_eb) { @@ -318,8 +321,6 @@ void PlasmaInjector::setupNFluxPerCell (amrex::ParmParse const& pp_species) // Parse the parameters of the plane (position, normal direction, etc.) utils::parser::getWithParser(pp_species, source_name, "surface_flux_pos", surface_flux_pos); - utils::parser::queryWithParser(pp_species, source_name, "flux_tmin", flux_tmin); - utils::parser::queryWithParser(pp_species, source_name, "flux_tmax", flux_tmax); std::string flux_normal_axis_string; utils::parser::get(pp_species, source_name, "flux_normal_axis", flux_normal_axis_string); flux_normal_axis = -1; diff --git a/Source/Initialization/WarpXAMReXInit.cpp b/Source/Initialization/WarpXAMReXInit.cpp index 5009d2def59..2c43168f5ef 100644 --- a/Source/Initialization/WarpXAMReXInit.cpp +++ b/Source/Initialization/WarpXAMReXInit.cpp @@ -7,13 +7,17 @@ #include "Initialization/WarpXAMReXInit.H" +#include "Utils/Parser/ParserUtils.H" #include "Utils/TextMsg.H" #include +#include #include +#include #include -#include +#include +#include #include namespace { @@ -105,6 +109,66 @@ namespace { set_device_synchronization(); override_default_tiling_option_for_particles(); } + + /** Parse prob_lo and hi + * + * Parse prob_lo and hi evaluating any expressions since geometry + * does not parse its input. Note that this operation has to be + * performed after having initialized AMReX + */ + void parse_geometry_input () + { + auto pp_geometry = amrex::ParmParse {"geometry"}; + + auto prob_lo = amrex::Vector(AMREX_SPACEDIM); + auto prob_hi = amrex::Vector(AMREX_SPACEDIM); + + utils::parser::getArrWithParser( + pp_geometry, "prob_lo", prob_lo, 0, AMREX_SPACEDIM); + utils::parser::getArrWithParser( + pp_geometry, "prob_hi", prob_hi, 0, AMREX_SPACEDIM); + + AMREX_ALWAYS_ASSERT(prob_lo.size() == AMREX_SPACEDIM); + AMREX_ALWAYS_ASSERT(prob_hi.size() == AMREX_SPACEDIM); + + pp_geometry.addarr("prob_lo", prob_lo); + pp_geometry.addarr("prob_hi", prob_hi); + + // Parse amr input, evaluating any expressions since amr does not parse its input + auto pp_amr = amrex::ParmParse{"amr"}; + + // Note that n_cell is replaced so that only the parsed version is written out to the + // warpx_job_info file. This must be done since yt expects to be able to parse + // the value of n_cell from that file. For the rest, this doesn't matter. + auto preparse_amrex_input_int_array = + [&pp_amr](const std::string& input_str, const bool replace = false) + { + const auto *const c_input_str = input_str.c_str(); + if (pp_amr.contains(c_input_str)) { + amrex::Vector input_array; + utils::parser::getArrWithParser(pp_amr,c_input_str, input_array); + if (replace) { + pp_amr.remove(c_input_str); + } + pp_amr.addarr(c_input_str, input_array); + } + }; + + preparse_amrex_input_int_array("n_cell", true); + + const auto params_to_parse = std::vector{ + "max_grid_size", "max_grid_size_x", "max_grid_size_y", "max_grid_size_z", + "blocking_factor", "blocking_factor_x", "blocking_factor_y", "blocking_factor_z"}; + std::for_each(params_to_parse.begin(), params_to_parse.end(), preparse_amrex_input_int_array); + } + + /** This method groups calls to functions related to the initialization of AMReX + * that can run only after having called amrex::Initialize + */ + void amrex_post_initialize () + { + parse_geometry_input(); + } } namespace warpx::initialization @@ -113,13 +177,18 @@ namespace warpx::initialization amrex::AMReX* amrex_init (int& argc, char**& argv, bool build_parm_parse) { - return amrex::Initialize( - argc, - argv, - build_parm_parse, - MPI_COMM_WORLD, - ::overwrite_amrex_parser_defaults - ); + amrex::AMReX* amrex = + amrex::Initialize( + argc, + argv, + build_parm_parse, + MPI_COMM_WORLD, + ::overwrite_amrex_parser_defaults + ); + + ::amrex_post_initialize(); + + return amrex; } } diff --git a/Source/Initialization/WarpXInit.H b/Source/Initialization/WarpXInit.H index ce179e2e997..85e3b8d068e 100644 --- a/Source/Initialization/WarpXInit.H +++ b/Source/Initialization/WarpXInit.H @@ -17,14 +17,23 @@ namespace warpx::initialization * @param[in] argc number of arguments from main() * @param[in] argv argument strings from main() */ - void initialize_external_libraries(int argc, char* argv[]); + void initialize_external_libraries (int argc, char* argv[]); /** Initializes, in the following order: * - the FFT library through the anyfft::cleanup() function in ablastr * - the AMReX library * - the MPI library through the mpi_finalize helper function in ablastr */ - void finalize_external_libraries(); + void finalize_external_libraries (); + + /** + * Initializes the Warning manager in ablastr + */ + void initialize_warning_manager (); + + /** Check that warpx.dims matches the binary name + */ + void check_dims (); } #endif //WARPX_INIT_H_ diff --git a/Source/Initialization/WarpXInit.cpp b/Source/Initialization/WarpXInit.cpp index 7e00760bf30..555bea52a7f 100644 --- a/Source/Initialization/WarpXInit.cpp +++ b/Source/Initialization/WarpXInit.cpp @@ -8,11 +8,17 @@ #include "WarpXInit.H" #include "Initialization/WarpXAMReXInit.H" +#include "Utils/TextMsg.H" #include +#include #include #include +#include + +#include +#include void warpx::initialization::initialize_external_libraries(int argc, char* argv[]) { @@ -21,9 +27,68 @@ void warpx::initialization::initialize_external_libraries(int argc, char* argv[] ablastr::math::anyfft::setup(); } -void warpx::initialization::finalize_external_libraries() +void warpx::initialization::finalize_external_libraries () { ablastr::math::anyfft::cleanup(); amrex::Finalize(); ablastr::parallelization::mpi_finalize(); } + +void warpx::initialization::initialize_warning_manager () +{ + const auto pp_warpx = amrex::ParmParse{"warpx"}; + + //"Synthetic" warning messages may be injected in the Warning Manager via + // inputfile for debug&testing purposes. + ablastr::warn_manager::GetWMInstance().debug_read_warnings_from_input(pp_warpx); + + // Set the flag to control if WarpX has to emit a warning message as soon as a warning is recorded + bool always_warn_immediately = false; + pp_warpx.query("always_warn_immediately", always_warn_immediately); + ablastr::warn_manager::GetWMInstance().SetAlwaysWarnImmediately(always_warn_immediately); + + // Set the WarnPriority threshold to decide if WarpX has to abort when a warning is recorded + if(std::string str_abort_on_warning_threshold; + pp_warpx.query("abort_on_warning_threshold", str_abort_on_warning_threshold)){ + std::optional abort_on_warning_threshold = std::nullopt; + if (str_abort_on_warning_threshold == "high") { + abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::high; + } else if (str_abort_on_warning_threshold == "medium" ) { + abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::medium; + } else if (str_abort_on_warning_threshold == "low") { + abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::low; + } else { + WARPX_ABORT_WITH_MESSAGE(str_abort_on_warning_threshold + +"is not a valid option for warpx.abort_on_warning_threshold (use: low, medium or high)"); + } + ablastr::warn_manager::GetWMInstance().SetAbortThreshold(abort_on_warning_threshold); + } +} + +void warpx::initialization::check_dims() +{ + // Ensure that geometry.dims is set properly. +#if defined(WARPX_DIM_3D) + std::string const dims_compiled = "3"; +#elif defined(WARPX_DIM_XZ) + std::string const dims_compiled = "2"; +#elif defined(WARPX_DIM_1D_Z) + std::string const dims_compiled = "1"; +#elif defined(WARPX_DIM_RZ) + std::string const dims_compiled = "RZ"; +#endif + const amrex::ParmParse pp_geometry("geometry"); + std::string dims; + std::string dims_error = "The selected WarpX executable was built as '"; + dims_error.append(dims_compiled).append("'-dimensional, but the "); + if (pp_geometry.contains("dims")) { + pp_geometry.get("dims", dims); + dims_error.append("inputs file declares 'geometry.dims = ").append(dims).append("'.\n"); + dims_error.append("Please re-compile with a different WarpX_DIMS option or select the right executable name."); + } else { + dims = "Not specified"; + dims_error.append("inputs file does not declare 'geometry.dims'. Please add 'geometry.dims = "); + dims_error.append(dims_compiled).append("' to inputs file."); + } + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(dims == dims_compiled, dims_error); +} diff --git a/Source/Initialization/WarpXInitData.cpp b/Source/Initialization/WarpXInitData.cpp index 149327eb7dc..1938c429989 100644 --- a/Source/Initialization/WarpXInitData.cpp +++ b/Source/Initialization/WarpXInitData.cpp @@ -17,6 +17,9 @@ #include "Diagnostics/MultiDiagnostics.H" #include "Diagnostics/ReducedDiags/MultiReducedDiags.H" #include "EmbeddedBoundary/Enabled.H" +#ifdef AMREX_USE_EB +# include "EmbeddedBoundary/EmbeddedBoundaryInit.H" +#endif #include "Fields.H" #include "FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H" #include "FieldSolver/FiniteDifferenceSolver/MacroscopicProperties/MacroscopicProperties.H" @@ -26,7 +29,6 @@ #include "Initialization/ExternalField.H" #include "Initialization/DivCleaner/ProjectionDivCleaner.H" #include "Particles/MultiParticleContainer.H" -#include "Utils/Algorithms/LinearInterpolation.H" #include "Utils/Logo/GetLogo.H" #include "Utils/Parser/ParserUtils.H" #include "Utils/TextMsg.H" @@ -37,6 +39,7 @@ #include "Python/callbacks.H" #include +#include #include #include #include @@ -90,6 +93,27 @@ using namespace amrex; namespace { + + /** Print dt and dx,dy,dz */ + void PrintDtDxDyDz ( + int max_level, const amrex::Vector& geom, const amrex::Vector& dt) + { + for (int lev=0; lev <= max_level; lev++) { + const amrex::Real* dx_lev = geom[lev].CellSize(); + amrex::Print() << "Level " << lev << ": dt = " << dt[lev] + #if defined(WARPX_DIM_1D_Z) + << " ; dz = " << dx_lev[0] << '\n'; + #elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + << " ; dx = " << dx_lev[0] + << " ; dz = " << dx_lev[1] << '\n'; + #elif defined(WARPX_DIM_3D) + << " ; dx = " << dx_lev[0] + << " ; dy = " << dx_lev[1] + << " ; dz = " << dx_lev[2] << '\n'; + #endif + } + } + /** * \brief Check that the number of guard cells is smaller than the number of valid cells, * for a given MultiFab, and abort otherwise. @@ -278,20 +302,24 @@ WarpX::PrintMainPICparameters () amrex::Print() << "Operation mode: | Electrostatic" << "\n"; amrex::Print() << " | - laboratory frame, electrostatic + magnetostatic" << "\n"; } + else if (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameEffectivePotential){ + amrex::Print() << "Operation mode: | Electrostatic" << "\n"; + amrex::Print() << " | - laboratory frame, effective potential scheme" << "\n"; + } else{ amrex::Print() << "Operation mode: | Electromagnetic" << "\n"; } - if (em_solver_medium == MediumForEM::Vacuum ){ + if (m_em_solver_medium == MediumForEM::Vacuum ){ amrex::Print() << " | - vacuum" << "\n"; } - else if (em_solver_medium == MediumForEM::Macroscopic ){ + else if (m_em_solver_medium == MediumForEM::Macroscopic ){ amrex::Print() << " | - macroscopic" << "\n"; } - if ( (em_solver_medium == MediumForEM::Macroscopic) && + if ( (m_em_solver_medium == MediumForEM::Macroscopic) && (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::LaxWendroff)){ amrex::Print() << " | - Lax-Wendroff algorithm\n"; } - else if ((em_solver_medium == MediumForEM::Macroscopic) && + else if ((m_em_solver_medium == MediumForEM::Macroscopic) && (WarpX::macroscopic_solver_algo == MacroscopicSolverAlgo::BackwardEuler)){ amrex::Print() << " | - Backward Euler algorithm\n"; } @@ -529,20 +557,20 @@ WarpX::InitData () // WarpX::computeMaxStepBoostAccelerator // needs to start from the initial zmin_domain_boost, // even if restarting from a checkpoint file - if (do_compute_max_step_from_zmax) { + if (m_zmax_plasma_to_compute_max_step.has_value()) { zmin_domain_boost_step_0 = geom[0].ProbLo(WARPX_ZINDEX); } if (restart_chkfile.empty()) { ComputeDt(); - WarpX::PrintDtDxDyDz(); + ::PrintDtDxDyDz(max_level, geom, dt); InitFromScratch(); InitDiagnostics(); } else { InitFromCheckpoint(); - WarpX::PrintDtDxDyDz(); + ::PrintDtDxDyDz(max_level, geom, dt); PostRestart(); reduced_diags->InitData(); } @@ -557,7 +585,7 @@ WarpX::InitData () BuildBufferMasks(); - if (WarpX::em_solver_medium == MediumForEM::Macroscopic) { + if (m_em_solver_medium == MediumForEM::Macroscopic) { const int lev_zero = 0; m_macroscopic_properties->InitData( Geom(lev_zero), @@ -589,7 +617,7 @@ WarpX::InitData () WriteUsedInputsFile(); // Run div cleaner here on loaded external fields - if (WarpX::do_divb_cleaning_external) { + if (m_do_divb_cleaning_external) { WarpX::ProjectionCleanDivB(); } @@ -609,6 +637,9 @@ WarpX::InitData () AddExternalFields(lev); } } + else { + ExecutePythonCallback("afterInitatRestart"); + } if (restart_chkfile.empty() || write_diagnostics_on_restart) { // Write full diagnostics before the first iteration. @@ -687,21 +718,7 @@ WarpX::InitFromScratch () m_implicit_solver->Define(this); m_implicit_solver->GetParticleSolverParams( max_particle_its_in_implicit_scheme, particle_tol_in_implicit_scheme ); - - // Add space to save the positions and velocities at the start of the time steps - for (auto const& pc : *mypc) { -#if (AMREX_SPACEDIM >= 2) - pc->NewRealComp("x_n"); -#endif -#if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - pc->NewRealComp("y_n"); -#endif - pc->NewRealComp("z_n"); - pc->NewRealComp("ux_n"); - pc->NewRealComp("uy_n"); - pc->NewRealComp("uz_n"); - } - + m_implicit_solver->CreateParticleAttributes(); } mypc->AllocData(); @@ -740,7 +757,7 @@ WarpX::InitPML () pml_ncell, pml_delta, amrex::IntVect::TheZeroVector(), dt[0], nox_fft, noy_fft, noz_fft, grid_type, do_moving_window, pml_has_particles, do_pml_in_domain, - psatd_solution_type, J_in_time, rho_in_time, + m_psatd_solution_type, J_in_time, rho_in_time, do_pml_dive_cleaning, do_pml_divb_cleaning, amrex::IntVect(0), amrex::IntVect(0), eb_enabled, @@ -781,7 +798,7 @@ WarpX::InitPML () pml_ncell, pml_delta, refRatio(lev-1), dt[lev], nox_fft, noy_fft, noz_fft, grid_type, do_moving_window, pml_has_particles, do_pml_in_domain, - psatd_solution_type, J_in_time, rho_in_time, do_pml_dive_cleaning, do_pml_divb_cleaning, + m_psatd_solution_type, J_in_time, rho_in_time, do_pml_dive_cleaning, do_pml_divb_cleaning, amrex::IntVect(0), amrex::IntVect(0), eb_enabled, guard_cells.ng_FieldSolver.max(), @@ -808,7 +825,7 @@ WarpX::ComputePMLFactors () void WarpX::ComputeMaxStep () { - if (do_compute_max_step_from_zmax) { + if (m_zmax_plasma_to_compute_max_step.has_value()) { computeMaxStepBoostAccelerator(); } } @@ -841,7 +858,7 @@ WarpX::computeMaxStepBoostAccelerator() { // End of the plasma: Transform input argument // zmax_plasma_to_compute_max_step to boosted frame. - const Real len_plasma_boost = zmax_plasma_to_compute_max_step/gamma_boost; + const Real len_plasma_boost = m_zmax_plasma_to_compute_max_step.value()/gamma_boost; // Plasma velocity const Real v_plasma_boost = -beta_boost * PhysConst::c; // Get time at which the lower end of the simulation domain passes the @@ -849,7 +866,7 @@ WarpX::computeMaxStepBoostAccelerator() { const Real interaction_time_boost = (len_plasma_boost-zmin_domain_boost_step_0)/ (moving_window_v-v_plasma_boost); // Divide by dt, and update value of max_step. - const auto computed_max_step = (do_subcycling)? + const auto computed_max_step = (m_do_subcycling)? static_cast(interaction_time_boost/dt[0]): static_cast(interaction_time_boost/dt[maxLevel()]); max_step = computed_max_step; @@ -975,23 +992,20 @@ WarpX::InitLevelData (int lev, Real /*time*/) // The default maxlevel_extEMfield_init value is the total number of levels in the simulation if ((m_p_ext_field_params->B_ext_grid_type == ExternalFieldType::parse_ext_grid_function) && (lev > 0) && (lev <= maxlevel_extEMfield_init)) { + ComputeExternalFieldOnGridUsingParser( FieldType::Bfield_aux, m_p_ext_field_params->Bxfield_parser->compile<4>(), m_p_ext_field_params->Byfield_parser->compile<4>(), m_p_ext_field_params->Bzfield_parser->compile<4>(), - lev, PatchType::fine, 'f', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, m_eb_update_B); ComputeExternalFieldOnGridUsingParser( FieldType::Bfield_cp, m_p_ext_field_params->Bxfield_parser->compile<4>(), m_p_ext_field_params->Byfield_parser->compile<4>(), m_p_ext_field_params->Bzfield_parser->compile<4>(), - lev, PatchType::coarse, 'f', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_mr_levels_alldirs(FieldType::face_areas, max_level)[lev]); + lev, PatchType::coarse, m_eb_update_B); } // if the input string for the E-field is "parse_e_ext_grid_function", @@ -1022,18 +1036,14 @@ WarpX::InitLevelData (int lev, Real /*time*/) m_p_ext_field_params->Exfield_parser->compile<4>(), m_p_ext_field_params->Eyfield_parser->compile<4>(), m_p_ext_field_params->Ezfield_parser->compile<4>(), - lev, PatchType::fine, 'e', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, m_eb_update_E); ComputeExternalFieldOnGridUsingParser( FieldType::Efield_cp, m_p_ext_field_params->Exfield_parser->compile<4>(), m_p_ext_field_params->Eyfield_parser->compile<4>(), m_p_ext_field_params->Ezfield_parser->compile<4>(), - lev, PatchType::coarse, 'e', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::coarse, m_eb_update_E); #ifdef AMREX_USE_EB if (eb_enabled) { if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { @@ -1062,21 +1072,25 @@ WarpX::InitLevelData (int lev, Real /*time*/) } } -void WarpX::ComputeExternalFieldOnGridUsingParser ( - warpx::fields::FieldType field, +template +void ComputeExternalFieldOnGridUsingParser_template ( + T field, amrex::ParserExecutor<4> const& fx_parser, amrex::ParserExecutor<4> const& fy_parser, amrex::ParserExecutor<4> const& fz_parser, - int lev, PatchType patch_type, [[maybe_unused]] const char topology, - std::optional const& edge_lengths, - std::optional const& face_areas) + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field, + bool use_eb_flags) { - auto t = gett_new(lev); + auto &warpx = WarpX::GetInstance(); + auto const &geom = warpx.Geom(lev); + + auto t = warpx.gett_new(lev); - auto dx_lev = geom[lev].CellSizeArray(); - const RealBox& real_box = geom[lev].ProbDomain(); + auto dx_lev = geom.CellSizeArray(); + const RealBox& real_box = geom.ProbDomain(); - amrex::IntVect refratio = (lev > 0 ) ? RefRatio(lev-1) : amrex::IntVect(1); + amrex::IntVect refratio = (lev > 0 ) ? WarpX::RefRatio(lev-1) : amrex::IntVect(1); if (patch_type == PatchType::coarse) { for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { dx_lev[idim] = dx_lev[idim] * refratio[idim]; @@ -1084,16 +1098,14 @@ void WarpX::ComputeExternalFieldOnGridUsingParser ( } using ablastr::fields::Direction; - amrex::MultiFab* mfx = m_fields.get(field, Direction{0}, lev); - amrex::MultiFab* mfy = m_fields.get(field, Direction{1}, lev); - amrex::MultiFab* mfz = m_fields.get(field, Direction{2}, lev); + amrex::MultiFab* mfx = warpx.m_fields.get(field, Direction{0}, lev); + amrex::MultiFab* mfy = warpx.m_fields.get(field, Direction{1}, lev); + amrex::MultiFab* mfz = warpx.m_fields.get(field, Direction{2}, lev); const amrex::IntVect x_nodal_flag = mfx->ixType().toIntVect(); const amrex::IntVect y_nodal_flag = mfy->ixType().toIntVect(); const amrex::IntVect z_nodal_flag = mfz->ixType().toIntVect(); - const bool eb_enabled = EB::enabled(); - for ( MFIter mfi(*mfx, TilingIfNotGPU()); mfi.isValid(); ++mfi) { const amrex::Box& tbx = mfi.tilebox( x_nodal_flag, mfx->nGrowVect() ); const amrex::Box& tby = mfi.tilebox( y_nodal_flag, mfy->nGrowVect() ); @@ -1103,44 +1115,19 @@ void WarpX::ComputeExternalFieldOnGridUsingParser ( auto const& mfyfab = mfy->array(mfi); auto const& mfzfab = mfz->array(mfi); - amrex::Array4 lx, ly, lz, Sx, Sy, Sz; - if (eb_enabled) { - if (edge_lengths.has_value()) { - const auto& edge_lengths_array = edge_lengths.value(); - lx = edge_lengths_array[0]->array(mfi); - ly = edge_lengths_array[1]->array(mfi); - lz = edge_lengths_array[2]->array(mfi); - } - if (face_areas.has_value()) { - const auto& face_areas_array = face_areas.value(); - Sx = face_areas_array[0]->array(mfi); - Sy = face_areas_array[1]->array(mfi); - Sz = face_areas_array[2]->array(mfi); - } - } - -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - amrex::Dim3 lx_lo, lx_hi, lz_lo, lz_hi; -#endif - if (eb_enabled) { -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - lx_lo = amrex::lbound(lx); - lx_hi = amrex::ubound(lx); - lz_lo = amrex::lbound(lz); - lz_hi = amrex::ubound(lz); -#endif + amrex::Array4 update_fx_arr, update_fy_arr, update_fz_arr; + if (use_eb_flags && EB::enabled()) { + update_fx_arr = eb_update_field[lev][0]->array(mfi); + update_fy_arr = eb_update_field[lev][1]->array(mfi); + update_fz_arr = eb_update_field[lev][2]->array(mfi); } amrex::ParallelFor (tbx, tby, tbz, [=] AMREX_GPU_DEVICE (int i, int j, int k) { -#ifdef AMREX_USE_EB -#ifdef WARPX_DIM_3D - if(lx && ((topology=='e' and lx(i, j, k)<=0) or (topology=='f' and Sx(i, j, k)<=0))) { return; } -#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - //In XZ and RZ Ex is associated with a x-edge, while Bx is associated with a z-edge - if(lx && ((topology=='e' and lx(i, j, k)<=0) or (topology=='f' and lz(i, j, k)<=0))) { return; } -#endif -#endif + + // Do not set fields inside the embedded boundary + if (update_fx_arr && update_fx_arr(i,j,k) == 0) { return; } + // Shift required in the x-, y-, or z- position // depending on the index type of the multifab #if defined(WARPX_DIM_1D_Z) @@ -1166,19 +1153,10 @@ void WarpX::ComputeExternalFieldOnGridUsingParser ( mfxfab(i,j,k) = fx_parser(x,y,z,t); }, [=] AMREX_GPU_DEVICE (int i, int j, int k) { -#ifdef AMREX_USE_EB -#ifdef WARPX_DIM_3D - if(ly && ((topology=='e' and ly(i, j, k)<=0) or (topology=='f' and Sy(i, j, k)<=0))) { return; } -#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - //In XZ and RZ Ey is associated with a mesh node, so we need to check if the mesh node is covered - if(lx && - ((topology=='e' and (lx(std::min(i , lx_hi.x), std::min(j , lx_hi.y), k)<=0 - || lx(std::max(i-1, lx_lo.x), std::min(j , lx_hi.y), k)<=0 - || lz(std::min(i , lz_hi.x), std::min(j , lz_hi.y), k)<=0 - || lz(std::min(i , lz_hi.x), std::max(j-1, lz_lo.y), k)<=0)) or - (topology=='f' and Sy(i,j,k)<=0))) { return; } -#endif -#endif + + // Do not set fields inside the embedded boundary + if (update_fy_arr && update_fy_arr(i,j,k) == 0) { return; } + #if defined(WARPX_DIM_1D_Z) const amrex::Real x = 0._rt; const amrex::Real y = 0._rt; @@ -1202,14 +1180,10 @@ void WarpX::ComputeExternalFieldOnGridUsingParser ( mfyfab(i,j,k) = fy_parser(x,y,z,t); }, [=] AMREX_GPU_DEVICE (int i, int j, int k) { -#ifdef AMREX_USE_EB -#ifdef WARPX_DIM_3D - if(lz && ((topology=='e' and lz(i, j, k)<=0) or (topology=='f' and Sz(i, j, k)<=0))) { return; } -#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - //In XZ and RZ Ez is associated with a z-edge, while Bz is associated with a x-edge - if(lz && ((topology=='e' and lz(i, j, k)<=0) or (topology=='f' and lx(i, j, k)<=0))) { return; } -#endif -#endif + + // Do not set fields inside the embedded boundary + if (update_fz_arr && update_fz_arr(i,j,k) == 0) { return; } + #if defined(WARPX_DIM_1D_Z) const amrex::Real x = 0._rt; const amrex::Real y = 0._rt; @@ -1236,6 +1210,68 @@ void WarpX::ComputeExternalFieldOnGridUsingParser ( } } +void WarpX::ComputeExternalFieldOnGridUsingParser ( + warpx::fields::FieldType field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field, + bool use_eb_flags) +{ + ComputeExternalFieldOnGridUsingParser_template ( + field, + fx_parser, fy_parser, fz_parser, + lev, patch_type, eb_update_field, + use_eb_flags); +} + +void WarpX::ComputeExternalFieldOnGridUsingParser ( + std::string const& field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field, + bool use_eb_flags) +{ + ComputeExternalFieldOnGridUsingParser_template ( + field, + fx_parser, fy_parser, fz_parser, + lev, patch_type, eb_update_field, + use_eb_flags); +} + +void WarpX::ComputeExternalFieldOnGridUsingParser ( + warpx::fields::FieldType field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field) +{ + ComputeExternalFieldOnGridUsingParser_template ( + field, + fx_parser, fy_parser, fz_parser, + lev, patch_type, eb_update_field, + true); +} + +void WarpX::ComputeExternalFieldOnGridUsingParser ( + std::string const& field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field) +{ + ComputeExternalFieldOnGridUsingParser_template ( + field, + fx_parser, fy_parser, fz_parser, + lev, patch_type, eb_update_field, + true); +} + void WarpX::CheckGuardCells() { for (int lev = 0; lev <= max_level; ++lev) @@ -1285,35 +1321,53 @@ void WarpX::InitializeEBGridData (int lev) #ifdef AMREX_USE_EB if (lev == maxLevel()) { - // Throw a warning if EB is on and particle_shape > 1 - if ((nox > 1 or noy > 1 or noz > 1) and EB::enabled()) - { - ablastr::warn_manager::WMRecordWarning("Particles", - "when algo.particle_shape > 1, numerical artifacts will be present when\n" - "particles are close to embedded boundaries"); - } + auto const eb_fact = fieldEBFactory(lev); if (WarpX::electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD ) { using warpx::fields::FieldType; - auto const eb_fact = fieldEBFactory(lev); + if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { - auto edge_lengths_lev = m_fields.get_alldirs(FieldType::edge_lengths, lev); - ComputeEdgeLengths(edge_lengths_lev, eb_fact); - ScaleEdges(edge_lengths_lev, CellSize(lev)); + auto edge_lengths_lev = m_fields.get_alldirs(FieldType::edge_lengths, lev); + warpx::embedded_boundary::ComputeEdgeLengths(edge_lengths_lev, eb_fact); + warpx::embedded_boundary::ScaleEdges(edge_lengths_lev, CellSize(lev)); + + auto face_areas_lev = m_fields.get_alldirs(FieldType::face_areas, lev); + warpx::embedded_boundary::ComputeFaceAreas(face_areas_lev, eb_fact); + warpx::embedded_boundary::ScaleAreas(face_areas_lev, CellSize(lev)); + + // Compute additional quantities required for the ECT solver + const auto& area_mod = m_fields.get_alldirs(FieldType::area_mod, maxLevel()); + warpx::embedded_boundary::MarkExtensionCells( + CellSize(maxLevel()), m_flag_info_face[maxLevel()], m_flag_ext_face[maxLevel()], + m_fields.get_alldirs(FieldType::Bfield_fp, maxLevel()), + face_areas_lev, + edge_lengths_lev, area_mod); + ComputeFaceExtensions(); - auto face_areas_lev = m_fields.get_alldirs(FieldType::face_areas, lev); - ComputeFaceAreas(face_areas_lev, eb_fact); - ScaleAreas(face_areas_lev, CellSize(lev)); + // Mark on which grid points E should be updated + warpx::embedded_boundary::MarkUpdateECellsECT( m_eb_update_E[lev], edge_lengths_lev ); + // Mark on which grid points B should be updated + warpx::embedded_boundary::MarkUpdateBCellsECT( m_eb_update_B[lev], face_areas_lev, edge_lengths_lev); - if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { - MarkCells(); - ComputeFaceExtensions(); + } else { + // Mark on which grid points E should be updated (stair-case approximation) + warpx::embedded_boundary::MarkUpdateCellsStairCase( + m_eb_update_E[lev], + m_fields.get_alldirs(FieldType::Efield_fp, lev), + eb_fact ); + // Mark on which grid points B should be updated (stair-case approximation) + warpx::embedded_boundary::MarkUpdateCellsStairCase( + m_eb_update_B[lev], + m_fields.get_alldirs(FieldType::Bfield_fp, lev), + eb_fact ); } + } ComputeDistanceToEB(); + warpx::embedded_boundary::MarkReducedShapeCells( m_eb_reduce_particle_shape[lev], eb_fact, nox, Geom(0).periodicity()); } #else @@ -1394,9 +1448,7 @@ WarpX::LoadExternalFields (int const lev) m_p_ext_field_params->Bxfield_parser->compile<4>(), m_p_ext_field_params->Byfield_parser->compile<4>(), m_p_ext_field_params->Bzfield_parser->compile<4>(), - lev, PatchType::fine, 'f', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, m_eb_update_B); } else if (m_p_ext_field_params->B_ext_grid_type == ExternalFieldType::read_from_file) { #if defined(WARPX_DIM_RZ) @@ -1419,9 +1471,7 @@ WarpX::LoadExternalFields (int const lev) m_p_ext_field_params->Exfield_parser->compile<4>(), m_p_ext_field_params->Eyfield_parser->compile<4>(), m_p_ext_field_params->Ezfield_parser->compile<4>(), - lev, PatchType::fine, 'e', - m_fields.get_alldirs(FieldType::edge_lengths, lev), - m_fields.get_alldirs(FieldType::face_areas, lev)); + lev, PatchType::fine, m_eb_update_E ); } else if (m_p_ext_field_params->E_ext_grid_type == ExternalFieldType::read_from_file) { #if defined(WARPX_DIM_RZ) @@ -1651,7 +1701,7 @@ WarpX::ReadExternalFieldFromFile ( f01 = fc_array(0, iz , ir+1), f10 = fc_array(0, iz+1, ir ), f11 = fc_array(0, iz+1, ir+1); - mffab(i,j,k) = static_cast(utils::algorithms::bilinear_interp + mffab(i,j,k) = static_cast(ablastr::math::bilinear_interp (xx0, xx0+file_dr, xx1, xx1+file_dz, f00, f01, f10, f11, x0, x1)); @@ -1666,7 +1716,7 @@ WarpX::ReadExternalFieldFromFile ( f101 = fc_array(iz+1, iy , ix+1), f110 = fc_array(iz , iy+1, ix+1), f111 = fc_array(iz+1, iy+1, ix+1); - mffab(i,j,k) = static_cast(utils::algorithms::trilinear_interp + mffab(i,j,k) = static_cast(ablastr::math::trilinear_interp (xx0, xx0+file_dx, xx1, xx1+file_dy, xx2, xx2+file_dz, f000, f001, f010, f011, f100, f101, f110, f111, x0, x1, x2)); diff --git a/Source/Laser/LaserProfilesImpl/LaserProfileFromFile.cpp b/Source/Laser/LaserProfilesImpl/LaserProfileFromFile.cpp index 934a537be5a..0ce5e71337f 100644 --- a/Source/Laser/LaserProfilesImpl/LaserProfileFromFile.cpp +++ b/Source/Laser/LaserProfilesImpl/LaserProfileFromFile.cpp @@ -6,12 +6,12 @@ */ #include "Laser/LaserProfiles.H" -#include "Utils/Algorithms/LinearInterpolation.H" #include "Utils/Parser/ParserUtils.H" #include "Utils/TextMsg.H" #include "Utils/WarpX_Complex.H" #include "Utils/WarpXConst.H" +#include #include #include @@ -489,7 +489,7 @@ WarpXLaserProfiles::FromFileLaserProfile::internal_fill_amplitude_uniform_cartes (i_interp-tmp_idx_first_time)*tmp_nx*tmp_ny+ j_interp*tmp_nx + k_interp; }; - const Complex val = utils::algorithms::trilinear_interp( + const Complex val = ablastr::math::trilinear_interp( t_left, t_right, x_0, x_1, y_0, y_1, @@ -574,33 +574,35 @@ WarpXLaserProfiles::FromFileLaserProfile::internal_fill_amplitude_uniform_cylind Complex fact = Complex{costheta, sintheta}; // azimuthal mode 0 - val += utils::algorithms::bilinear_interp( - t_left, t_right, - r_0, r_1, - p_E_lasy_data[idx(0, idx_t_left, idx_r_left)], - p_E_lasy_data[idx(0, idx_t_left, idx_r_right)], - p_E_lasy_data[idx(0, idx_t_right, idx_r_left)], - p_E_lasy_data[idx(0, idx_t_right, idx_r_right)], - t, Rp_i); + val += + ablastr::math::bilinear_interp( + t_left, t_right, + r_0, r_1, + p_E_lasy_data[idx(0, idx_t_left, idx_r_left)], + p_E_lasy_data[idx(0, idx_t_left, idx_r_right)], + p_E_lasy_data[idx(0, idx_t_right, idx_r_left)], + p_E_lasy_data[idx(0, idx_t_right, idx_r_right)], + t, Rp_i); // higher modes for (int m=1 ; m <= tmp_n_rz_azimuthal_components/2; m++) { - val += utils::algorithms::bilinear_interp( - t_left, t_right, - r_0, r_1, - p_E_lasy_data[idx(2*m-1, idx_t_left, idx_r_left)], - p_E_lasy_data[idx(2*m-1, idx_t_left, idx_r_right)], - p_E_lasy_data[idx(2*m-1, idx_t_right, idx_r_left)], - p_E_lasy_data[idx(2*m-1, idx_t_right, idx_r_right)], - t, Rp_i)*(fact.real()) + - utils::algorithms::bilinear_interp( - t_left, t_right, - r_0, r_1, - p_E_lasy_data[idx(2*m, idx_t_left, idx_r_left)], - p_E_lasy_data[idx(2*m, idx_t_left, idx_r_right)], - p_E_lasy_data[idx(2*m, idx_t_right, idx_r_left)], - p_E_lasy_data[idx(2*m, idx_t_right, idx_r_right)], - t, Rp_i)*(fact.imag()) ; + val += + ablastr::math::bilinear_interp( + t_left, t_right, + r_0, r_1, + p_E_lasy_data[idx(2*m-1, idx_t_left, idx_r_left)], + p_E_lasy_data[idx(2*m-1, idx_t_left, idx_r_right)], + p_E_lasy_data[idx(2*m-1, idx_t_right, idx_r_left)], + p_E_lasy_data[idx(2*m-1, idx_t_right, idx_r_right)], + t, Rp_i)*(fact.real()) + + ablastr::math::bilinear_interp( + t_left, t_right, + r_0, r_1, + p_E_lasy_data[idx(2*m, idx_t_left, idx_r_left)], + p_E_lasy_data[idx(2*m, idx_t_left, idx_r_right)], + p_E_lasy_data[idx(2*m, idx_t_right, idx_r_left)], + p_E_lasy_data[idx(2*m, idx_t_right, idx_r_right)], + t, Rp_i)*(fact.imag()) ; fact = fact*Complex{costheta, sintheta}; } amplitude[i] = (val*exp_omega_t).real(); @@ -683,7 +685,7 @@ WarpXLaserProfiles::FromFileLaserProfile::internal_fill_amplitude_uniform_binary (i_interp-tmp_idx_first_time)*tmp_nx*tmp_ny+ j_interp*tmp_ny + k_interp; }; - amplitude[i] = utils::algorithms::trilinear_interp( + amplitude[i] = ablastr::math::trilinear_interp( t_left, t_right, x_0, x_1, y_0, y_1, @@ -702,7 +704,7 @@ WarpXLaserProfiles::FromFileLaserProfile::internal_fill_amplitude_uniform_binary const auto idx = [=](int i_interp, int j_interp){ return (i_interp-tmp_idx_first_time) * tmp_nx + j_interp; }; - amplitude[i] = utils::algorithms::bilinear_interp( + amplitude[i] = ablastr::math::bilinear_interp( t_left, t_right, x_0, x_1, p_E_binary_data[idx(idx_t_left, idx_x_left)], diff --git a/Source/Laser/LaserProfilesImpl/LaserProfileGaussian.cpp b/Source/Laser/LaserProfilesImpl/LaserProfileGaussian.cpp index 96d61d920f1..a1162e9a7a5 100644 --- a/Source/Laser/LaserProfilesImpl/LaserProfileGaussian.cpp +++ b/Source/Laser/LaserProfilesImpl/LaserProfileGaussian.cpp @@ -117,8 +117,8 @@ WarpXLaserProfiles::GaussianLaserProfile::fill_amplitude ( // Time stretching due to STCs and phi2 complex envelope // (1 if zeta=0, beta=0, phi2=0) const Complex stretch_factor = 1._rt + 4._rt * - (m_params.zeta+m_params.beta*m_params.focal_distance*inv_tau2) - * (m_params.zeta+m_params.beta*m_params.focal_distance*inv_complex_waist_2) + ((m_params.zeta+m_params.beta*m_params.focal_distance)*inv_tau2) + * ((m_params.zeta+m_params.beta*m_params.focal_distance)*inv_complex_waist_2) + 2._rt*I*(m_params.phi2-m_params.beta*m_params.beta*k0*m_params.focal_distance)*inv_tau2; // Amplitude and monochromatic oscillations diff --git a/Source/Make.WarpX b/Source/Make.WarpX index 57bac56e9a4..6563121e336 100644 --- a/Source/Make.WarpX +++ b/Source/Make.WarpX @@ -151,7 +151,7 @@ endif ifeq ($(USE_OPENPMD), TRUE) # try pkg-config query - ifeq (0, $(shell pkg-config "openPMD >= 0.15.1"; echo $$?)) + ifeq (0, $(shell pkg-config "openPMD >= 0.16.1"; echo $$?)) CXXFLAGS += $(shell pkg-config --cflags openPMD) LIBRARY_LOCATIONS += $(shell pkg-config --variable=libdir openPMD) libraries += $(shell pkg-config --libs-only-l openPMD) diff --git a/Source/NonlinearSolvers/CurlCurlMLMGPC.H b/Source/NonlinearSolvers/CurlCurlMLMGPC.H new file mode 100644 index 00000000000..b3fcc6fe38f --- /dev/null +++ b/Source/NonlinearSolvers/CurlCurlMLMGPC.H @@ -0,0 +1,356 @@ +/* Copyright 2024 Debojyoti Ghosh + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ +#ifndef CURL_CURL_MLMG_PC_H_ +#define CURL_CURL_MLMG_PC_H_ + +#include "Fields.H" +#include "Utils/WarpXConst.H" +#include "Preconditioner.H" + +#include + +#include +#include +#include +#include +#include +#ifndef WARPX_DIM_1D_Z // currently not implemented in 1D +#include +#include +#include +#include +#endif + +/** + * \brief Curl-curl Preconditioner + * + * Preconditioner that solves the curl-curl equation for the E-field, given + * a RHS. Uses AMReX's curl-curl linear operator and multigrid solver. + * + * The equation solves for Eg in: + * curl ( alpha * curl ( Eg ) ) + beta * Eg = b + * where + * + alpha is a scalar + * + beta can either be a scalar that is constant in space or a MultiFab + * + Eg is the electric field. + * + b is a specified RHS with the same layout as Eg + * + * This class is templated on a solution-type class T and an operator class Ops. + * + * The Ops class must have the following function: + * + Return number of AMR levels + * + Return the amrex::Geometry object given an AMR level + * + Return hi and lo linear operator boundaries + * + Return the time step factor (theta) for the time integration scheme + * + * The T class must have the following functions: + * + Return underlying vector of amrex::MultiFab arrays + */ + +template +class CurlCurlMLMGPC : public Preconditioner +{ + public: + + using RT = typename T::value_type; + + /** + * \brief Default constructor + */ + CurlCurlMLMGPC () = default; + + /** + * \brief Default destructor + */ + ~CurlCurlMLMGPC () override = default; + + // Prohibit move and copy operations + CurlCurlMLMGPC(const CurlCurlMLMGPC&) = delete; + CurlCurlMLMGPC& operator=(const CurlCurlMLMGPC&) = delete; + CurlCurlMLMGPC(CurlCurlMLMGPC&&) noexcept = delete; + CurlCurlMLMGPC& operator=(CurlCurlMLMGPC&&) noexcept = delete; + + /** + * \brief Define the preconditioner + */ + void Define (const T&, Ops*) override; + + /** + * \brief Update the preconditioner + */ + void Update (const T&) override; + + /** + * \brief Apply (solve) the preconditioner given a RHS + * + * Given a right-hand-side b, solve: + * A x = b + * where A is the linear operator, in this case, the curl-curl operator: + * A x = curl (alpha * curl (x) ) + beta * x + */ + void Apply (T&, const T&) override; + + /** + * \brief Print parameters + */ + void printParameters() const override; + + /** + * \brief Check if the nonlinear solver has been defined. + */ + [[nodiscard]] inline bool IsDefined () const override { return m_is_defined; } + + protected: + + using MFArr = amrex::Array; + + bool m_is_defined = false; + + bool m_verbose = true; + bool m_bottom_verbose = false; + bool m_agglomeration = true; + bool m_consolidation = true; + bool m_use_gmres = false; + bool m_use_gmres_pc = true; + + int m_max_iter = 10; + int m_max_coarsening_level = 30; + + RT m_atol = 1.0e-16; + RT m_rtol = 1.0e-4; + + Ops* m_ops = nullptr; + + int m_num_amr_levels = 0; + amrex::Vector m_geom; + amrex::Vector m_grids; + amrex::Vector m_dmap; + amrex::IntVect m_gv; + +// currently not implemented in 1D +#ifndef WARPX_DIM_1D_Z + amrex::Array m_bc_lo; + amrex::Array m_bc_hi; + + std::unique_ptr m_info; + std::unique_ptr m_curl_curl; + std::unique_ptr> m_solver; + std::unique_ptr> m_gmres_solver; +#endif + + /** + * \brief Read parameters + */ + void readParameters(); + + private: + +}; + +template +void CurlCurlMLMGPC::printParameters() const +{ + using namespace amrex; + auto pc_name = getEnumNameString(PreconditionerType::pc_curl_curl_mlmg); + Print() << pc_name << " verbose: " << (m_verbose?"true":"false") << "\n"; + Print() << pc_name << " bottom verbose: " << (m_bottom_verbose?"true":"false") << "\n"; + Print() << pc_name << " max iter: " << m_max_iter << "\n"; + Print() << pc_name << " agglomeration: " << m_agglomeration << "\n"; + Print() << pc_name << " consolidation: " << m_consolidation << "\n"; + Print() << pc_name << " max_coarsening_level: " << m_max_coarsening_level << "\n"; + Print() << pc_name << " absolute tolerance: " << m_atol << "\n"; + Print() << pc_name << " relative tolerance: " << m_rtol << "\n"; + Print() << pc_name << " use GMRES: " << (m_use_gmres?"true":"false") << "\n"; + if (m_use_gmres) { + Print() << pc_name + << " use PC for GMRES: " + << (m_use_gmres_pc?"true":"false") << "\n"; + } +} + +template +void CurlCurlMLMGPC::readParameters() +{ + const amrex::ParmParse pp(amrex::getEnumNameString(PreconditionerType::pc_curl_curl_mlmg)); + pp.query("verbose", m_verbose); + pp.query("bottom_verbose", m_bottom_verbose); + pp.query("max_iter", m_max_iter); + pp.query("agglomeration", m_agglomeration); + pp.query("consolidation", m_consolidation); + pp.query("max_coarsening_level", m_max_coarsening_level); + pp.query("absolute_tolerance", m_atol); + pp.query("relative_tolerance", m_rtol); + pp.query("use_gmres", m_use_gmres); + pp.query("use_gmres_pc", m_use_gmres_pc); +} + +template +void CurlCurlMLMGPC::Define ( const T& a_U, + Ops* const a_ops ) +{ + using namespace amrex; + + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + !IsDefined(), + "CurlCurlMLMGPC::Define() called on defined object" ); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + (a_ops != nullptr), + "CurlCurlMLMGPC::Define(): a_ops is nullptr" ); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + a_U.getArrayVecType()==warpx::fields::FieldType::Efield_fp, + "CurlCurlMLMGPC::Define() must be called with Efield_fp type"); + + m_ops = a_ops; + // read preconditioner parameters + readParameters(); + +// currently not implemented in 1D +#ifdef WARPX_DIM_1D_Z + WARPX_ABORT_WITH_MESSAGE("CurlCurlMLMGPC not yet implemented for 1D"); +#else + // create info object for curl-curl op + m_info = std::make_unique(); + m_info->setAgglomeration(m_agglomeration); + m_info->setConsolidation(m_consolidation); + m_info->setMaxCoarseningLevel(m_max_coarsening_level); + + // Get data vectors from a_U + auto& u_mfarrvec = a_U.getArrayVec(); + + // Set number of AMR levels and create geometry, grids, and + // distribution mapping vectors. + m_num_amr_levels = m_ops->numAMRLevels(); + m_geom.resize(m_num_amr_levels); + m_grids.resize(m_num_amr_levels); + m_dmap.resize(m_num_amr_levels); + for (int n = 0; n < m_num_amr_levels; n++) { + m_geom[n] = m_ops->GetGeometry(n); + m_dmap[n] = u_mfarrvec[n][0]->DistributionMap(); + + BoxArray ba = u_mfarrvec[n][0]->boxArray(); + m_grids[n] = ba.enclosedCells(); + } + + // Construct the curl-curl linear operator and set its BCs + m_curl_curl = std::make_unique(m_geom, m_grids, m_dmap, *m_info); + m_curl_curl->setDomainBC(m_ops->GetLinOpBCLo(), m_ops->GetLinOpBCHi()); + + // Dummy value for alpha and beta to avoid abort due to degenerate matrix by MLMG solver + m_curl_curl->setScalars(1.0, 1.0); + + // Construct the MLMG solver + m_solver = std::make_unique>(*m_curl_curl); + m_solver->setMaxIter(m_max_iter); + m_solver->setFixedIter(m_max_iter); + m_solver->setVerbose(static_cast(m_verbose)); + m_solver->setBottomVerbose(static_cast(m_bottom_verbose)); + + // If using GMRES solver, construct it + if (m_use_gmres) { + m_gmres_solver = std::make_unique>(*m_solver); + m_gmres_solver->usePrecond(m_use_gmres_pc); + m_gmres_solver->setPrecondNumIters(m_max_iter); + m_gmres_solver->setVerbose(static_cast(m_verbose)); + } +#endif + + m_is_defined = true; +} + +template +void CurlCurlMLMGPC::Update (const T& a_U) +{ + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + IsDefined(), + "CurlCurlMLMGPC::Update() called on undefined object" ); + + // a_U is not needed for a linear operator + amrex::ignore_unused(a_U); + + // set the coefficients alpha and beta for curl-curl op + // (m_dt here is actually theta<=0.5 times simulation dt) + const RT alpha = (this->m_dt*PhysConst::c) * (this->m_dt*PhysConst::c); + const RT beta = RT(1.0); + +// currently not implemented in 1D +#ifndef WARPX_DIM_1D_Z + m_curl_curl->setScalars(alpha, beta); +#endif + + if (m_verbose) { + amrex::Print() << "Updating " << amrex::getEnumNameString(PreconditionerType::pc_curl_curl_mlmg) + << ": theta*dt = " << this->m_dt << ", " + << " coefficients: " + << "alpha = " << alpha << ", " + << "beta = " << beta << "\n"; + } +} + +template +void CurlCurlMLMGPC::Apply (T& a_x, const T& a_b) +{ + // Given a right-hand-side b, solve: + // A x = b + // where A is the linear operator, in this case, the curl-curl + // operator: + // A x = curl (alpha * curl (x) ) + beta * x + + using namespace amrex; + + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + IsDefined(), + "CurlCurlMLMGPC::Apply() called on undefined object" ); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + a_x.getArrayVecType()==warpx::fields::FieldType::Efield_fp, + "CurlCurlMLMGPC::Apply() - a_x must be Efield_fp type"); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + a_b.getArrayVecType()==warpx::fields::FieldType::Efield_fp, + "CurlCurlMLMGPC::Apply() - a_b must be Efield_fp type"); + + // Get the data vectors + auto& b_mfarrvec = a_b.getArrayVec(); + auto& x_mfarrvec = a_x.getArrayVec(); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + ((b_mfarrvec.size() == m_num_amr_levels) && (x_mfarrvec.size() == m_num_amr_levels)), + "Error in CurlCurlMLMGPC::Apply() - mismatch in number of levels." ); + + for (int n = 0; n < m_num_amr_levels; n++) { + + // Copy initial guess to local object +#if defined(WARPX_DIM_1D_Z) + // Missing dimensions is x,y in WarpX and y,z in AMReX + WARPX_ABORT_WITH_MESSAGE("CurlCurlMLMGPC not yet implemented for 1D"); +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + // Missing dimension is y in WarpX and z in AMReX + Array solution { MultiFab(*x_mfarrvec[n][0], make_alias, 0, 1), + MultiFab(*x_mfarrvec[n][2], make_alias, 0, 1), + MultiFab(*x_mfarrvec[n][1], make_alias, 0, 1) }; + Array rhs { MultiFab(*b_mfarrvec[n][0], make_alias, 0, 1), + MultiFab(*b_mfarrvec[n][2], make_alias, 0, 1), + MultiFab(*b_mfarrvec[n][1], make_alias, 0, 1) }; +#elif defined(WARPX_DIM_3D) + Array solution { MultiFab(*x_mfarrvec[n][0], make_alias, 0, 1), + MultiFab(*x_mfarrvec[n][1], make_alias, 0, 1), + MultiFab(*x_mfarrvec[n][2], make_alias, 0, 1) }; + Array rhs { MultiFab(*b_mfarrvec[n][0], make_alias, 0, 1), + MultiFab(*b_mfarrvec[n][1], make_alias, 0, 1), + MultiFab(*b_mfarrvec[n][2], make_alias, 0, 1) }; +#endif + +// currently not implemented in 1D +#ifndef WARPX_DIM_1D_Z + m_curl_curl->prepareRHS({&rhs}); + if (m_use_gmres) { + m_gmres_solver->solve(solution, rhs, m_rtol, m_atol); + } else { + m_solver->solve({&solution}, {&rhs}, m_rtol, m_atol); + } +#endif + } +} + +#endif diff --git a/Source/NonlinearSolvers/JacobianFunctionMF.H b/Source/NonlinearSolvers/JacobianFunctionMF.H index d5c2b6cbac9..1a30dde4250 100644 --- a/Source/NonlinearSolvers/JacobianFunctionMF.H +++ b/Source/NonlinearSolvers/JacobianFunctionMF.H @@ -7,6 +7,9 @@ #ifndef JacobianFunctionMF_H_ #define JacobianFunctionMF_H_ +#include "CurlCurlMLMGPC.H" +#include + /** * \brief This is a linear function class for computing the action of a * Jacobian on a vector using a matrix-free finite-difference method. @@ -35,14 +38,18 @@ class JacobianFunctionMF inline void precond ( T& a_U, const T& a_X ) { - if (m_usePreCond) { a_U.zero(); } - else { a_U.Copy(a_X); } + if (m_usePreCond) { + a_U.zero(); + m_preCond->Apply(a_U, a_X); + } else { + a_U.Copy(a_X); + } } inline void updatePreCondMat ( const T& a_X ) { - amrex::ignore_unused(a_X); + if (m_usePreCond) { m_preCond->Update(a_X); } } inline @@ -133,15 +140,25 @@ class JacobianFunctionMF void curTime ( RT a_time ) { m_cur_time = a_time; + if (m_usePreCond) { m_preCond->CurTime(a_time); } } inline void curTimeStep ( RT a_dt ) { m_dt = a_dt; + if (m_usePreCond) { m_preCond->CurTimeStep(a_dt); } + } + + inline + void printParams () const + { + if (m_pc_type != PreconditionerType::none) { + m_preCond->printParameters(); + } } - void define( const T&, Ops* ); + void define( const T&, Ops*, const PreconditionerType& ); private: @@ -151,16 +168,18 @@ class JacobianFunctionMF RT m_epsJFNK = RT(1.0e-6); RT m_normY0; RT m_cur_time, m_dt; - std::string m_pc_type; - T m_Z, m_Y0, m_R0, m_R; - Ops* m_ops; + PreconditionerType m_pc_type = PreconditionerType::none; + T m_Z, m_Y0, m_R0, m_R; + Ops* m_ops = nullptr; + std::unique_ptr> m_preCond = nullptr; }; template -void JacobianFunctionMF::define ( const T& a_U, - Ops* a_ops ) +void JacobianFunctionMF::define ( const T& a_U, + Ops* a_ops, + const PreconditionerType& a_pc_type ) { m_Z.Define(a_U); m_Y0.Define(a_U); @@ -169,6 +188,20 @@ void JacobianFunctionMF::define ( const T& a_U, m_ops = a_ops; + m_usePreCond = (a_pc_type != PreconditionerType::none); + if (m_usePreCond) { + m_pc_type = a_pc_type; + if (m_pc_type == PreconditionerType::pc_curl_curl_mlmg) { + m_preCond = std::make_unique>(); + } else { + std::stringstream convergenceMsg; + convergenceMsg << "JacobianFunctionMF::define(): " << amrex::getEnumNameString(m_pc_type) + << " is not a valid preconditioner type."; + WARPX_ABORT_WITH_MESSAGE(convergenceMsg.str()); + } + m_preCond->Define(a_U, a_ops); + } + m_is_defined = true; } @@ -220,7 +253,7 @@ void JacobianFunctionMF::apply (T& a_dF, const T& a_dU) const RT eps_inv = 1.0_rt/eps; m_Z.linComb( 1.0, m_Y0, eps, a_dU ); // Z = Y0 + eps*dU - m_ops->ComputeRHS(m_R, m_Z, m_cur_time, m_dt, -1, true ); + m_ops->ComputeRHS(m_R, m_Z, m_cur_time, -1, true ); // F(Y) = Y - b - R(Y) ==> dF = dF/dY*dU = [1 - dR/dY]*dU // = dU - (R(Z)-R(Y0))/eps diff --git a/Source/NonlinearSolvers/NewtonSolver.H b/Source/NonlinearSolvers/NewtonSolver.H index 742e139a5f5..9a1a7d5034a 100644 --- a/Source/NonlinearSolvers/NewtonSolver.H +++ b/Source/NonlinearSolvers/NewtonSolver.H @@ -9,12 +9,15 @@ #include "NonlinearSolver.H" #include "JacobianFunctionMF.H" +#include "Preconditioner.H" +#include "Utils/TextMsg.H" #include #include -#include "Utils/TextMsg.H" #include +#include +#include /** * \brief Newton method to solve nonlinear equation of form: @@ -44,7 +47,8 @@ public: void Solve ( Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt ) const override; + amrex::Real a_dt, + int a_step) const override; void GetSolverParams ( amrex::Real& a_rtol, amrex::Real& a_atol, @@ -79,6 +83,9 @@ public: amrex::Print() << "GMRES max iterations: " << m_gmres_maxits << "\n"; amrex::Print() << "GMRES relative tolerance: " << m_gmres_rtol << "\n"; amrex::Print() << "GMRES absolute tolerance: " << m_gmres_atol << "\n"; + amrex::Print() << "Preconditioner type: " << amrex::getEnumNameString(m_pc_type) << "\n"; + + m_linear_function->printParams(); } private: @@ -138,9 +145,12 @@ private: */ int m_gmres_restart_length = 30; + /** + * \brief Preconditioner type + */ + PreconditionerType m_pc_type = PreconditionerType::none; + mutable amrex::Real m_cur_time, m_dt; - mutable bool m_update_pc = false; - mutable bool m_update_pc_init = false; /** * \brief The linear function used by GMRES to compute A*v. @@ -162,7 +172,6 @@ private: const Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt, int a_iter ) const; }; @@ -184,7 +193,7 @@ void NewtonSolver::Define ( const Vec& a_U, m_ops = a_ops; m_linear_function = std::make_unique>(); - m_linear_function->define(m_F, m_ops); + m_linear_function->define(m_F, m_ops, m_pc_type); m_linear_solver = std::make_unique>>(); m_linear_solver->define(*m_linear_function); @@ -194,6 +203,34 @@ void NewtonSolver::Define ( const Vec& a_U, this->m_is_defined = true; + // Create diagnostic file and write header + if (!this->m_diagnostic_file.empty() && amrex::ParallelDescriptor::IOProcessor()) { + + std::filesystem::path const diagnostic_path(this->m_diagnostic_file); + std::filesystem::path const diagnostic_dir = diagnostic_path.parent_path(); + if (!diagnostic_dir.empty()) { + std::filesystem::create_directories(diagnostic_dir); + } + + std::ofstream diagnostic_file{this->m_diagnostic_file, std::ofstream::out | std::ofstream::trunc}; + int c = 0; + diagnostic_file << "#"; + diagnostic_file << "[" << c++ << "]step()"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]time(s)"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]iters"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]norm_abs"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]norm_rel"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]gmres_iters"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]gmres_last_res"; + diagnostic_file << "\n"; + diagnostic_file.close(); + } } template @@ -205,6 +242,7 @@ void NewtonSolver::ParseParameters () pp_newton.query("relative_tolerance", m_rtol); pp_newton.query("max_iterations", m_maxits); pp_newton.query("require_convergence", m_require_convergence); + pp_newton.query("diagnostic_file", this->m_diagnostic_file); const amrex::ParmParse pp_gmres("gmres"); pp_gmres.query("verbose_int", m_gmres_verbose_int); @@ -212,13 +250,17 @@ void NewtonSolver::ParseParameters () pp_gmres.query("absolute_tolerance", m_gmres_atol); pp_gmres.query("relative_tolerance", m_gmres_rtol); pp_gmres.query("max_iterations", m_gmres_maxits); + + const amrex::ParmParse pp_jac("jacobian"); + pp_jac.query("pc_type", m_pc_type); } template void NewtonSolver::Solve ( Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt ) const + amrex::Real a_dt, + int a_step) const { BL_PROFILE("NewtonSolver::Solve()"); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( @@ -239,10 +281,11 @@ void NewtonSolver::Solve ( Vec& a_U, amrex::Real norm_rel = 0.; int iter; + int linear_solver_iters = 0; for (iter = 0; iter < m_maxits;) { // Compute residual: F(U) = U - b - R(U) - EvalResidual(m_F, a_U, a_b, a_time, a_dt, iter); + EvalResidual(m_F, a_U, a_b, a_time, iter); // Compute norm of the residual norm_abs = m_F.norm2(); @@ -284,6 +327,7 @@ void NewtonSolver::Solve ( Vec& a_U, // Solve linear system for Newton step [Jac]*dU = F m_dU.zero(); m_linear_solver->solve( m_dU, m_F, m_gmres_rtol, m_gmres_atol ); + linear_solver_iters += m_linear_solver->getNumIters(); // Update solution a_U -= m_dU; @@ -304,7 +348,7 @@ void NewtonSolver::Solve ( Vec& a_U, " and the relative tolerance is " << m_rtol << ". Absolute norm is " << norm_abs << " and the absolute tolerance is " << m_atol; - if (this->m_verbose) { amrex::Print() << convergenceMsg.str() << std::endl; } + if (this->m_verbose) { amrex::Print() << convergenceMsg.str() << "\n"; } if (m_require_convergence) { WARPX_ABORT_WITH_MESSAGE(convergenceMsg.str()); } else { @@ -312,6 +356,26 @@ void NewtonSolver::Solve ( Vec& a_U, } } + if (!this->m_diagnostic_file.empty() && amrex::ParallelDescriptor::IOProcessor()) { + std::ofstream diagnostic_file{this->m_diagnostic_file, std::ofstream::out | std::ofstream::app}; + diagnostic_file << std::setprecision(14); + diagnostic_file << a_step; + diagnostic_file << " ";; + diagnostic_file << a_time; + diagnostic_file << " ";; + diagnostic_file << iter; + diagnostic_file << " ";; + diagnostic_file << norm_abs; + diagnostic_file << " ";; + diagnostic_file << norm_rel; + diagnostic_file << " ";; + diagnostic_file << linear_solver_iters; + diagnostic_file << " ";; + diagnostic_file << m_linear_solver->getResidualNorm(); + diagnostic_file << "\n"; + diagnostic_file.close(); + } + } template @@ -319,21 +383,17 @@ void NewtonSolver::EvalResidual ( Vec& a_F, const Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt, int a_iter ) const { - m_ops->ComputeRHS( m_R, a_U, a_time, a_dt, a_iter, false ); + m_ops->ComputeRHS( m_R, a_U, a_time, a_iter, false ); // set base U and R(U) for matrix-free Jacobian action calculation m_linear_function->setBaseSolution(a_U); m_linear_function->setBaseRHS(m_R); // update preconditioner - if (m_update_pc || m_update_pc_init) { - m_linear_function->updatePreCondMat(a_U); - } - m_update_pc_init = false; + m_linear_function->updatePreCondMat(a_U); // Compute residual: F(U) = U - b - R(U) a_F.Copy(a_U); diff --git a/Source/NonlinearSolvers/NonlinearSolver.H b/Source/NonlinearSolvers/NonlinearSolver.H index 6e64f1eb113..d7175d8ea56 100644 --- a/Source/NonlinearSolvers/NonlinearSolver.H +++ b/Source/NonlinearSolvers/NonlinearSolver.H @@ -16,7 +16,7 @@ * This class is templated on a vector class Vec, and an operator class Ops. * * The Ops class must have the following function: - * ComputeRHS( R_vec, U_vec, time, dt, nl_iter, from_jacobian ), + * ComputeRHS( R_vec, U_vec, time, nl_iter, from_jacobian ), * where U_vec and R_vec are of type Vec. * * The Vec class must have basic math operators, such as Copy, +=, -=, @@ -59,7 +59,8 @@ public: virtual void Solve ( Vec&, const Vec&, amrex::Real, - amrex::Real ) const = 0; + amrex::Real, + int) const = 0; /** * \brief Print parameters used by the nonlinear solver. @@ -81,6 +82,7 @@ protected: bool m_is_defined = false; mutable bool m_verbose = true; + std::string m_diagnostic_file; }; diff --git a/Source/NonlinearSolvers/PicardSolver.H b/Source/NonlinearSolvers/PicardSolver.H index f6c47c4f4bc..448fea7e75d 100644 --- a/Source/NonlinearSolvers/PicardSolver.H +++ b/Source/NonlinearSolvers/PicardSolver.H @@ -13,6 +13,8 @@ #include "Utils/TextMsg.H" #include +#include +#include /** * \brief Picard fixed-point iteration method to solve nonlinear @@ -42,7 +44,8 @@ public: void Solve ( Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt ) const override; + amrex::Real a_dt, + int a_step) const override; void GetSolverParams ( amrex::Real& a_rtol, amrex::Real& a_atol, @@ -114,6 +117,31 @@ void PicardSolver::Define ( const Vec& a_U, this->m_is_defined = true; + // Create diagnostic file and write header + if (!this->m_diagnostic_file.empty() && amrex::ParallelDescriptor::IOProcessor()) { + + std::filesystem::path const diagnostic_path(this->m_diagnostic_file); + std::filesystem::path const diagnostic_dir = diagnostic_path.parent_path(); + if (!diagnostic_dir.empty()) { + std::filesystem::create_directories(diagnostic_dir); + } + + std::ofstream diagnostic_file{this->m_diagnostic_file, std::ofstream::out | std::ofstream::trunc}; + int c = 0; + diagnostic_file << "#"; + diagnostic_file << "[" << c++ << "]step()"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]time(s)"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]iters"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]norm_abs"; + diagnostic_file << " "; + diagnostic_file << "[" << c++ << "]norm_rel"; + diagnostic_file << "\n"; + diagnostic_file.close(); + } + } template @@ -125,19 +153,21 @@ void PicardSolver::ParseParameters () pp_picard.query("relative_tolerance", m_rtol); pp_picard.query("max_iterations", m_maxits); pp_picard.query("require_convergence", m_require_convergence); - + pp_picard.query("diagnostic_file", this->m_diagnostic_file); } template void PicardSolver::Solve ( Vec& a_U, const Vec& a_b, amrex::Real a_time, - amrex::Real a_dt ) const + amrex::Real a_dt, + int a_step) const { BL_PROFILE("PicardSolver::Solve()"); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( this->m_is_defined, "PicardSolver::Solve() called on undefined object"); + amrex::ignore_unused(a_dt); using namespace amrex::literals; // @@ -156,7 +186,7 @@ void PicardSolver::Solve ( Vec& a_U, m_Usave.Copy(a_U); // Update the solver state (a_U = a_b + m_R) - m_ops->ComputeRHS( m_R, a_U, a_time, a_dt, iter, false ); + m_ops->ComputeRHS( m_R, a_U, a_time, iter, false ); a_U.Copy(a_b); a_U += m_R; @@ -204,7 +234,7 @@ void PicardSolver::Solve ( Vec& a_U, " and the relative tolerance is " << m_rtol << ". Absolute norm is " << norm_abs << " and the absolute tolerance is " << m_atol; - if (this->m_verbose) { amrex::Print() << convergenceMsg.str() << std::endl; } + if (this->m_verbose) { amrex::Print() << convergenceMsg.str() << "\n"; } if (m_require_convergence) { WARPX_ABORT_WITH_MESSAGE(convergenceMsg.str()); } else { @@ -212,6 +242,22 @@ void PicardSolver::Solve ( Vec& a_U, } } + if (!this->m_diagnostic_file.empty() && amrex::ParallelDescriptor::IOProcessor()) { + std::ofstream diagnostic_file{this->m_diagnostic_file, std::ofstream::out | std::ofstream::app}; + diagnostic_file << std::setprecision(14); + diagnostic_file << a_step; + diagnostic_file << " "; + diagnostic_file << a_time; + diagnostic_file << " "; + diagnostic_file << iter; + diagnostic_file << " "; + diagnostic_file << norm_abs; + diagnostic_file << " "; + diagnostic_file << norm_rel; + diagnostic_file << "\n"; + diagnostic_file.close(); + } + } #endif diff --git a/Source/NonlinearSolvers/Preconditioner.H b/Source/NonlinearSolvers/Preconditioner.H new file mode 100644 index 00000000000..191a48d00bc --- /dev/null +++ b/Source/NonlinearSolvers/Preconditioner.H @@ -0,0 +1,100 @@ +/* Copyright 2024 Debojyoti Ghosh + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ +#ifndef WARPX_PRECONDITIONER_H_ +#define WARPX_PRECONDITIONER_H_ + +#include + +/** + * \brief Types for preconditioners for field solvers + */ +AMREX_ENUM(PreconditionerType, pc_curl_curl_mlmg, none); + +/** + * \brief Base class for preconditioners + * + * This class is templated on a solution-type class T and an operator class Ops. + * + * The Ops class must have the following function: + * (this will depend on the specific preconditioners inheriting from this class) + * + * The T class must have the following functions: + * (this will depend on the specific preconditioners inheriting from this class) + */ + +template +class Preconditioner +{ + public: + + using RT = typename T::value_type; + + /** + * \brief Default constructor + */ + Preconditioner () = default; + + /** + * \brief Default destructor + */ + virtual ~Preconditioner () = default; + + // Default move and copy operations + Preconditioner(const Preconditioner&) = default; + Preconditioner& operator=(const Preconditioner&) = default; + Preconditioner(Preconditioner&&) noexcept = default; + Preconditioner& operator=(Preconditioner&&) noexcept = default; + + /** + * \brief Define the preconditioner + */ + virtual void Define (const T&, Ops*) = 0; + + /** + * \brief Update the preconditioner + */ + virtual void Update ( const T& ) = 0; + + /** + * \brief Apply (solve) the preconditioner given a RHS + * + * Given a right-hand-side b, solve: + * A x = b + * where A is a linear operator. + */ + virtual void Apply (T& a_x, const T& a_b) = 0; + + /** + * \brief Check if the nonlinear solver has been defined. + */ + [[nodiscard]] virtual bool IsDefined () const = 0; + + /** + * \brief Print parameters + */ + virtual void printParameters() const { } + + /** + * \brief Set the current time. + */ + inline void CurTime (const RT a_time) { m_time = a_time; } + + /** + * \brief Set the current time step size. + */ + inline void CurTimeStep (const RT a_dt) { m_dt = a_dt; } + + protected: + + RT m_time = 0.0; + RT m_dt = 0.0; + + private: + +}; + +#endif diff --git a/Source/Parallelization/WarpXComm.cpp b/Source/Parallelization/WarpXComm.cpp index d64632d964a..3adf4389a46 100644 --- a/Source/Parallelization/WarpXComm.cpp +++ b/Source/Parallelization/WarpXComm.cpp @@ -756,7 +756,7 @@ WarpX::FillBoundaryE (const int lev, const PatchType patch_type, const amrex::In ng.allLE(mf[i]->nGrowVect()), "Error: in FillBoundaryE, requested more guard cells than allocated"); - const amrex::IntVect nghost = (safe_guard_cells) ? mf[i]->nGrowVect() : ng; + const amrex::IntVect nghost = (m_safe_guard_cells) ? mf[i]->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*mf[i], nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -821,7 +821,7 @@ WarpX::FillBoundaryB (const int lev, const PatchType patch_type, const amrex::In ng.allLE(mf[i]->nGrowVect()), "Error: in FillBoundaryB, requested more guard cells than allocated"); - const amrex::IntVect nghost = (safe_guard_cells) ? mf[i]->nGrowVect() : ng; + const amrex::IntVect nghost = (m_safe_guard_cells) ? mf[i]->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*mf[i], nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -836,6 +836,8 @@ WarpX::FillBoundaryE_avg(int lev, IntVect ng) void WarpX::FillBoundaryE_avg (int lev, PatchType patch_type, IntVect ng) { + bool const skip_lev0_coarse_patch = true; + if (patch_type == PatchType::fine) { if (do_pml && pml[lev]->ok()) @@ -846,7 +848,7 @@ WarpX::FillBoundaryE_avg (int lev, PatchType patch_type, IntVect ng) ablastr::fields::MultiLevelVectorField Efield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_fp, finest_level); const amrex::Periodicity& period = Geom(lev).periodicity(); - if ( safe_guard_cells ){ + if ( m_safe_guard_cells ){ const Vector mf{Efield_avg_fp[lev][0],Efield_avg_fp[lev][1],Efield_avg_fp[lev][2]}; ablastr::utils::communication::FillBoundary(mf, WarpX::do_single_precision_comms, period); } else { @@ -865,10 +867,10 @@ WarpX::FillBoundaryE_avg (int lev, PatchType patch_type, IntVect ng) WARPX_ABORT_WITH_MESSAGE("Averaged Galilean PSATD with PML is not yet implemented"); } - ablastr::fields::MultiLevelVectorField Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level); + ablastr::fields::MultiLevelVectorField Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level, skip_lev0_coarse_patch); const amrex::Periodicity& cperiod = Geom(lev-1).periodicity(); - if ( safe_guard_cells ) { + if ( m_safe_guard_cells ) { const Vector mf{Efield_avg_cp[lev][0],Efield_avg_cp[lev][1],Efield_avg_cp[lev][2]}; ablastr::utils::communication::FillBoundary(mf, WarpX::do_single_precision_comms, cperiod); @@ -896,6 +898,8 @@ WarpX::FillBoundaryB_avg (int lev, PatchType patch_type, IntVect ng) { using ablastr::fields::Direction; + bool const skip_lev0_coarse_patch = true; + if (patch_type == PatchType::fine) { if (do_pml && pml[lev]->ok()) @@ -906,7 +910,7 @@ WarpX::FillBoundaryB_avg (int lev, PatchType patch_type, IntVect ng) ablastr::fields::MultiLevelVectorField Bfield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_fp, finest_level); const amrex::Periodicity& period = Geom(lev).periodicity(); - if ( safe_guard_cells ) { + if ( m_safe_guard_cells ) { const Vector mf{Bfield_avg_fp[lev][0],Bfield_avg_fp[lev][1],Bfield_avg_fp[lev][2]}; ablastr::utils::communication::FillBoundary(mf, WarpX::do_single_precision_comms, period); } else { @@ -925,10 +929,10 @@ WarpX::FillBoundaryB_avg (int lev, PatchType patch_type, IntVect ng) WARPX_ABORT_WITH_MESSAGE("Averaged Galilean PSATD with PML is not yet implemented"); } - ablastr::fields::MultiLevelVectorField Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level); + ablastr::fields::MultiLevelVectorField Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level, skip_lev0_coarse_patch); const amrex::Periodicity& cperiod = Geom(lev-1).periodicity(); - if ( safe_guard_cells ){ + if ( m_safe_guard_cells ){ const Vector mf{Bfield_avg_cp[lev][0],Bfield_avg_cp[lev][1],Bfield_avg_cp[lev][2]}; ablastr::utils::communication::FillBoundary(mf, WarpX::do_single_precision_comms, cperiod); } else { @@ -967,7 +971,7 @@ WarpX::FillBoundaryF (int lev, PatchType patch_type, IntVect ng, std::optionalnGrowVect() : ng; + const amrex::IntVect& nghost = (m_safe_guard_cells) ? m_fields.get(FieldType::F_fp, lev)->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*m_fields.get(FieldType::F_fp, lev), nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -986,7 +990,7 @@ WarpX::FillBoundaryF (int lev, PatchType patch_type, IntVect ng, std::optionalnGrowVect() : ng; + const amrex::IntVect& nghost = (m_safe_guard_cells) ? m_fields.get(FieldType::F_cp, lev)->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*m_fields.get(FieldType::F_cp, lev), nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -1020,7 +1024,7 @@ void WarpX::FillBoundaryG (int lev, PatchType patch_type, IntVect ng, std::optio { const amrex::Periodicity& period = Geom(lev).periodicity(); MultiFab* G_fp = m_fields.get(FieldType::G_fp,lev); - const amrex::IntVect& nghost = (safe_guard_cells) ? G_fp->nGrowVect() : ng; + const amrex::IntVect& nghost = (m_safe_guard_cells) ? G_fp->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*G_fp, nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -1040,7 +1044,7 @@ void WarpX::FillBoundaryG (int lev, PatchType patch_type, IntVect ng, std::optio { const amrex::Periodicity& period = Geom(lev-1).periodicity(); MultiFab* G_cp = m_fields.get(FieldType::G_cp,lev); - const amrex::IntVect& nghost = (safe_guard_cells) ? G_cp->nGrowVect() : ng; + const amrex::IntVect& nghost = (m_safe_guard_cells) ? G_cp->nGrowVect() : ng; ablastr::utils::communication::FillBoundary(*G_cp, nghost, WarpX::do_single_precision_comms, period, nodal_sync); } } @@ -1077,12 +1081,14 @@ WarpX::SyncCurrent (const std::string& current_fp_string) WARPX_PROFILE("WarpX::SyncCurrent()"); + bool const skip_lev0_coarse_patch = true; + ablastr::fields::MultiLevelVectorField const& J_fp = m_fields.get_mr_levels_alldirs(current_fp_string, finest_level); // If warpx.do_current_centering = 1, center currents from nodal grid to staggered grid if (do_current_centering) { - ablastr::fields::MultiLevelVectorField const& J_fp_nodal = m_fields.get_mr_levels_alldirs(FieldType::current_fp_nodal, finest_level+1); + ablastr::fields::MultiLevelVectorField const& J_fp_nodal = m_fields.get_mr_levels_alldirs(FieldType::current_fp_nodal, finest_level); AMREX_ALWAYS_ASSERT_WITH_MESSAGE(finest_level <= 1, "warpx.do_current_centering=1 not supported with more than one fine levels"); @@ -1192,10 +1198,10 @@ WarpX::SyncCurrent (const std::string& current_fp_string) } }); // Now it's safe to apply filter and sumboundary on J_cp - ablastr::fields::MultiLevelVectorField const& J_cp = m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level); + ablastr::fields::MultiLevelVectorField const& J_cp = m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch); if (use_filter) { - ApplyFilterJ(J_cp, lev+1, idim); + ApplyFilterMF(J_cp, lev+1, idim); } SumBoundaryJ(J_cp, lev+1, idim, period); } @@ -1207,14 +1213,14 @@ WarpX::SyncCurrent (const std::string& current_fp_string) // filtering depends on the level. This is also done before any // same-level communication because it's easier this way to // avoid double counting. - ablastr::fields::MultiLevelVectorField const& J_cp = m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level); + ablastr::fields::MultiLevelVectorField const& J_cp = m_fields.get_mr_levels_alldirs(FieldType::current_cp, finest_level, skip_lev0_coarse_patch); J_cp[lev][Direction{idim}]->setVal(0.0); ablastr::coarsen::average::Coarsen(*J_cp[lev][Direction{idim}], *J_fp[lev][Direction{idim}], refRatio(lev-1)); if (m_fields.has(FieldType::current_buf, Direction{idim}, lev)) { - ablastr::fields::MultiLevelVectorField const& J_buffer = m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level); + ablastr::fields::MultiLevelVectorField const& J_buffer = m_fields.get_mr_levels_alldirs(FieldType::current_buf, finest_level, skip_lev0_coarse_patch); IntVect const& ng = J_cp[lev][Direction{idim}]->nGrowVect(); AMREX_ASSERT(ng.allLE(J_buffer[lev][Direction{idim}]->nGrowVect())); @@ -1232,7 +1238,7 @@ WarpX::SyncCurrent (const std::string& current_fp_string) if (use_filter) { - ApplyFilterJ(J_fp, lev, idim); + ApplyFilterMF(J_fp, lev, idim); } SumBoundaryJ(J_fp, lev, idim, period); } @@ -1241,14 +1247,15 @@ WarpX::SyncCurrent (const std::string& current_fp_string) void WarpX::SyncRho () { + bool const skip_lev0_coarse_patch = true; const ablastr::fields::MultiLevelScalarField rho_fp = m_fields.has(FieldType::rho_fp, 0) ? m_fields.get_mr_levels(FieldType::rho_fp, finest_level) : ablastr::fields::MultiLevelScalarField{static_cast(finest_level+1)}; const ablastr::fields::MultiLevelScalarField rho_cp = m_fields.has(FieldType::rho_cp, 1) ? - m_fields.get_mr_levels(FieldType::rho_cp, finest_level) : + m_fields.get_mr_levels(FieldType::rho_cp, finest_level, skip_lev0_coarse_patch) : ablastr::fields::MultiLevelScalarField{static_cast(finest_level+1)}; const ablastr::fields::MultiLevelScalarField rho_buf = m_fields.has(FieldType::rho_buf, 1) ? - m_fields.get_mr_levels(FieldType::rho_buf, finest_level) : + m_fields.get_mr_levels(FieldType::rho_buf, finest_level, skip_lev0_coarse_patch) : ablastr::fields::MultiLevelScalarField{static_cast(finest_level+1)}; SyncRho(rho_fp, rho_cp, rho_buf); @@ -1354,32 +1361,32 @@ void WarpX::RestrictCurrentFromFineToCoarsePatch ( ablastr::coarsen::average::Coarsen(*crse[2], *fine[2], refinement_ratio ); } -void WarpX::ApplyFilterJ ( - const ablastr::fields::MultiLevelVectorField& current, +void WarpX::ApplyFilterMF ( + const ablastr::fields::MultiLevelVectorField& mfvec, const int lev, const int idim) { using ablastr::fields::Direction; - amrex::MultiFab& J = *current[lev][Direction{idim}]; + amrex::MultiFab& mf = *mfvec[lev][Direction{idim}]; - const int ncomp = J.nComp(); - const amrex::IntVect ngrow = J.nGrowVect(); - amrex::MultiFab Jf(J.boxArray(), J.DistributionMap(), ncomp, ngrow); - bilinear_filter.ApplyStencil(Jf, J, lev); + const int ncomp = mf.nComp(); + const amrex::IntVect ngrow = mf.nGrowVect(); + amrex::MultiFab mf_filtered(mf.boxArray(), mf.DistributionMap(), ncomp, ngrow); + bilinear_filter.ApplyStencil(mf_filtered, mf, lev); const int srccomp = 0; const int dstcomp = 0; - amrex::MultiFab::Copy(J, Jf, srccomp, dstcomp, ncomp, ngrow); + amrex::MultiFab::Copy(mf, mf_filtered, srccomp, dstcomp, ncomp, ngrow); } -void WarpX::ApplyFilterJ ( - const ablastr::fields::MultiLevelVectorField& current, +void WarpX::ApplyFilterMF ( + const ablastr::fields::MultiLevelVectorField& mfvec, const int lev) { for (int idim=0; idim<3; ++idim) { - ApplyFilterJ(current, lev, idim); + ApplyFilterMF(mfvec, lev, idim); } } @@ -1457,7 +1464,7 @@ void WarpX::AddCurrentFromFineLevelandSumBoundary ( if (use_filter) { - ApplyFilterJ(J_fp, lev); + ApplyFilterMF(J_fp, lev); } SumBoundaryJ(J_fp, lev, period); @@ -1476,8 +1483,8 @@ void WarpX::AddCurrentFromFineLevelandSumBoundary ( if (use_filter && J_buffer[lev+1][idim]) { - ApplyFilterJ(J_cp, lev+1, idim); - ApplyFilterJ(J_buffer, lev+1, idim); + ApplyFilterMF(J_cp, lev+1, idim); + ApplyFilterMF(J_buffer, lev+1, idim); MultiFab::Add( *J_buffer[lev+1][idim], *J_cp[lev+1][idim], @@ -1491,7 +1498,7 @@ void WarpX::AddCurrentFromFineLevelandSumBoundary ( } else if (use_filter) // but no buffer { - ApplyFilterJ(J_cp, lev+1, idim); + ApplyFilterMF(J_cp, lev+1, idim); ablastr::utils::communication::ParallelAdd( mf, *J_cp[lev+1][idim], 0, 0, @@ -1660,51 +1667,3 @@ void WarpX::AddRhoFromFineLevelandSumBoundary ( MultiFab::Add(*charge_fp[lev], mf, 0, icomp, ncomp, 0); } } - -void WarpX::NodalSyncJ ( - const ablastr::fields::MultiLevelVectorField& J_fp, - const ablastr::fields::MultiLevelVectorField& J_cp, - const int lev, - PatchType patch_type) -{ - if (!override_sync_intervals.contains(istep[0])) { return; } - - if (patch_type == PatchType::fine) - { - const amrex::Periodicity& period = Geom(lev).periodicity(); - ablastr::utils::communication::OverrideSync(*J_fp[lev][0], WarpX::do_single_precision_comms, period); - ablastr::utils::communication::OverrideSync(*J_fp[lev][1], WarpX::do_single_precision_comms, period); - ablastr::utils::communication::OverrideSync(*J_fp[lev][2], WarpX::do_single_precision_comms, period); - } - else if (patch_type == PatchType::coarse) - { - const amrex::Periodicity& cperiod = Geom(lev-1).periodicity(); - ablastr::utils::communication::OverrideSync(*J_cp[lev][0], WarpX::do_single_precision_comms, cperiod); - ablastr::utils::communication::OverrideSync(*J_cp[lev][1], WarpX::do_single_precision_comms, cperiod); - ablastr::utils::communication::OverrideSync(*J_cp[lev][2], WarpX::do_single_precision_comms, cperiod); - } -} - -void WarpX::NodalSyncRho ( - const amrex::Vector>& charge_fp, - const amrex::Vector>& charge_cp, - const int lev, - PatchType patch_type, - const int icomp, - const int ncomp) -{ - if (!override_sync_intervals.contains(istep[0])) { return; } - - if (patch_type == PatchType::fine && charge_fp[lev]) - { - const amrex::Periodicity& period = Geom(lev).periodicity(); - MultiFab rhof(*charge_fp[lev], amrex::make_alias, icomp, ncomp); - ablastr::utils::communication::OverrideSync(rhof, WarpX::do_single_precision_comms, period); - } - else if (patch_type == PatchType::coarse && charge_cp[lev]) - { - const amrex::Periodicity& cperiod = Geom(lev-1).periodicity(); - MultiFab rhoc(*charge_cp[lev], amrex::make_alias, icomp, ncomp); - ablastr::utils::communication::OverrideSync(rhoc, WarpX::do_single_precision_comms, cperiod); - } -} diff --git a/Source/Parallelization/WarpXRegrid.cpp b/Source/Parallelization/WarpXRegrid.cpp index a0a2d4929df..4c7668aa0e2 100644 --- a/Source/Parallelization/WarpXRegrid.cpp +++ b/Source/Parallelization/WarpXRegrid.cpp @@ -174,6 +174,14 @@ WarpX::RemakeLevel (int lev, Real /*time*/, const BoxArray& ba, const Distributi using ablastr::fields::Direction; using warpx::fields::FieldType; + const auto RemakeMultiFab = [&](auto& mf){ + if (mf == nullptr) { return; } + const IntVect& ng = mf->nGrowVect(); + auto pmf = std::remove_reference_t{}; + AllocInitMultiFab(pmf, mf->boxArray(), dm, mf->nComp(), ng, lev, mf->tags()[0]); + mf = std::move(pmf); + }; + bool const eb_enabled = EB::enabled(); if (ba == boxArray(lev)) { @@ -186,7 +194,10 @@ WarpX::RemakeLevel (int lev, Real /*time*/, const BoxArray& ba, const Distributi for (int idim=0; idim < 3; ++idim) { if (eb_enabled) { + RemakeMultiFab( m_eb_reduce_particle_shape[lev] ); if (WarpX::electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD) { + RemakeMultiFab( m_eb_update_E[lev][idim] ); + RemakeMultiFab( m_eb_update_B[lev][idim] ); if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { m_borrowing[lev][idim] = std::make_unique>(amrex::convert(ba, Bfield_fp[lev][idim]->ixType().toIntVect()), dm); } @@ -285,7 +296,7 @@ WarpX::RemakeLevel (int lev, Real /*time*/, const BoxArray& ba, const Distributi } // Re-initialize the lattice element finder with the new ba and dm. - m_accelerator_lattice[lev]->InitElementFinder(lev, ba, dm); + m_accelerator_lattice[lev]->InitElementFinder(lev, gamma_boost, ba, dm); if (costs[lev] != nullptr) { @@ -320,7 +331,7 @@ WarpX::ComputeCostsHeuristic (amrex::Vector& dx, const amrex::Real num_ppc_real, - amrex::Array4 const& eb_bnd_normal_arr, - int i, int j, int k ) { + AMREX_D_DECL(const amrex::Real n0, + const amrex::Real n1, + const amrex::Real n2)) { using namespace amrex::literals; // Scale particle weight by the area of the emitting surface, within one cell // By definition, eb_bnd_area_arr is normalized (unitless). // Here we undo the normalization (i.e. multiply by the surface used for normalization in amrex: // see https://amrex-codes.github.io/amrex/docs_html/EB.html#embedded-boundary-data-structures) #if defined(WARPX_DIM_3D) - const amrex::Real nx = eb_bnd_normal_arr(i,j,k,0); - const amrex::Real ny = eb_bnd_normal_arr(i,j,k,1); - const amrex::Real nz = eb_bnd_normal_arr(i,j,k,2); - amrex::Real scale_fac = std::sqrt(amrex::Math::powi<2>(nx*dx[1]*dx[2]) + - amrex::Math::powi<2>(ny*dx[0]*dx[2]) + - amrex::Math::powi<2>(nz*dx[0]*dx[1])); + amrex::Real scale_fac = std::sqrt(amrex::Math::powi<2>(n0*dx[1]*dx[2]) + + amrex::Math::powi<2>(n1*dx[0]*dx[2]) + + amrex::Math::powi<2>(n2*dx[0]*dx[1])); #elif defined(WARPX_DIM_RZ) || defined(WARPX_DIM_XZ) - const amrex::Real nx = eb_bnd_normal_arr(i,j,k,0); - const amrex::Real nz = eb_bnd_normal_arr(i,j,k,1); - amrex::Real scale_fac = std::sqrt(amrex::Math::powi<2>(nx*dx[1]) + - amrex::Math::powi<2>(nz*dx[0])); + amrex::Real scale_fac = std::sqrt(amrex::Math::powi<2>(n0*dx[1]) + + amrex::Math::powi<2>(n1*dx[0])); #else - amrex::ignore_unused(dx, eb_bnd_normal_arr, i, j, k); + amrex::ignore_unused(dx, AMREX_D_DECL(n0,n1,n2)); amrex::Real scale_fac = 0.0_rt; #endif // Do not multiply by eb_bnd_area_arr(i,j,k) here because this @@ -159,8 +155,9 @@ amrex::Real compute_scale_fac_area_eb ( AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE void rotate_momentum_eb ( PDim3 & pu, - amrex::Array4 const& eb_bnd_normal_arr, - int i, int j, int k ) + AMREX_D_DECL(const amrex::Real n0, + const amrex::Real n1, + const amrex::Real n2)) { using namespace amrex::literals; @@ -168,9 +165,9 @@ void rotate_momentum_eb ( // The minus sign below takes into account the fact that eb_bnd_normal_arr // points towards the covered region, while particles are to be emitted // *away* from the covered region. - amrex::Real const nx = -eb_bnd_normal_arr(i,j,k,0); - amrex::Real const ny = -eb_bnd_normal_arr(i,j,k,1); - amrex::Real const nz = -eb_bnd_normal_arr(i,j,k,2); + amrex::Real const nx = -n0; + amrex::Real const ny = -n1; + amrex::Real const nz = -n2; // Rotate the momentum in theta and phi amrex::Real const cos_theta = nz; @@ -194,14 +191,14 @@ void rotate_momentum_eb ( // The minus sign below takes into account the fact that eb_bnd_normal_arr // points towards the covered region, while particles are to be emitted // *away* from the covered region. - amrex::Real const sin_theta = -eb_bnd_normal_arr(i,j,k,0); - amrex::Real const cos_theta = -eb_bnd_normal_arr(i,j,k,1); + amrex::Real const sin_theta = -n0; + amrex::Real const cos_theta = -n1; amrex::Real const uz = pu.z*cos_theta - pu.x*sin_theta; amrex::Real const ux = pu.x*cos_theta + pu.z*sin_theta; pu.x = ux; pu.z = uz; #else - amrex::ignore_unused(pu, eb_bnd_normal_arr, i, j, k); + amrex::ignore_unused(pu, AMREX_D_DECL(n0,n1,n2)); #endif } #endif //AMREX_USE_EB @@ -254,8 +251,6 @@ struct PlasmaParserHelper PlasmaParserHelper (SoAType& a_soa, std::size_t old_size, const std::vector& a_user_int_attribs, const std::vector& a_user_real_attribs, - std::map& a_particle_icomps, - std::map& a_particle_comps, const PlasmaParserWrapper& wrapper) : m_wrapper_ptr(&wrapper) { m_pa_user_int_pinned.resize(a_user_int_attribs.size()); @@ -269,10 +264,10 @@ struct PlasmaParserHelper #endif for (std::size_t ia = 0; ia < a_user_int_attribs.size(); ++ia) { - m_pa_user_int_pinned[ia] = a_soa.GetIntData(a_particle_icomps[a_user_int_attribs[ia]]).data() + old_size; + m_pa_user_int_pinned[ia] = a_soa.GetIntData(a_user_int_attribs[ia]).data() + old_size; } for (std::size_t ia = 0; ia < a_user_real_attribs.size(); ++ia) { - m_pa_user_real_pinned[ia] = a_soa.GetRealData(a_particle_comps[a_user_real_attribs[ia]]).data() + old_size; + m_pa_user_real_pinned[ia] = a_soa.GetRealData(a_user_real_attribs[ia]).data() + old_size; } #ifdef AMREX_USE_GPU @@ -311,7 +306,6 @@ struct QEDHelper { template QEDHelper (SoAType& a_soa, std::size_t old_size, - std::map& a_particle_comps, bool a_has_quantum_sync, bool a_has_breit_wheeler, const std::shared_ptr& a_shr_p_qs_engine, const std::shared_ptr& a_shr_p_bw_engine) @@ -320,22 +314,20 @@ struct QEDHelper if(has_quantum_sync){ quantum_sync_get_opt = a_shr_p_qs_engine->build_optical_depth_functor(); - p_optical_depth_QSR = a_soa.GetRealData( - a_particle_comps["opticalDepthQSR"]).data() + old_size; + p_optical_depth_QSR = a_soa.GetRealData("opticalDepthQSR").data() + old_size; } if(has_breit_wheeler){ breit_wheeler_get_opt = a_shr_p_bw_engine->build_optical_depth_functor(); - p_optical_depth_BW = a_soa.GetRealData( - a_particle_comps["opticalDepthBW"]).data() + old_size; + p_optical_depth_BW = a_soa.GetRealData("opticalDepthBW").data() + old_size; } } amrex::ParticleReal* p_optical_depth_QSR = nullptr; amrex::ParticleReal* p_optical_depth_BW = nullptr; - const bool has_quantum_sync; - const bool has_breit_wheeler; + bool has_quantum_sync; + bool has_breit_wheeler; QuantumSynchrotronGetOpticalDepth quantum_sync_get_opt; BreitWheelerGetOpticalDepth breit_wheeler_get_opt; diff --git a/Source/Particles/Collision/BackgroundMCC/BackgroundMCCCollision.cpp b/Source/Particles/Collision/BackgroundMCC/BackgroundMCCCollision.cpp index 80ce13744fd..8becd7d231a 100644 --- a/Source/Particles/Collision/BackgroundMCC/BackgroundMCCCollision.cpp +++ b/Source/Particles/Collision/BackgroundMCC/BackgroundMCCCollision.cpp @@ -106,6 +106,14 @@ BackgroundMCCCollision::BackgroundMCCCollision (std::string const& collision_nam utils::parser::getWithParser( pp_collision_name, kw_energy.c_str(), energy); } + // if the scattering process is forward scattering get the energy + // associated with the process if it is given (this allows forward + // scattering to be used both with and without a fixed energy loss) + else if (scattering_process.find("forward") != std::string::npos) { + const std::string kw_energy = scattering_process + "_energy"; + utils::parser::queryWithParser( + pp_collision_name, kw_energy.c_str(), energy); + } ScatteringProcess process(scattering_process, cross_section_file, energy); diff --git a/Source/Particles/Collision/BinaryCollision/DSMC/CollisionFilterFunc.H b/Source/Particles/Collision/BinaryCollision/DSMC/CollisionFilterFunc.H index 46b228b049e..c5bd2e1cec6 100644 --- a/Source/Particles/Collision/BinaryCollision/DSMC/CollisionFilterFunc.H +++ b/Source/Particles/Collision/BinaryCollision/DSMC/CollisionFilterFunc.H @@ -34,7 +34,7 @@ * @param[in] scattering processes an array of scattering processes included for consideration. * @param[in] engine the random engine. */ -template +template AMREX_GPU_HOST_DEVICE AMREX_INLINE void CollisionPairFilter (const amrex::ParticleReal u1x, const amrex::ParticleReal u1y, const amrex::ParticleReal u1z, const amrex::ParticleReal u2x, @@ -65,11 +65,11 @@ void CollisionPairFilter (const amrex::ParticleReal u1x, const amrex::ParticleRe // Evaluate the cross-section for each scattering process to determine // the total collision probability. - AMREX_ASSERT_WITH_MESSAGE( - (process_count < 4), "Too many scattering processes in DSMC routine." - ); - int coll_type[4] = {0, 0, 0, 0}; - amrex::ParticleReal sigma_sums[4] = {0._prt, 0._prt, 0._prt, 0._prt}; + + // The size of the arrays below is a compile-time constant (template parameter) + // for performance reasons: it avoids dynamic memory allocation on the GPU. + int coll_type[max_process_count] = {0}; + amrex::ParticleReal sigma_sums[max_process_count] = {0._prt}; for (int ii = 0; ii < process_count; ii++) { auto const& scattering_process = scattering_processes[ii]; coll_type[ii] = int(scattering_process.m_type); diff --git a/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.H b/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.H index a692d2cbb9e..6051aab1b59 100644 --- a/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.H +++ b/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.H @@ -163,7 +163,11 @@ public: u1y[I1[i1]] = u1xbuf*std::sin(theta) + u1y[I1[i1]]*std::cos(theta); #endif - CollisionPairFilter( + const int max_process_count = 4; // Pre-defined value, for performance reasons + AMREX_ALWAYS_ASSERT_WITH_MESSAGE( + (m_process_count < max_process_count), "Too many scattering processes in DSMC routine (hardcoded to only allow 4). Update the max_process_count value in source code to allow more scattering processes." + ); + CollisionPairFilter( u1x[ I1[i1] ], u1y[ I1[i1] ], u1z[ I1[i1] ], u2x[ I2[i2] ], u2y[ I2[i2] ], u2z[ I2[i2] ], m1, m2, w1[ I1[i1] ], w2[ I2[i2] ], @@ -172,6 +176,7 @@ public: m_process_count, m_scattering_processes_data, engine); #if (defined WARPX_DIM_RZ) + /* Undo the earlier velocity rotation. */ amrex::ParticleReal const u1xbuf_new = u1x[I1[i1]]; u1x[I1[i1]] = u1xbuf_new*std::cos(-theta) - u1y[I1[i1]]*std::sin(-theta); u1y[I1[i1]] = u1xbuf_new*std::sin(-theta) + u1y[I1[i1]]*std::cos(-theta); diff --git a/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.cpp b/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.cpp index e40a4e9822c..cf5f8de8d3c 100644 --- a/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.cpp +++ b/Source/Particles/Collision/BinaryCollision/DSMC/DSMCFunc.cpp @@ -46,6 +46,14 @@ DSMCFunc::DSMCFunc ( utils::parser::getWithParser( pp_collision_name, kw_energy.c_str(), energy); } + // if the scattering process is forward scattering get the energy + // associated with the process if it is given (this allows forward + // scattering to be used both with and without a fixed energy loss) + else if (scattering_process.find("forward") != std::string::npos) { + const std::string kw_energy = scattering_process + "_energy"; + utils::parser::queryWithParser( + pp_collision_name, kw_energy.c_str(), energy); + } ScatteringProcess process(scattering_process, cross_section_file, energy); diff --git a/Source/Particles/Collision/BinaryCollision/DSMC/SplitAndScatterFunc.H b/Source/Particles/Collision/BinaryCollision/DSMC/SplitAndScatterFunc.H index 473199a6b21..e4b4d8a6a3a 100644 --- a/Source/Particles/Collision/BinaryCollision/DSMC/SplitAndScatterFunc.H +++ b/Source/Particles/Collision/BinaryCollision/DSMC/SplitAndScatterFunc.H @@ -154,6 +154,25 @@ public: auto& uy2 = soa_products_data[1].m_rdata[PIdx::uy][product2_index]; auto& uz2 = soa_products_data[1].m_rdata[PIdx::uz][product2_index]; +#if (defined WARPX_DIM_RZ) + /* In RZ geometry, macroparticles can collide with other macroparticles + * in the same *cylindrical* cell. For this reason, collisions between macroparticles + * are actually not local in space. In this case, the underlying assumption is that + * particles within the same cylindrical cell represent a cylindrically-symmetry + * momentum distribution function. Therefore, here, we temporarily rotate the + * momentum of one of the macroparticles in agreement with this cylindrical symmetry. + * (This is technically only valid if we use only the m=0 azimuthal mode in the simulation; + * there is a corresponding assert statement at initialization.) + */ + amrex::ParticleReal const theta = ( + soa_products_data[1].m_rdata[PIdx::theta][product2_index] + - soa_products_data[0].m_rdata[PIdx::theta][product1_index] + ); + amrex::ParticleReal const ux1buf = ux1; + ux1 = ux1buf*std::cos(theta) - uy1*std::sin(theta); + uy1 = ux1buf*std::sin(theta) + uy1*std::cos(theta); +#endif + // for simplicity (for now) we assume non-relativistic particles // and simply calculate the center-of-momentum velocity from the // rest masses @@ -202,6 +221,8 @@ public: else { amrex::Abort("Uneven mass charge-exchange not implemented yet."); } + } else if (mask[i] == int(ScatteringProcessType::FORWARD)) { + amrex::Abort("Forward scattering with DSMC not implemented yet."); } else { amrex::Abort("Unknown scattering process."); @@ -213,6 +234,13 @@ public: ux2 += uCOM_x; uy2 += uCOM_y; uz2 += uCOM_z; + +#if (defined WARPX_DIM_RZ) + /* Undo the earlier velocity rotation. */ + amrex::ParticleReal const ux1buf_new = ux1; + ux1 = ux1buf_new*std::cos(-theta) - uy1*std::sin(-theta); + uy1 = ux1buf_new*std::sin(-theta) + uy1*std::cos(-theta); +#endif } }); @@ -224,7 +252,7 @@ public: ParticleCreation::DefaultInitializeRuntimeAttributes(*tile_products[i], 0, 0, pc_products[i]->getUserRealAttribs(), pc_products[i]->getUserIntAttribs(), - pc_products[i]->getParticleComps(), pc_products[i]->getParticleiComps(), + pc_products[i]->GetRealSoANames(), pc_products[i]->GetIntSoANames(), pc_products[i]->getUserRealAttribParser(), pc_products[i]->getUserIntAttribParser(), #ifdef WARPX_QED diff --git a/Source/Particles/Collision/BinaryCollision/ParticleCreationFunc.H b/Source/Particles/Collision/BinaryCollision/ParticleCreationFunc.H index e4772aab7c9..59565c92516 100644 --- a/Source/Particles/Collision/BinaryCollision/ParticleCreationFunc.H +++ b/Source/Particles/Collision/BinaryCollision/ParticleCreationFunc.H @@ -235,7 +235,7 @@ public: ParticleCreation::DefaultInitializeRuntimeAttributes(*tile_products[i], 0, 0, pc_products[i]->getUserRealAttribs(), pc_products[i]->getUserIntAttribs(), - pc_products[i]->getParticleComps(), pc_products[i]->getParticleiComps(), + pc_products[i]->GetRealSoANames(), pc_products[i]->GetIntSoANames(), pc_products[i]->getUserRealAttribParser(), pc_products[i]->getUserIntAttribParser(), #ifdef WARPX_QED diff --git a/Source/Particles/Collision/ScatteringProcess.H b/Source/Particles/Collision/ScatteringProcess.H index 59ef7a02afb..0c3f2daf8c1 100644 --- a/Source/Particles/Collision/ScatteringProcess.H +++ b/Source/Particles/Collision/ScatteringProcess.H @@ -21,6 +21,7 @@ enum class ScatteringProcessType { CHARGE_EXCHANGE, EXCITATION, IONIZATION, + FORWARD, }; class ScatteringProcess diff --git a/Source/Particles/Collision/ScatteringProcess.cpp b/Source/Particles/Collision/ScatteringProcess.cpp index ea1b4b40f54..ad3f179fa18 100644 --- a/Source/Particles/Collision/ScatteringProcess.cpp +++ b/Source/Particles/Collision/ScatteringProcess.cpp @@ -87,6 +87,8 @@ ScatteringProcess::parseProcessType(const std::string& scattering_process) return ScatteringProcessType::IONIZATION; } else if (scattering_process.find("excitation") != std::string::npos) { return ScatteringProcessType::EXCITATION; + } else if (scattering_process.find("forward") != std::string::npos) { + return ScatteringProcessType::FORWARD; } else { return ScatteringProcessType::INVALID; } diff --git a/Source/Particles/Deposition/CurrentDeposition.H b/Source/Particles/Deposition/CurrentDeposition.H index cb56c559bc0..bc870257d8f 100644 --- a/Source/Particles/Deposition/CurrentDeposition.H +++ b/Source/Particles/Deposition/CurrentDeposition.H @@ -638,6 +638,9 @@ void doDepositionSharedShapeN (const GetParticlePosition& GetPosition, * \param lo Index lower bounds of domain. * \param q species charge. * \param n_rz_azimuthal_modes Number of azimuthal modes when using RZ geometry. + * \param reduced_particle_shape_mask Array4 of int, Mask that indicates whether a particle + * should use its regular shape factor or a reduced, order-1 shape factor instead in a given cell. + * \param enable_reduced_shape Flag to indicate whether to use the reduced shape factor */ template void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, @@ -656,7 +659,10 @@ void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, const amrex::XDim3 & xyzmin, amrex::Dim3 lo, amrex::Real q, - [[maybe_unused]]int n_rz_azimuthal_modes) + [[maybe_unused]] int n_rz_azimuthal_modes, + const amrex::Array4& reduced_particle_shape_mask, + bool enable_reduced_shape + ) { using namespace amrex; using namespace amrex::literals; @@ -680,9 +686,14 @@ void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, #endif // Loop over particles and deposit into Jx_arr, Jy_arr and Jz_arr - amrex::ParallelFor( - np_to_deposit, - [=] AMREX_GPU_DEVICE (long const ip) { + + // (Compile 2 versions of the kernel: with and without reduced shape) + enum eb_flags : int { has_reduced_shape, no_reduced_shape }; + const int reduce_shape_runtime_flag = (enable_reduced_shape && (depos_order>1))? has_reduced_shape : no_reduced_shape; + + amrex::ParallelFor( TypeList>{}, + {reduce_shape_runtime_flag}, + np_to_deposit, [=] AMREX_GPU_DEVICE (long ip, auto reduce_shape_control) { // --- Get particle quantities Real const gaminv = 1.0_rt/std::sqrt(1.0_rt + uxp[ip]*uxp[ip]*clightsq + uyp[ip]*uyp[ip]*clightsq @@ -735,6 +746,43 @@ void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, double const z_new = (zp - xyzmin.z + (relative_time + 0.5_rt*dt)*uzp[ip]*gaminv)*dinv.z; double const z_old = z_new - dt*dinv.z*uzp[ip]*gaminv; + // Check whether the particle is close to the EB at the old and new position + bool reduce_shape_old, reduce_shape_new; +#ifdef AMREX_USE_CUDA + amrex::ignore_unused(reduced_particle_shape_mask, lo); // Needed to avoid compilation error with nvcc +#endif + if constexpr (reduce_shape_control == has_reduced_shape) { +#if defined(WARPX_DIM_3D) + reduce_shape_old = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(x_old)), + lo.y + int(amrex::Math::floor(y_old)), + lo.z + int(amrex::Math::floor(z_old))); + reduce_shape_new = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(x_new)), + lo.y + int(amrex::Math::floor(y_new)), + lo.z + int(amrex::Math::floor(z_new))); +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + reduce_shape_old = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(x_old)), + lo.y + int(amrex::Math::floor(z_old)), + 0); + reduce_shape_new = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(x_new)), + lo.y + int(amrex::Math::floor(z_new)), + 0); +#elif defined(WARPX_DIM_1D_Z) + reduce_shape_old = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(z_old)), + 0, 0); + reduce_shape_new = reduced_particle_shape_mask( + lo.x + int(amrex::Math::floor(z_new)), + 0, 0); +#endif + } else { + reduce_shape_old = false; + reduce_shape_new = false; + } + #if defined(WARPX_DIM_RZ) Real const vy = (-uxp[ip]*sintheta_mid + uyp[ip]*costheta_mid)*gaminv; #elif defined(WARPX_DIM_XZ) @@ -749,6 +797,9 @@ void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, // [ijk]_new: leftmost grid point that the particle touches const Compute_shape_factor< depos_order > compute_shape_factor; const Compute_shifted_shape_factor< depos_order > compute_shifted_shape_factor; + // In cells marked by reduced_particle_shape_mask, we need order 1 deposition + const Compute_shifted_shape_factor< 1 > compute_shifted_shape_factor_order1; + amrex::ignore_unused(compute_shifted_shape_factor_order1); // unused for `no_reduced_shape` // Shape factor arrays // Note that there are extra values above and below @@ -758,19 +809,58 @@ void doEsirkepovDepositionShapeN (const GetParticlePosition& GetPosition, #if !defined(WARPX_DIM_1D_Z) double sx_new[depos_order + 3] = {0.}; double sx_old[depos_order + 3] = {0.}; - const int i_new = compute_shape_factor(sx_new+1, x_new); + const int i_new = compute_shape_factor(sx_new+1, x_new ); const int i_old = compute_shifted_shape_factor(sx_old, x_old, i_new); + // If particle is close to the embedded boundary, recompute deposition with order 1 shape + if constexpr (reduce_shape_control == has_reduced_shape) { + if (reduce_shape_new) { + for (int i=0; i m_get_position; diff --git a/Source/Particles/ElementaryProcess/QEDPhotonEmission.H b/Source/Particles/ElementaryProcess/QEDPhotonEmission.H index 514526374bd..f509f884c48 100644 --- a/Source/Particles/ElementaryProcess/QEDPhotonEmission.H +++ b/Source/Particles/ElementaryProcess/QEDPhotonEmission.H @@ -47,7 +47,7 @@ public: /** * \brief Constructor of the PhotonEmissionFilterFunc functor. * - * @param[in] opt_depth_runtime_comp Index of the optical depth component + * @param[in] opt_depth_runtime_comp Index of the optical depth component in the runtime real data */ PhotonEmissionFilterFunc(int const opt_depth_runtime_comp) : m_opt_depth_runtime_comp(opt_depth_runtime_comp) @@ -73,7 +73,7 @@ public: } private: - int m_opt_depth_runtime_comp; /*!< Index of the optical depth component of the source species*/ + int m_opt_depth_runtime_comp; /*!< Index of the optical depth runtime component of the source species */ }; /** @@ -178,12 +178,12 @@ public: } private: - const QuantumSynchrotronGetOpticalDepth + QuantumSynchrotronGetOpticalDepth m_opt_depth_functor; /*!< A copy of the functor to initialize the optical depth of the source species. */ - const int m_opt_depth_runtime_comp = 0; /*!< Index of the optical depth component of source species*/ + int m_opt_depth_runtime_comp = 0; /*!< Index of the optical depth component of source species*/ - const QuantumSynchrotronPhotonEmission + QuantumSynchrotronPhotonEmission m_emission_functor; /*!< A copy of the functor to generate photons. It contains only pointers to the lookup tables.*/ GetParticlePosition m_get_position; diff --git a/Source/Particles/ElementaryProcess/QEDSchwingerProcess.H b/Source/Particles/ElementaryProcess/QEDSchwingerProcess.H index 32b58dc50dc..e7eb7e8be04 100644 --- a/Source/Particles/ElementaryProcess/QEDSchwingerProcess.H +++ b/Source/Particles/ElementaryProcess/QEDSchwingerProcess.H @@ -17,9 +17,9 @@ */ struct SchwingerFilterFunc { - const int m_threshold_poisson_gaussian; - const amrex::Real m_dV; - const amrex::Real m_dt; + int m_threshold_poisson_gaussian; + amrex::Real m_dV; + amrex::Real m_dt; /** Get the number of created pairs in a given cell at a given timestep. * @@ -59,8 +59,8 @@ struct SchwingerFilterFunc */ struct SchwingerTransformFunc { - const amrex::Real m_y_size; - const int m_weight_index; + amrex::Real m_y_size; + int m_weight_index; /** Assign a weight to particles created via the Schwinger process. * diff --git a/Source/Particles/Filter/FilterFunctors.H b/Source/Particles/Filter/FilterFunctors.H index 982eeb0d23a..9d2b5f67a64 100644 --- a/Source/Particles/Filter/FilterFunctors.H +++ b/Source/Particles/Filter/FilterFunctors.H @@ -50,8 +50,8 @@ struct RandomFilter return ( (!m_is_active) || (amrex::Random(engine) < m_fraction) ); } private: - const bool m_is_active; //! select all particles if false - const amrex::Real m_fraction = 1.0; //! range: [0.0:1.0] where 0 is no & 1 is all particles + bool m_is_active; //! select all particles if false + amrex::Real m_fraction = 1.0; //! range: [0.0:1.0] where 0 is no & 1 is all particles }; /** @@ -77,8 +77,8 @@ struct UniformFilter return ( (!m_is_active) || ( p.id()%m_stride == 0 ) ); } private: - const bool m_is_active; //! select all particles if false - const int m_stride = 0; //! selection of every n-th particle + bool m_is_active; //! select all particles if false + int m_stride = 0; //! selection of every n-th particle }; /** @@ -134,10 +134,10 @@ struct ParserFilter } private: /** Whether this diagnostics is activated. Select all particles if false */ - const bool m_is_active; + bool m_is_active; public: /** Parser function with 7 input variables, t,x,y,z,ux,uy,uz */ - amrex::ParserExecutor<7> const m_function_partparser; + amrex::ParserExecutor<7> m_function_partparser; /** Mass of particle species */ amrex::ParticleReal m_mass; /** Store physical time on the coarsest level. */ @@ -171,9 +171,9 @@ struct GeometryFilter } private: /** Whether this diagnostics is activated. Select all particles if false */ - const bool m_is_active; + bool m_is_active; /** Physical extent of the axis-aligned region used for particle check */ - const amrex::RealBox m_domain; + amrex::RealBox m_domain; }; #endif // WARPX_FILTERFUNCTORS_H diff --git a/Source/Particles/Gather/GetExternalFields.H b/Source/Particles/Gather/GetExternalFields.H index 7000d6d7c26..c3c8f992b07 100644 --- a/Source/Particles/Gather/GetExternalFields.H +++ b/Source/Particles/Gather/GetExternalFields.H @@ -15,8 +15,6 @@ #include #include -#include - /** \brief Functor class that assigns external * field values (E and B) to particles. @@ -56,10 +54,10 @@ struct GetExternalEBField const amrex::ParticleReal* AMREX_RESTRICT m_uy = nullptr; const amrex::ParticleReal* AMREX_RESTRICT m_uz = nullptr; - std::optional d_lattice_element_finder; + LatticeElementFinderDevice d_lattice_element_finder; [[nodiscard]] AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE - bool isNoOp () const { return (m_Etype == None && m_Btype == None && !d_lattice_element_finder.has_value()); } + bool isNoOp () const { return (m_Etype == None && m_Btype == None && !d_lattice_element_finder.m_initialized); } AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE void operator () (long i, @@ -72,10 +70,9 @@ struct GetExternalEBField { using namespace amrex::literals; - if (d_lattice_element_finder) { - // Note that the "*" is needed since d_lattice_element_finder is optional - (*d_lattice_element_finder)(i, field_Ex, field_Ey, field_Ez, - field_Bx, field_By, field_Bz); + if (d_lattice_element_finder.m_initialized) { + d_lattice_element_finder(i, field_Ex, field_Ey, field_Ez, + field_Bx, field_By, field_Bz); } if (m_Etype == None && m_Btype == None) { return; } @@ -112,9 +109,9 @@ struct GetExternalEBField lab_time = m_gamma_boost*m_time + m_uz_boost*z*inv_c2; z = m_gamma_boost*z + m_uz_boost*m_time; } - Bx = m_Bxfield_partparser(x, y, z, lab_time); - By = m_Byfield_partparser(x, y, z, lab_time); - Bz = m_Bzfield_partparser(x, y, z, lab_time); + Bx = m_Bxfield_partparser((amrex::ParticleReal) x, (amrex::ParticleReal) y, (amrex::ParticleReal) z, lab_time); + By = m_Byfield_partparser((amrex::ParticleReal) x, (amrex::ParticleReal) y, (amrex::ParticleReal) z, lab_time); + Bz = m_Bzfield_partparser((amrex::ParticleReal) x, (amrex::ParticleReal) y, (amrex::ParticleReal) z, lab_time); } if (m_Etype == RepeatedPlasmaLens || diff --git a/Source/Particles/Gather/ScaleFields.H b/Source/Particles/Gather/ScaleFields.H index 5731bc047f4..a8c685eef8b 100644 --- a/Source/Particles/Gather/ScaleFields.H +++ b/Source/Particles/Gather/ScaleFields.H @@ -47,8 +47,21 @@ struct ScaleFields // This only approximates what should be happening. The particles // should by advanced a fraction of a time step instead. // Scaling the fields is much easier and may be good enough. - const amrex::Real dtscale = 1._rt - (m_z_plane_previous - zp)/(m_vz_ave_boosted + m_v_boost)/m_dt; - if (0._rt < dtscale && dtscale < 1._rt) + + // The scaling factor corresponds to the fraction of time that + // the particles spends to the right of the injection plane, + // between (n-1/2)*dt and (n+1/2)*dt, which is the interval + // over which the velocity is updated, in the leap-frog velocity push. + // (Note that here, `zp` is the particle position at time n*dt) + amrex::Real dtscale = 0.5_rt - (m_z_plane_previous - zp)/(m_vz_ave_boosted + m_v_boost)/m_dt; + // If the particle stays to the left of the plane during the + // whole push, simply set the scaling factor to 0, and thus + // the velocity push leaves the velocity unchanged. + if (dtscale < 0._rt) { + dtscale = 0; + } + // Scale the fields. + if (dtscale < 1._rt) { Exp *= dtscale; Eyp *= dtscale; diff --git a/Source/Particles/LaserParticleContainer.cpp b/Source/Particles/LaserParticleContainer.cpp index c804bb12797..c79d1f675b5 100644 --- a/Source/Particles/LaserParticleContainer.cpp +++ b/Source/Particles/LaserParticleContainer.cpp @@ -873,18 +873,18 @@ LaserParticleContainer::update_laser_particle (WarpXParIter& pti, #if (AMREX_SPACEDIM >= 2) ParticleReal* x_n = nullptr; if (push_type == PushType::Implicit) { - x_n = pti.GetAttribs(particle_comps["x_n"]).dataPtr(); + x_n = pti.GetAttribs("x_n").dataPtr(); } #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) ParticleReal* y_n = nullptr; if (push_type == PushType::Implicit) { - y_n = pti.GetAttribs(particle_comps["y_n"]).dataPtr(); + y_n = pti.GetAttribs("y_n").dataPtr(); } #endif ParticleReal* z_n = nullptr; if (push_type == PushType::Implicit) { - z_n = pti.GetAttribs(particle_comps["z_n"]).dataPtr(); + z_n = pti.GetAttribs("z_n").dataPtr(); } // Copy member variables to tmp copies for GPU runs. @@ -917,11 +917,13 @@ LaserParticleContainer::update_laser_particle (WarpXParIter& pti, puyp[i] = gamma * vy; puzp[i] = gamma * vz; - // Push the the particle positions + // Push the particle positions // When using the implicit solver, this function is called multiple times per timestep // (within the linear and nonlinear solver). Thus, the position of the particles needs to be reset - // to the initial position (at the beginning of the timestep), before updating the particle position + // to the initial position (at the beginning of the timestep), before updating the particle position. + // Also, the current deposition schemes expect the particle positions to be time centered + // (cur_time + 0.5*dt) for PushType::Implicit. ParticleReal x=0., y=0., z=0.; if (push_type == PushType::Explicit) { @@ -930,20 +932,26 @@ LaserParticleContainer::update_laser_particle (WarpXParIter& pti, #if !defined(WARPX_DIM_1D_Z) if (push_type == PushType::Implicit) { - x = x_n[i]; + x = x_n[i] + vx * dt*0.5_prt; + } + else { + x += vx * dt; } - x += vx * dt; #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) if (push_type == PushType::Implicit) { - y = y_n[i]; + y = y_n[i] + vy * dt*0.5_prt; + } + else { + y += vy * dt; } - y += vy * dt; #endif if (push_type == PushType::Implicit) { - z = z_n[i]; + z = z_n[i] + vz * dt*0.5_prt; + } + else { + z += vz * dt; } - z += vz * dt; SetPosition(i, x, y, z); } diff --git a/Source/Particles/MultiParticleContainer.cpp b/Source/Particles/MultiParticleContainer.cpp index 619b54ed7ad..6c08dc6aa8d 100644 --- a/Source/Particles/MultiParticleContainer.cpp +++ b/Source/Particles/MultiParticleContainer.cpp @@ -21,7 +21,6 @@ # include "Particles/ElementaryProcess/QEDPhotonEmission.H" #endif #include "Particles/LaserParticleContainer.H" -#include "Particles/NamedComponentParticleContainer.H" #include "Particles/ParticleCreation/FilterCopyTransform.H" #ifdef WARPX_QED # include "Particles/ParticleCreation/FilterCreateTransformFromFAB.H" @@ -88,7 +87,7 @@ namespace /** A little collection to transport six Array4 that point to the EM fields */ struct MyFieldList { - Array4< amrex::Real const > const Ex, Ey, Ez, Bx, By, Bz; + Array4< amrex::Real const > Ex, Ey, Ez, Bx, By, Bz; }; } @@ -223,7 +222,7 @@ MultiParticleContainer::ReadParameters () pp_particles, "repeated_plasma_lens_lengths", h_repeated_plasma_lens_lengths); - const int n_lenses = static_cast(h_repeated_plasma_lens_starts.size()); + const auto n_lenses = static_cast(h_repeated_plasma_lens_starts.size()); d_repeated_plasma_lens_starts.resize(n_lenses); d_repeated_plasma_lens_lengths.resize(n_lenses); amrex::Gpu::copyAsync(amrex::Gpu::hostToDevice, @@ -1622,7 +1621,7 @@ void MultiParticleContainer::doQedQuantumSync (int lev, auto Transform = PhotonEmissionTransformFunc( m_shr_p_qs_engine->build_optical_depth_functor(), - pc_source->particle_runtime_comps["opticalDepthQSR"], + pc_source->GetRealCompIndex("opticalDepthQSR") - pc_source->NArrayReal, m_shr_p_qs_engine->build_phot_em_functor(), pti, lev, Ex.nGrowVect(), Ex[pti], Ey[pti], Ez[pti], diff --git a/Source/Particles/NamedComponentParticleContainer.H b/Source/Particles/NamedComponentParticleContainer.H deleted file mode 100644 index 57c65746d18..00000000000 --- a/Source/Particles/NamedComponentParticleContainer.H +++ /dev/null @@ -1,222 +0,0 @@ -/* Copyright 2022 Remi Lehe - * - * This file is part of WarpX. - * - * License: BSD-3-Clause-LBNL - */ -#ifndef WARPX_NamedComponentParticleContainer_H_ -#define WARPX_NamedComponentParticleContainer_H_ - -#include "Utils/TextMsg.H" - -#include -#include -#include - -#include -#include -#include - - -/** Real Particle Attributes stored in amrex::ParticleContainer's struct of array - */ -struct PIdx -{ - enum { -#if !defined (WARPX_DIM_1D_Z) - x, -#endif -#if defined (WARPX_DIM_3D) - y, -#endif - z, - w, ///< weight - ux, uy, uz, -#ifdef WARPX_DIM_RZ - theta, ///< RZ needs all three position components -#endif - nattribs ///< number of compile-time attributes - }; -}; - -/** Integer Particle Attributes stored in amrex::ParticleContainer's struct of array - */ -struct PIdxInt -{ - enum { - nattribs ///< number of compile-time attributes - }; -}; - -/** Particle Container class that allows to add/access particle components - * with a name (string) instead of doing so with an integer index. - * (The "components" are all the particle amrex::Real quantities.) - * - * This is done by storing maps that give the index of the component - * that corresponds to a given string. - * - * @tparam T_Allocator Mainly controls in which type of memory (e.g. device - * arena, pinned memory arena, etc.) the particle data will be stored - */ -template class T_Allocator=amrex::DefaultAllocator> -class NamedComponentParticleContainer : -public amrex::ParticleContainerPureSoA -{ -public: - /** Construct an empty NamedComponentParticleContainer **/ - NamedComponentParticleContainer () : amrex::ParticleContainerPureSoA() {} - - /** Construct a NamedComponentParticleContainer from an AmrParGDB object - * - * In this case, the only components are the default ones: - * weight, momentum and (in RZ geometry) theta. - * - * @param amr_pgdb A pointer to a ParGDBBase, which contains pointers to - * the Geometry, DistributionMapping, and BoxArray objects that define the - * AMR hierarchy. Usually, this is generated by an AmrCore or AmrLevel object. - */ - NamedComponentParticleContainer (amrex::AmrParGDB* amr_pgdb) - : amrex::ParticleContainerPureSoA(amr_pgdb) { - // build up the map of string names to particle component numbers -#if !defined (WARPX_DIM_1D_Z) - particle_comps["x"] = PIdx::x; -#endif -#if defined (WARPX_DIM_3D) - particle_comps["y"] = PIdx::y; -#endif - particle_comps["z"] = PIdx::z; - particle_comps["w"] = PIdx::w; - particle_comps["ux"] = PIdx::ux; - particle_comps["uy"] = PIdx::uy; - particle_comps["uz"] = PIdx::uz; -#ifdef WARPX_DIM_RZ - particle_comps["theta"] = PIdx::theta; -#endif - } - - /** Destructor for NamedComponentParticleContainer */ - ~NamedComponentParticleContainer() override = default; - - /** Construct a NamedComponentParticleContainer from a regular - * amrex::ParticleContainer, and additional name-to-index maps - * - * @param pc regular particle container, where components are not named (only indexed) - * @param p_comps name-to-index map for compile-time and run-time real components - * @param p_icomps name-to-index map for compile-time and run-time integer components - * @param p_rcomps name-to-index map for run-time real components - * @param p_ricomps name-to-index map for run-time integer components - */ - NamedComponentParticleContainer( - amrex::ParticleContainerPureSoA && pc, - std::map p_comps, - std::map p_icomps, - std::map p_rcomps, - std::map p_ricomps) - : amrex::ParticleContainerPureSoA(std::move(pc)), - particle_comps(std::move(p_comps)), - particle_icomps(std::move(p_icomps)), - particle_runtime_comps(std::move(p_rcomps)), - particle_runtime_icomps(std::move(p_ricomps)) {} - - /** Copy constructor for NamedComponentParticleContainer */ - NamedComponentParticleContainer ( const NamedComponentParticleContainer &) = delete; - /** Copy operator for NamedComponentParticleContainer */ - NamedComponentParticleContainer& operator= ( const NamedComponentParticleContainer & ) = delete; - - /** Move constructor for NamedComponentParticleContainer */ - NamedComponentParticleContainer ( NamedComponentParticleContainer && ) noexcept = default; - /** Move operator for NamedComponentParticleContainer */ - NamedComponentParticleContainer& operator= ( NamedComponentParticleContainer && ) noexcept = default; - - /** Create an empty particle container - * - * This creates a new NamedComponentParticleContainer with same compile-time - * and run-time attributes. But it can change its allocator. - * - * This function overloads the corresponding function from the parent - * class (amrex::ParticleContainer) - */ - template class NewAllocator=amrex::DefaultAllocator> - NamedComponentParticleContainer - make_alike () const { - auto tmp = NamedComponentParticleContainer( - amrex::ParticleContainerPureSoA::template make_alike(), - particle_comps, - particle_icomps, - particle_runtime_comps, - particle_runtime_icomps); - - return tmp; - } - - using amrex::ParticleContainerPureSoA::NumRealComps; - using amrex::ParticleContainerPureSoA::NumIntComps; - using amrex::ParticleContainerPureSoA::AddRealComp; - using amrex::ParticleContainerPureSoA::AddIntComp; - - /** Allocate a new run-time real component - * - * @param name Name of the new component - * @param comm Whether to communicate this component, in the particle Redistribute - */ - void NewRealComp (const std::string& name, bool comm=true) - { - auto search = particle_comps.find(name); - if (search == particle_comps.end()) { - particle_comps[name] = NumRealComps(); - particle_runtime_comps[name] = NumRealComps() - PIdx::nattribs; - AddRealComp(comm); - } else { - amrex::Print() << Utils::TextMsg::Info( - name + " already exists in particle_comps, not adding."); - } - } - - /** Allocate a new run-time integer component - * - * @param name Name of the new component - * @param comm Whether to communicate this component, in the particle Redistribute - */ - void NewIntComp (const std::string& name, bool comm=true) - { - auto search = particle_icomps.find(name); - if (search == particle_icomps.end()) { - particle_icomps[name] = NumIntComps(); - particle_runtime_icomps[name] = NumIntComps() - 0; - AddIntComp(comm); - } else { - amrex::Print() << Utils::TextMsg::Info( - name + " already exists in particle_icomps, not adding."); - } - } - - void defineAllParticleTiles () noexcept - { - for (int lev = 0; lev <= amrex::ParticleContainerPureSoA::finestLevel(); ++lev) - { - for (auto mfi = amrex::ParticleContainerPureSoA::MakeMFIter(lev); mfi.isValid(); ++mfi) - { - const int grid_id = mfi.index(); - const int tile_id = mfi.LocalTileIndex(); - amrex::ParticleContainerPureSoA::DefineAndReturnParticleTile(lev, grid_id, tile_id); - } - } - } - - /** Return the name-to-index map for the compile-time and runtime-time real components */ - [[nodiscard]] std::map getParticleComps () const noexcept { return particle_comps;} - /** Return the name-to-index map for the compile-time and runtime-time integer components */ - [[nodiscard]] std::map getParticleiComps () const noexcept { return particle_icomps;} - /** Return the name-to-index map for the runtime-time real components */ - [[nodiscard]] std::map getParticleRuntimeComps () const noexcept { return particle_runtime_comps;} - /** Return the name-to-index map for the runtime-time integer components */ - [[nodiscard]] std::map getParticleRuntimeiComps () const noexcept { return particle_runtime_icomps;} - -protected: - std::map particle_comps; - std::map particle_icomps; - std::map particle_runtime_comps; - std::map particle_runtime_icomps; -}; - -#endif //WARPX_NamedComponentParticleContainer_H_ diff --git a/Source/Particles/ParticleBoundaryBuffer.H b/Source/Particles/ParticleBoundaryBuffer.H index 24b388be00e..c9589ac0c75 100644 --- a/Source/Particles/ParticleBoundaryBuffer.H +++ b/Source/Particles/ParticleBoundaryBuffer.H @@ -32,9 +32,9 @@ public: /** Copy operator for ParticleBoundaryBuffer */ ParticleBoundaryBuffer& operator= ( const ParticleBoundaryBuffer & ) = delete; - /** Move constructor for NamedComponentParticleContainer */ + /** Move constructor for ParticleBoundaryBuffer */ ParticleBoundaryBuffer ( ParticleBoundaryBuffer && ) = default; - /** Move operator for NamedComponentParticleContainer */ + /** Move operator for ParticleBoundaryBuffer */ ParticleBoundaryBuffer& operator= ( ParticleBoundaryBuffer && ) = default; int numSpecies() const { return static_cast(getSpeciesNames().size()); } diff --git a/Source/Particles/ParticleBoundaryBuffer.cpp b/Source/Particles/ParticleBoundaryBuffer.cpp index a1f1c46d894..048534bff6a 100644 --- a/Source/Particles/ParticleBoundaryBuffer.cpp +++ b/Source/Particles/ParticleBoundaryBuffer.cpp @@ -50,11 +50,11 @@ struct IsOutsideDomainBoundary { }; struct FindEmbeddedBoundaryIntersection { - const int m_step_index; - const int m_delta_index; - const int m_normal_index; - const int m_step; - const amrex::Real m_dt; + int m_step_index; + int m_delta_index; + int m_normal_index; + int m_step; + amrex::Real m_dt; amrex::Array4 m_phiarr; amrex::GpuArray m_dxi; amrex::GpuArray m_plo; @@ -173,7 +173,7 @@ struct CopyAndTimestamp { int m_delta_index; int m_normal_index; int m_step; - const amrex::Real m_dt; + amrex::Real m_dt; int m_idim; int m_iside; @@ -384,11 +384,11 @@ void ParticleBoundaryBuffer::gatherParticlesFromDomainBoundaries (MultiParticleC if (!buffer[i].isDefined()) { buffer[i] = pc.make_alike(); - buffer[i].NewIntComp("stepScraped", false); - buffer[i].NewRealComp("deltaTimeScraped", false); - buffer[i].NewRealComp("nx", false); - buffer[i].NewRealComp("ny", false); - buffer[i].NewRealComp("nz", false); + buffer[i].AddIntComp("stepScraped", false); + buffer[i].AddRealComp("deltaTimeScraped", false); + buffer[i].AddRealComp("nx", false); + buffer[i].AddRealComp("ny", false); + buffer[i].AddRealComp("nz", false); } auto& species_buffer = buffer[i]; @@ -443,11 +443,10 @@ void ParticleBoundaryBuffer::gatherParticlesFromDomainBoundaries (MultiParticleC WARPX_PROFILE("ParticleBoundaryBuffer::gatherParticles::filterAndTransform"); auto& warpx = WarpX::GetInstance(); const auto dt = warpx.getdt(pti.GetLevel()); - auto string_to_index_intcomp = buffer[i].getParticleRuntimeiComps(); - const int step_scraped_index = string_to_index_intcomp.at("stepScraped"); - auto string_to_index_realcomp = buffer[i].getParticleRuntimeComps(); - const int delta_index = string_to_index_realcomp.at("deltaTimeScraped"); - const int normal_index = string_to_index_realcomp.at("nx"); + auto & buf = buffer[i]; + const int step_scraped_index = buf.GetIntCompIndex("stepScraped") - PinnedMemoryParticleContainer::NArrayInt; + const int delta_index = buf.GetRealCompIndex("deltaTimeScraped") - PinnedMemoryParticleContainer::NArrayReal; + const int normal_index = buf.GetRealCompIndex("nx") - PinnedMemoryParticleContainer::NArrayReal; const int step = warpx_instance.getistep(0); amrex::filterAndTransformParticles(ptile_buffer, ptile, predicate, @@ -481,11 +480,11 @@ void ParticleBoundaryBuffer::gatherParticlesFromEmbeddedBoundaries ( if (!buffer[i].isDefined()) { buffer[i] = pc.make_alike(); - buffer[i].NewIntComp("stepScraped", false); - buffer[i].NewRealComp("deltaTimeScraped", false); - buffer[i].NewRealComp("nx", false); - buffer[i].NewRealComp("ny", false); - buffer[i].NewRealComp("nz", false); + buffer[i].AddIntComp("stepScraped", false); + buffer[i].AddRealComp("deltaTimeScraped", false); + buffer[i].AddRealComp("nx", false); + buffer[i].AddRealComp("ny", false); + buffer[i].AddRealComp("nz", false); } @@ -546,11 +545,10 @@ void ParticleBoundaryBuffer::gatherParticlesFromEmbeddedBoundaries ( } auto &warpx = WarpX::GetInstance(); const auto dt = warpx.getdt(pti.GetLevel()); - auto string_to_index_intcomp = buffer[i].getParticleRuntimeiComps(); - const int step_scraped_index = string_to_index_intcomp.at("stepScraped"); - auto string_to_index_realcomp = buffer[i].getParticleRuntimeComps(); - const int delta_index = string_to_index_realcomp.at("deltaTimeScraped"); - const int normal_index = string_to_index_realcomp.at("nx"); + auto & buf = buffer[i]; + const int step_scraped_index = buf.GetIntCompIndex("stepScraped") - PinnedMemoryParticleContainer::NArrayInt; + const int delta_index = buf.GetRealCompIndex("deltaTimeScraped") - PinnedMemoryParticleContainer::NArrayReal; + const int normal_index = buf.GetRealCompIndex("nx") - PinnedMemoryParticleContainer::NArrayReal; const int step = warpx_instance.getistep(0); { diff --git a/Source/Particles/ParticleCreation/DefaultInitialization.H b/Source/Particles/ParticleCreation/DefaultInitialization.H index 88b23905481..1922c829379 100644 --- a/Source/Particles/ParticleCreation/DefaultInitialization.H +++ b/Source/Particles/ParticleCreation/DefaultInitialization.H @@ -102,8 +102,8 @@ namespace ParticleCreation { * These are NOT initialized by this function. * @param[in] user_real_attribs The names of the real components for this particle tile * @param[in] user_int_attribs The names of the int components for this particle tile - * @param[in] particle_comps map between particle component index and component name for real comps - * @param[in] particle_icomps map between particle component index and component name for int comps + * @param[in] particle_comps particle component names for real comps + * @param[in] particle_icomps particle component names for int comps * @param[in] user_real_attrib_parser the parser functions used to initialize the user real components * @param[in] user_int_attrib_parser the parser functions used to initialize the user int components * @param[in] do_qed_comps whether to initialize the qed components (these are usually handled by @@ -120,8 +120,8 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, const int n_external_attr_int, const std::vector& user_real_attribs, const std::vector& user_int_attribs, - const std::map& particle_comps, - const std::map& particle_icomps, + const std::vector& particle_comps, + const std::vector& particle_icomps, const std::vector& user_real_attrib_parser, const std::vector& user_int_attrib_parser, #ifdef WARPX_QED @@ -151,8 +151,9 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, auto attr_ptr = ptile.GetStructOfArrays().GetRealData(j).data(); #ifdef WARPX_QED // Current runtime comp is quantum synchrotron optical depth - if (particle_comps.find("opticalDepthQSR") != particle_comps.end() && - particle_comps.at("opticalDepthQSR") == j) + auto const it_qsr = std::find(particle_comps.begin(), particle_comps.end(), "opticalDepthQSR"); + if (it_qsr != particle_comps.end() && + std::distance(particle_comps.begin(), it_qsr) == j) { if (!do_qed_comps) { continue; } const QuantumSynchrotronGetOpticalDepth quantum_sync_get_opt = @@ -172,9 +173,10 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, } } - // Current runtime comp is Breit-Wheeler optical depth - if (particle_comps.find("opticalDepthBW") != particle_comps.end() && - particle_comps.at("opticalDepthBW") == j) + // Current runtime comp is Breit-Wheeler optical depth + auto const it_bw = std::find(particle_comps.begin(), particle_comps.end(), "opticalDepthBW"); + if (it_bw != particle_comps.end() && + std::distance(particle_comps.begin(), it_bw) == j) { if (!do_qed_comps) { continue; } const BreitWheelerGetOpticalDepth breit_wheeler_get_opt = @@ -198,8 +200,9 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, for (int ia = 0; ia < n_user_real_attribs; ++ia) { // Current runtime comp is ia-th user defined attribute - if (particle_comps.find(user_real_attribs[ia]) != particle_comps.end() && - particle_comps.at(user_real_attribs[ia]) == j) + auto const it_ura = std::find(particle_comps.begin(), particle_comps.end(), user_real_attribs[ia]); + if (it_ura != particle_comps.end() && + std::distance(particle_comps.begin(), it_ura) == j) { const amrex::ParserExecutor<7> user_real_attrib_parserexec = user_real_attrib_parser[ia]->compile<7>(); @@ -232,8 +235,9 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, auto attr_ptr = ptile.GetStructOfArrays().GetIntData(j).data(); // Current runtime comp is ionization level - if (particle_icomps.find("ionizationLevel") != particle_icomps.end() && - particle_icomps.at("ionizationLevel") == j) + auto const it_ioniz = std::find(particle_icomps.begin(), particle_icomps.end(), "ionizationLevel"); + if (it_ioniz != particle_icomps.end() && + std::distance(particle_icomps.begin(), it_ioniz) == j) { if constexpr (amrex::RunOnGpu>::value) { amrex::ParallelFor(stop - start, @@ -251,8 +255,9 @@ void DefaultInitializeRuntimeAttributes (PTile& ptile, for (int ia = 0; ia < n_user_int_attribs; ++ia) { // Current runtime comp is ia-th user defined attribute - if (particle_icomps.find(user_int_attribs[ia]) != particle_icomps.end() && - particle_icomps.at(user_int_attribs[ia]) == j) + auto const it_uia = std::find(particle_icomps.begin(), particle_icomps.end(), user_int_attribs[ia]); + if (it_uia != particle_icomps.end() && + std::distance(particle_icomps.begin(), it_uia) == j) { const amrex::ParserExecutor<7> user_int_attrib_parserexec = user_int_attrib_parser[ia]->compile<7>(); diff --git a/Source/Particles/ParticleCreation/FilterCopyTransform.H b/Source/Particles/ParticleCreation/FilterCopyTransform.H index c6ca69d5e89..c05038fae2f 100644 --- a/Source/Particles/ParticleCreation/FilterCopyTransform.H +++ b/Source/Particles/ParticleCreation/FilterCopyTransform.H @@ -88,7 +88,7 @@ Index filterCopyTransformParticles (DstPC& pc, DstTile& dst, SrcTile& src, ParticleCreation::DefaultInitializeRuntimeAttributes(dst, 0, 0, pc.getUserRealAttribs(), pc.getUserIntAttribs(), - pc.getParticleComps(), pc.getParticleiComps(), + pc.GetRealSoANames(), pc.GetIntSoANames(), pc.getUserRealAttribParser(), pc.getUserIntAttribParser(), #ifdef WARPX_QED @@ -258,7 +258,7 @@ Index filterCopyTransformParticles (DstPC& pc1, DstPC& pc2, DstTile& dst1, DstTi ParticleCreation::DefaultInitializeRuntimeAttributes(dst1, 0, 0, pc1.getUserRealAttribs(), pc1.getUserIntAttribs(), - pc1.getParticleComps(), pc1.getParticleiComps(), + pc1.GetRealSoANames(), pc1.GetIntSoANames(), pc1.getUserRealAttribParser(), pc1.getUserIntAttribParser(), #ifdef WARPX_QED @@ -272,7 +272,7 @@ Index filterCopyTransformParticles (DstPC& pc1, DstPC& pc2, DstTile& dst1, DstTi ParticleCreation::DefaultInitializeRuntimeAttributes(dst2, 0, 0, pc2.getUserRealAttribs(), pc2.getUserIntAttribs(), - pc2.getParticleComps(), pc2.getParticleiComps(), + pc2.GetRealSoANames(), pc2.GetIntSoANames(), pc2.getUserRealAttribParser(), pc2.getUserIntAttribParser(), #ifdef WARPX_QED diff --git a/Source/Particles/ParticleCreation/FilterCreateTransformFromFAB.H b/Source/Particles/ParticleCreation/FilterCreateTransformFromFAB.H index 424008e18a6..266faae6322 100644 --- a/Source/Particles/ParticleCreation/FilterCreateTransformFromFAB.H +++ b/Source/Particles/ParticleCreation/FilterCreateTransformFromFAB.H @@ -136,7 +136,7 @@ Index filterCreateTransformFromFAB (DstPC& pc1, DstPC& pc2, ParticleCreation::DefaultInitializeRuntimeAttributes(dst1, 0, 0, pc1.getUserRealAttribs(), pc1.getUserIntAttribs(), - pc1.getParticleComps(), pc1.getParticleiComps(), + pc1.GetRealSoANames(), pc1.GetIntSoANames(), pc1.getUserRealAttribParser(), pc1.getUserIntAttribParser(), #ifdef WARPX_QED @@ -150,7 +150,7 @@ Index filterCreateTransformFromFAB (DstPC& pc1, DstPC& pc2, ParticleCreation::DefaultInitializeRuntimeAttributes(dst2, 0, 0, pc2.getUserRealAttribs(), pc2.getUserIntAttribs(), - pc2.getParticleComps(), pc2.getParticleiComps(), + pc2.GetRealSoANames(), pc2.GetIntSoANames(), pc2.getUserRealAttribParser(), pc2.getUserIntAttribParser(), #ifdef WARPX_QED diff --git a/Source/Particles/ParticleCreation/SmartCopy.H b/Source/Particles/ParticleCreation/SmartCopy.H index e1d944e9c30..6be363e6337 100644 --- a/Source/Particles/ParticleCreation/SmartCopy.H +++ b/Source/Particles/ParticleCreation/SmartCopy.H @@ -140,10 +140,10 @@ class SmartCopyFactory public: template SmartCopyFactory (const SrcPC& src, const DstPC& dst) noexcept : - m_tag_real{getSmartCopyTag(src.getParticleComps(), dst.getParticleComps())}, - m_tag_int{getSmartCopyTag(src.getParticleiComps(), dst.getParticleiComps())}, - m_policy_real{getPolicies(dst.getParticleComps())}, - m_policy_int{getPolicies(dst.getParticleiComps())}, + m_tag_real{getSmartCopyTag(src.GetRealSoANames(), dst.GetRealSoANames())}, + m_tag_int{getSmartCopyTag(src.GetIntSoANames(), dst.GetIntSoANames())}, + m_policy_real{getPolicies(dst.GetRealSoANames())}, + m_policy_int{getPolicies(dst.GetIntSoANames())}, m_defined{true} {} diff --git a/Source/Particles/ParticleCreation/SmartCreate.H b/Source/Particles/ParticleCreation/SmartCreate.H index fe4cb5929e0..688f1c3701f 100644 --- a/Source/Particles/ParticleCreation/SmartCreate.H +++ b/Source/Particles/ParticleCreation/SmartCreate.H @@ -35,7 +35,7 @@ struct SmartCreate { const InitializationPolicy* m_policy_real; const InitializationPolicy* m_policy_int; - const int m_weight_index = 0; + int m_weight_index = 0; template AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE @@ -97,8 +97,8 @@ class SmartCreateFactory public: template SmartCreateFactory (const PartTileData& part) noexcept: - m_policy_real{getPolicies(part.getParticleComps())}, - m_policy_int{getPolicies(part.getParticleiComps())}, + m_policy_real{getPolicies(part.GetRealSoANames())}, + m_policy_int{getPolicies(part.GetIntSoANames())}, m_defined{true} {} diff --git a/Source/Particles/ParticleCreation/SmartUtils.H b/Source/Particles/ParticleCreation/SmartUtils.H index 652a3aecd17..358c2b1a7a9 100644 --- a/Source/Particles/ParticleCreation/SmartUtils.H +++ b/Source/Particles/ParticleCreation/SmartUtils.H @@ -35,9 +35,9 @@ struct SmartCopyTag [[nodiscard]] int size () const noexcept { return static_cast(common_names.size()); } }; -PolicyVec getPolicies (const NameMap& names) noexcept; +PolicyVec getPolicies (std::vector const & names) noexcept; -SmartCopyTag getSmartCopyTag (const NameMap& src, const NameMap& dst) noexcept; +SmartCopyTag getSmartCopyTag (std::vector const & src, std::vector const & dst) noexcept; /** * \brief Sets the ids of newly created particles to the next values. diff --git a/Source/Particles/ParticleCreation/SmartUtils.cpp b/Source/Particles/ParticleCreation/SmartUtils.cpp index 7e79f58c59e..19e5bee8b97 100644 --- a/Source/Particles/ParticleCreation/SmartUtils.cpp +++ b/Source/Particles/ParticleCreation/SmartUtils.cpp @@ -13,8 +13,11 @@ #include #include -PolicyVec getPolicies (const NameMap& names) noexcept +PolicyVec getPolicies (std::vector const & names_vec) noexcept { + NameMap names; + for (auto i = 0u; i < names_vec.size(); ++i) { names.emplace(names_vec[i], i); } + std::vector h_policies; h_policies.resize(names.size()); for (const auto& kv : names) @@ -31,10 +34,16 @@ PolicyVec getPolicies (const NameMap& names) noexcept return policies; } -SmartCopyTag getSmartCopyTag (const NameMap& src, const NameMap& dst) noexcept +SmartCopyTag getSmartCopyTag (std::vector const & src_names, std::vector const & dst_names) noexcept { SmartCopyTag tag; + // We want to avoid running an NxM algorithm to find pairs, so sort the components first. + NameMap src; + NameMap dst; + for (auto i = 0u; i < src_names.size(); ++i) { src.emplace(src_names[i], i); } + for (auto i = 0u; i < dst_names.size(); ++i) { dst.emplace(dst_names[i], i); } + std::vector h_src_comps; std::vector h_dst_comps; diff --git a/Source/Particles/PhotonParticleContainer.cpp b/Source/Particles/PhotonParticleContainer.cpp index 47c426cd6ff..ad0b3364eea 100644 --- a/Source/Particles/PhotonParticleContainer.cpp +++ b/Source/Particles/PhotonParticleContainer.cpp @@ -122,7 +122,7 @@ PhotonParticleContainer::PushPX (WarpXParIter& pti, const bool local_has_breit_wheeler = has_breit_wheeler(); if (local_has_breit_wheeler) { evolve_opt = m_shr_p_bw_engine->build_evolve_functor(); - p_optical_depth_BW = pti.GetAttribs(particle_comps["opticalDepthBW"]).dataPtr() + offset; + p_optical_depth_BW = pti.GetAttribs("opticalDepthBW").dataPtr() + offset; } #endif diff --git a/Source/Particles/PhysicalParticleContainer.cpp b/Source/Particles/PhysicalParticleContainer.cpp index c973e9afafa..335d7370e75 100644 --- a/Source/Particles/PhysicalParticleContainer.cpp +++ b/Source/Particles/PhysicalParticleContainer.cpp @@ -342,12 +342,12 @@ PhysicalParticleContainer::PhysicalParticleContainer (AmrCore* amr_core, int isp #ifdef WARPX_QED pp_species_name.query("do_qed_quantum_sync", m_do_qed_quantum_sync); if (m_do_qed_quantum_sync) { - NewRealComp("opticalDepthQSR"); + AddRealComp("opticalDepthQSR"); } pp_species_name.query("do_qed_breit_wheeler", m_do_qed_breit_wheeler); if (m_do_qed_breit_wheeler) { - NewRealComp("opticalDepthBW"); + AddRealComp("opticalDepthBW"); } if(m_do_qed_quantum_sync){ @@ -368,7 +368,7 @@ PhysicalParticleContainer::PhysicalParticleContainer (AmrCore* amr_core, int isp str_int_attrib_function.at(i)); m_user_int_attrib_parser.at(i) = std::make_unique( utils::parser::makeParser(str_int_attrib_function.at(i),{"x","y","z","ux","uy","uz","t"})); - NewIntComp(m_user_int_attribs.at(i)); + AddIntComp(m_user_int_attribs.at(i)); } // User-defined real attributes @@ -383,19 +383,19 @@ PhysicalParticleContainer::PhysicalParticleContainer (AmrCore* amr_core, int isp str_real_attrib_function.at(i)); m_user_real_attrib_parser.at(i) = std::make_unique( utils::parser::makeParser(str_real_attrib_function.at(i),{"x","y","z","ux","uy","uz","t"})); - NewRealComp(m_user_real_attribs.at(i)); + AddRealComp(m_user_real_attribs.at(i)); } // If old particle positions should be saved add the needed components pp_species_name.query("save_previous_position", m_save_previous_position); if (m_save_previous_position) { #if (AMREX_SPACEDIM >= 2) - NewRealComp("prev_x"); + AddRealComp("prev_x"); #endif #if defined(WARPX_DIM_3D) - NewRealComp("prev_y"); + AddRealComp("prev_y"); #endif - NewRealComp("prev_z"); + AddRealComp("prev_z"); #ifdef WARPX_DIM_RZ amrex::Abort("Saving previous particle positions not yet implemented in RZ"); #endif @@ -813,7 +813,7 @@ PhysicalParticleContainer::DefaultInitializeRuntimeAttributes ( ParticleCreation::DefaultInitializeRuntimeAttributes(pinned_tile, n_external_attr_real, n_external_attr_int, m_user_real_attribs, m_user_int_attribs, - particle_comps, particle_icomps, + GetRealSoANames(), GetIntSoANames(), amrex::GetVecOfPtrs(m_user_real_attrib_parser), amrex::GetVecOfPtrs(m_user_int_attrib_parser), #ifdef WARPX_QED @@ -1086,7 +1086,7 @@ PhysicalParticleContainer::AddPlasma (PlasmaInjector const& plasma_injector, int } uint64_t * AMREX_RESTRICT pa_idcpu = soa.GetIdCPUData().data() + old_size; - PlasmaParserHelper plasma_parser_helper (soa, old_size, m_user_int_attribs, m_user_real_attribs, particle_icomps, particle_comps, plasma_parser_wrapper); + PlasmaParserHelper plasma_parser_helper(soa, old_size, m_user_int_attribs, m_user_real_attribs, plasma_parser_wrapper); int** pa_user_int_data = plasma_parser_helper.getUserIntDataPtrs(); ParticleReal** pa_user_real_data = plasma_parser_helper.getUserRealDataPtrs(); amrex::ParserExecutor<7> const* user_int_parserexec_data = plasma_parser_helper.getUserIntParserExecData(); @@ -1094,11 +1094,11 @@ PhysicalParticleContainer::AddPlasma (PlasmaInjector const& plasma_injector, int int* pi = nullptr; if (do_field_ionization) { - pi = soa.GetIntData(particle_icomps["ionizationLevel"]).data() + old_size; + pi = soa.GetIntData("ionizationLevel").data() + old_size; } #ifdef WARPX_QED - const QEDHelper qed_helper(soa, old_size, particle_comps, + const QEDHelper qed_helper(soa, old_size, has_quantum_sync(), has_breit_wheeler(), m_shr_p_qs_engine, m_shr_p_bw_engine); #endif @@ -1351,16 +1351,11 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, #ifdef AMREX_USE_EB bool const inject_from_eb = plasma_injector.m_inject_from_eb; // whether to inject from EB or from a plane // Extract data structures for embedded boundaries + amrex::EBFArrayBoxFactory const* eb_factory = nullptr; amrex::FabArray const* eb_flag = nullptr; - amrex::MultiCutFab const* eb_bnd_area = nullptr; - amrex::MultiCutFab const* eb_bnd_normal = nullptr; - amrex::MultiCutFab const* eb_bnd_cent = nullptr; if (inject_from_eb) { - amrex::EBFArrayBoxFactory const& eb_box_factory = WarpX::GetInstance().fieldEBFactory(0); - eb_flag = &eb_box_factory.getMultiEBCellFlagFab(); - eb_bnd_area = &eb_box_factory.getBndryArea(); - eb_bnd_normal = &eb_box_factory.getBndryNormal(); - eb_bnd_cent = &eb_box_factory.getBndryCent(); + eb_factory = &(WarpX::GetInstance().fieldEBFactory(0)); + eb_flag = &(eb_factory->getMultiEBCellFlagFab()); } #endif @@ -1370,8 +1365,8 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, // we will then call Redistribute on this new container and finally // add the new particles to the original container. PhysicalParticleContainer tmp_pc(&WarpX::GetInstance()); - for (int ic = 0; ic < NumRuntimeRealComps(); ++ic) { tmp_pc.AddRealComp(false); } - for (int ic = 0; ic < NumRuntimeIntComps(); ++ic) { tmp_pc.AddIntComp(false); } + for (int ic = 0; ic < NumRuntimeRealComps(); ++ic) { tmp_pc.AddRealComp(GetRealSoANames()[ic + NArrayReal], false); } + for (int ic = 0; ic < NumRuntimeIntComps(); ++ic) { tmp_pc.AddIntComp(GetIntSoANames()[ic + NArrayInt], false); } tmp_pc.defineAllParticleTiles(); Box fine_injection_box; @@ -1456,17 +1451,8 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, } #ifdef AMREX_USE_EB - // Extract data structures for embedded boundaries - amrex::Array4::value_type> eb_flag_arr; - amrex::Array4 eb_bnd_area_arr; - amrex::Array4 eb_bnd_normal_arr; - amrex::Array4 eb_bnd_cent_arr; - if (inject_from_eb) { - eb_flag_arr = eb_flag->array(mfi); - eb_bnd_area_arr = eb_bnd_area->array(mfi); - eb_bnd_normal_arr = eb_bnd_normal->array(mfi); - eb_bnd_cent_arr = eb_bnd_cent->array(mfi); - } + auto eb_flag_arr = eb_flag ? eb_flag->const_array(mfi) : Array4{}; + auto eb_data = eb_factory ? eb_factory->getEBData(mfi) : EBData{}; #endif amrex::ParallelForRNG(overlap_box, [=] AMREX_GPU_DEVICE (int i, int j, int k, amrex::RandomEngine const& engine) noexcept @@ -1482,18 +1468,15 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, // Skip cells that are not partially covered by the EB if (eb_flag_arr(i,j,k).isRegular() || eb_flag_arr(i,j,k).isCovered()) { return; } // Scale by the (normalized) area of the EB surface in this cell - num_ppc_real_in_this_cell *= eb_bnd_area_arr(i,j,k); - } else + num_ppc_real_in_this_cell *= eb_data.get(i,j,k); + } #else amrex::Real const num_ppc_real_in_this_cell = num_ppc_real; // user input: number of macroparticles per cell #endif - { - // Injection from a plane - auto lo = getCellCoords(overlap_corner, dx, {0._rt, 0._rt, 0._rt}, iv); - auto hi = getCellCoords(overlap_corner, dx, {1._rt, 1._rt, 1._rt}, iv); - // Skip cells that do not overlap with the plane - if (!flux_pos->overlapsWith(lo, hi)) { return; } - } + // Skip cells that do not overlap with the bounds specified by the user (xmin/xmax, ymin/ymax, zmin/zmax) + auto lo = getCellCoords(overlap_corner, dx, {0._rt, 0._rt, 0._rt}, iv); + auto hi = getCellCoords(overlap_corner, dx, {1._rt, 1._rt, 1._rt}, iv); + if (!flux_pos->overlapsWith(lo, hi)) { return; } auto index = overlap_box.index(iv); // Take into account refined injection region @@ -1539,7 +1522,7 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, } uint64_t * AMREX_RESTRICT pa_idcpu = soa.GetIdCPUData().data() + old_size; - PlasmaParserHelper plasma_parser_helper (soa, old_size, m_user_int_attribs, m_user_real_attribs, particle_icomps, particle_comps, plasma_parser_wrapper); + PlasmaParserHelper plasma_parser_helper(soa, old_size, m_user_int_attribs, m_user_real_attribs, plasma_parser_wrapper); int** pa_user_int_data = plasma_parser_helper.getUserIntDataPtrs(); ParticleReal** pa_user_real_data = plasma_parser_helper.getUserRealDataPtrs(); amrex::ParserExecutor<7> const* user_int_parserexec_data = plasma_parser_helper.getUserIntParserExecData(); @@ -1547,11 +1530,11 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, int* p_ion_level = nullptr; if (do_field_ionization) { - p_ion_level = soa.GetIntData(particle_icomps["ionizationLevel"]).data() + old_size; + p_ion_level = soa.GetIntData("ionizationLevel").data() + old_size; } #ifdef WARPX_QED - const QEDHelper qed_helper(soa, old_size, particle_comps, + const QEDHelper qed_helper(soa, old_size, has_quantum_sync(), has_breit_wheeler(), m_shr_p_qs_engine, m_shr_p_bw_engine); #endif @@ -1577,7 +1560,10 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, Real scale_fac; #ifdef AMREX_USE_EB if (inject_from_eb) { - scale_fac = compute_scale_fac_area_eb(dx, num_ppc_real, eb_bnd_normal_arr, i, j, k ); + scale_fac = compute_scale_fac_area_eb(dx, num_ppc_real, + AMREX_D_DECL(eb_data.get(i,j,k,0), + eb_data.get(i,j,k,1), + eb_data.get(i,j,k,2))); } else #endif { @@ -1598,14 +1584,15 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, XDim3 r; #ifdef AMREX_USE_EB if (inject_from_eb) { + auto const& pt = eb_data.randomPointOnEB(i,j,k,engine); #if defined(WARPX_DIM_3D) - pos.x = overlap_corner[0] + (iv[0] + 0.5_rt + eb_bnd_cent_arr(i,j,k,0))*dx[0]; - pos.y = overlap_corner[1] + (iv[1] + 0.5_rt + eb_bnd_cent_arr(i,j,k,1))*dx[1]; - pos.z = overlap_corner[2] + (iv[2] + 0.5_rt + eb_bnd_cent_arr(i,j,k,2))*dx[2]; + pos.x = overlap_corner[0] + (iv[0] + 0.5_rt + pt[0])*dx[0]; + pos.y = overlap_corner[1] + (iv[1] + 0.5_rt + pt[1])*dx[1]; + pos.z = overlap_corner[2] + (iv[2] + 0.5_rt + pt[2])*dx[2]; #elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - pos.x = overlap_corner[0] + (iv[0] + 0.5_rt + eb_bnd_cent_arr(i,j,k,0))*dx[0]; + pos.x = overlap_corner[0] + (iv[0] + 0.5_rt + pt[0])*dx[0]; pos.y = 0.0_rt; - pos.z = overlap_corner[1] + (iv[1] + 0.5_rt + eb_bnd_cent_arr(i,j,k,1))*dx[1]; + pos.z = overlap_corner[1] + (iv[1] + 0.5_rt + pt[1])*dx[1]; #endif } else #endif @@ -1664,7 +1651,9 @@ PhysicalParticleContainer::AddPlasmaFlux (PlasmaInjector const& plasma_injector, // Injection from EB: rotate momentum according to the normal of the EB surface // (The above code initialized the momentum by assuming that z is the direction // normal to the EB surface. Thus we need to rotate from z to the normal.) - rotate_momentum_eb(pu, eb_bnd_normal_arr, i, j , k); + rotate_momentum_eb(pu, AMREX_D_DECL(eb_data.get(i,j,k,0), + eb_data.get(i,j,k,1), + eb_data.get(i,j,k,2))); } #endif @@ -1933,7 +1922,7 @@ PhysicalParticleContainer::Evolve (ablastr::fields::MultiFabRegister& fields, // Deposit charge before particle push, in component 0 of MultiFab rho. const int* const AMREX_RESTRICT ion_lev = (do_field_ionization)? - pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr():nullptr; + pti.GetiAttribs("ionizationLevel").dataPtr():nullptr; amrex::MultiFab* rho = fields.get(FieldType::rho_fp, lev); DepositCharge(pti, wp, ion_lev, rho, 0, 0, @@ -2029,7 +2018,7 @@ PhysicalParticleContainer::Evolve (ablastr::fields::MultiFabRegister& fields, const amrex::Real relative_time = (push_type == PushType::Explicit ? -0.5_rt * dt : 0.0_rt); const int* const AMREX_RESTRICT ion_lev = (do_field_ionization)? - pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr():nullptr; + pti.GetiAttribs("ionizationLevel").dataPtr():nullptr; // Deposit inside domains amrex::MultiFab * jx = fields.get(current_fp_string, Direction{0}, lev); @@ -2061,7 +2050,7 @@ PhysicalParticleContainer::Evolve (ablastr::fields::MultiFabRegister& fields, "Cannot deposit charge in rho component 1: only component 0 is allocated!"); const int* const AMREX_RESTRICT ion_lev = (do_field_ionization)? - pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr():nullptr; + pti.GetiAttribs("ionizationLevel").dataPtr():nullptr; DepositCharge(pti, wp, ion_lev, rho, 1, 0, np_current, thread_num, lev, lev); @@ -2435,7 +2424,7 @@ PhysicalParticleContainer::PushP (int lev, Real dt, int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr(); + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr(); } // Loop over the particles and update their momentum @@ -2631,7 +2620,7 @@ PhysicalParticleContainer::PushPX (WarpXParIter& pti, int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr() + offset; + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr() + offset; } const bool save_previous_position = m_save_previous_position; @@ -2640,12 +2629,12 @@ PhysicalParticleContainer::PushPX (WarpXParIter& pti, ParticleReal* z_old = nullptr; if (save_previous_position) { #if (AMREX_SPACEDIM >= 2) - x_old = pti.GetAttribs(particle_comps["prev_x"]).dataPtr() + offset; + x_old = pti.GetAttribs("prev_x").dataPtr() + offset; #endif #if defined(WARPX_DIM_3D) - y_old = pti.GetAttribs(particle_comps["prev_y"]).dataPtr() + offset; + y_old = pti.GetAttribs("prev_y").dataPtr() + offset; #endif - z_old = pti.GetAttribs(particle_comps["prev_z"]).dataPtr() + offset; + z_old = pti.GetAttribs("prev_z").dataPtr() + offset; amrex::ignore_unused(x_old, y_old); } @@ -2665,7 +2654,7 @@ PhysicalParticleContainer::PushPX (WarpXParIter& pti, const bool local_has_quantum_sync = has_quantum_sync(); if (local_has_quantum_sync) { evolve_opt = m_shr_p_qs_engine->build_evolve_functor(); - p_optical_depth_QSR = pti.GetAttribs(particle_comps["opticalDepthQSR"]).dataPtr() + offset; + p_optical_depth_QSR = pti.GetAttribs("opticalDepthQSR").dataPtr() + offset; } #endif @@ -2870,15 +2859,15 @@ PhysicalParticleContainer::ImplicitPushXP (WarpXParIter& pti, ParticleReal* const AMREX_RESTRICT uz = attribs[PIdx::uz].dataPtr() + offset; #if (AMREX_SPACEDIM >= 2) - ParticleReal* x_n = pti.GetAttribs(particle_comps["x_n"]).dataPtr(); + ParticleReal* x_n = pti.GetAttribs("x_n").dataPtr(); #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - ParticleReal* y_n = pti.GetAttribs(particle_comps["y_n"]).dataPtr(); + ParticleReal* y_n = pti.GetAttribs("y_n").dataPtr(); #endif - ParticleReal* z_n = pti.GetAttribs(particle_comps["z_n"]).dataPtr(); - ParticleReal* ux_n = pti.GetAttribs(particle_comps["ux_n"]).dataPtr(); - ParticleReal* uy_n = pti.GetAttribs(particle_comps["uy_n"]).dataPtr(); - ParticleReal* uz_n = pti.GetAttribs(particle_comps["uz_n"]).dataPtr(); + ParticleReal* z_n = pti.GetAttribs("z_n").dataPtr(); + ParticleReal* ux_n = pti.GetAttribs("ux_n").dataPtr(); + ParticleReal* uy_n = pti.GetAttribs("uy_n").dataPtr(); + ParticleReal* uz_n = pti.GetAttribs("uz_n").dataPtr(); const int do_copy = (m_do_back_transformed_particles && (a_dt_type!=DtType::SecondHalf) ); CopyParticleAttribs copyAttribs; @@ -2888,7 +2877,7 @@ PhysicalParticleContainer::ImplicitPushXP (WarpXParIter& pti, int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr() + offset; + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr() + offset; } // Loop over the particles and update their momentum @@ -2907,7 +2896,7 @@ PhysicalParticleContainer::ImplicitPushXP (WarpXParIter& pti, const bool local_has_quantum_sync = has_quantum_sync(); if (local_has_quantum_sync) { evolve_opt = m_shr_p_qs_engine->build_evolve_functor(); - p_optical_depth_QSR = pti.GetAttribs(particle_comps["opticalDepthQSR"]).dataPtr() + offset; + p_optical_depth_QSR = pti.GetAttribs("opticalDepthQSR").dataPtr() + offset; } #endif @@ -3121,7 +3110,7 @@ PhysicalParticleContainer::InitIonizationModule () physical_element == "H" || !do_adk_correction, "Correction to ADK by Zhang et al., PRA 90, 043410 (2014) only works with Hydrogen"); // Add runtime integer component for ionization level - NewIntComp("ionizationLevel"); + AddIntComp("ionizationLevel"); // Get atomic number and ionization energies from file const int ion_element_id = utils::physics::ion_map_ids.at(physical_element); ion_atomic_number = utils::physics::ion_atomic_numbers[ion_element_id]; @@ -3204,7 +3193,7 @@ PhysicalParticleContainer::getIonizationFunc (const WarpXParIter& pti, adk_exp_prefactor.dataPtr(), adk_power.dataPtr(), adk_correction_factors.dataPtr(), - particle_icomps["ionizationLevel"], + GetIntCompIndex("ionizationLevel"), ion_atomic_number, do_adk_correction}; } @@ -3310,14 +3299,14 @@ PhotonEmissionFilterFunc PhysicalParticleContainer::getPhotonEmissionFilterFunc () { WARPX_PROFILE("PhysicalParticleContainer::getPhotonEmissionFunc()"); - return PhotonEmissionFilterFunc{particle_runtime_comps["opticalDepthQSR"]}; + return PhotonEmissionFilterFunc{GetRealCompIndex("opticalDepthQSR") - NArrayReal}; } PairGenerationFilterFunc PhysicalParticleContainer::getPairGenerationFilterFunc () { WARPX_PROFILE("PhysicalParticleContainer::getPairGenerationFunc()"); - return PairGenerationFilterFunc{particle_runtime_comps["opticalDepthBW"]}; + return PairGenerationFilterFunc{GetRealCompIndex("opticalDepthBW") - NArrayReal}; } #endif diff --git a/Source/Particles/PinnedMemoryParticleContainer.H b/Source/Particles/PinnedMemoryParticleContainer.H index 402c621eb9a..b9fc4bbe79e 100644 --- a/Source/Particles/PinnedMemoryParticleContainer.H +++ b/Source/Particles/PinnedMemoryParticleContainer.H @@ -1,8 +1,8 @@ #ifndef WARPX_PinnedMemoryParticleContainer_H_ #define WARPX_PinnedMemoryParticleContainer_H_ -#include "NamedComponentParticleContainer.H" +#include "WarpXParticleContainer.H" -using PinnedMemoryParticleContainer = NamedComponentParticleContainer; +using PinnedMemoryParticleContainer = amrex::ParticleContainerPureSoA; #endif //WARPX_PinnedMemoryParticleContainer_H_ diff --git a/Source/Particles/Pusher/GetAndSetPosition.H b/Source/Particles/Pusher/GetAndSetPosition.H index ab06fe3d6cd..d2a223c57d8 100644 --- a/Source/Particles/Pusher/GetAndSetPosition.H +++ b/Source/Particles/Pusher/GetAndSetPosition.H @@ -9,7 +9,6 @@ #define WARPX_PARTICLES_PUSHER_GETANDSETPOSITION_H_ #include "Particles/WarpXParticleContainer.H" -#include "Particles/NamedComponentParticleContainer.H" #include #include diff --git a/Source/Particles/Resampling/VelocityCoincidenceThinning.H b/Source/Particles/Resampling/VelocityCoincidenceThinning.H index a815092e03e..d55aed99bcd 100644 --- a/Source/Particles/Resampling/VelocityCoincidenceThinning.H +++ b/Source/Particles/Resampling/VelocityCoincidenceThinning.H @@ -14,6 +14,8 @@ #include "Utils/Parser/ParserUtils.H" #include "Utils/ParticleUtils.H" +#include + /** * \brief This class implements a particle merging scheme wherein particles * are clustered in phase space and particles in the same cluster is merged @@ -66,14 +68,6 @@ public: */ struct HeapSort { - AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE - void swap(int &a, int &b) const - { - const auto temp = b; - b = a; - a = temp; - } - AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE void operator() (int index_array[], const int bin_array[], const int start, const int n) const { @@ -84,7 +78,7 @@ public: // move child through heap if it is bigger than its parent while (j > 0 && bin_array[index_array[j+start]] > bin_array[index_array[(j - 1)/2 + start]]) { // swap child and parent until branch is properly ordered - swap(index_array[j+start], index_array[(j - 1)/2 + start]); + amrex::Swap(index_array[j+start], index_array[(j - 1)/2 + start]); j = (j - 1) / 2; } } @@ -92,7 +86,7 @@ public: for (int i = n - 1; i > 0; i--) { // swap value of first (now the largest value) to the new end point - swap(index_array[start], index_array[i+start]); + amrex::Swap(index_array[start], index_array[i+start]); // remake the max heap int j = 0, index; @@ -105,7 +99,7 @@ public: } // if parent is smaller than child, swap parent with child having higher value if (index < i && bin_array[index_array[j+start]] < bin_array[index_array[index+start]]) { - swap(index_array[j+start], index_array[index+start]); + amrex::Swap(index_array[j+start], index_array[index+start]); } j = index; } diff --git a/Source/Particles/RigidInjectedParticleContainer.cpp b/Source/Particles/RigidInjectedParticleContainer.cpp index d1e1f48ab38..420d7599ecb 100644 --- a/Source/Particles/RigidInjectedParticleContainer.cpp +++ b/Source/Particles/RigidInjectedParticleContainer.cpp @@ -176,10 +176,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, // Save the position, momentum and optical depth, making copies amrex::Gpu::DeviceVector xp_save, yp_save, zp_save; - amrex::Gpu::DeviceVector uxp_save, uyp_save, uzp_save; -#ifdef WARPX_QED - amrex::Gpu::DeviceVector optical_depth_save; -#endif const auto GetPosition = GetParticlePosition(pti, offset); auto SetPosition = SetParticlePosition(pti, offset); @@ -188,12 +184,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, amrex::ParticleReal* const AMREX_RESTRICT uy = uyp.dataPtr() + offset; amrex::ParticleReal* const AMREX_RESTRICT uz = uzp.dataPtr() + offset; -#ifdef WARPX_QED - const bool loc_has_quantum_sync = has_quantum_sync(); - amrex::ParticleReal* AMREX_RESTRICT p_optical_depth = nullptr; - amrex::ParticleReal* AMREX_RESTRICT p_optical_depth_save = nullptr; -#endif - if (!done_injecting_lev) { // If the old values are not already saved, create copies here. @@ -201,27 +191,10 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, yp_save.resize(np_to_push); zp_save.resize(np_to_push); - uxp_save.resize(np_to_push); - uyp_save.resize(np_to_push); - uzp_save.resize(np_to_push); - amrex::ParticleReal* const AMREX_RESTRICT xp_save_ptr = xp_save.dataPtr(); amrex::ParticleReal* const AMREX_RESTRICT yp_save_ptr = yp_save.dataPtr(); amrex::ParticleReal* const AMREX_RESTRICT zp_save_ptr = zp_save.dataPtr(); - amrex::ParticleReal* const AMREX_RESTRICT uxp_save_ptr = uxp_save.dataPtr(); - amrex::ParticleReal* const AMREX_RESTRICT uyp_save_ptr = uyp_save.dataPtr(); - amrex::ParticleReal* const AMREX_RESTRICT uzp_save_ptr = uzp_save.dataPtr(); - -#ifdef WARPX_QED - if(loc_has_quantum_sync){ - p_optical_depth = pti.GetAttribs(particle_comps["opticalDepthQSR"]).dataPtr() - + offset; - optical_depth_save.resize(np_to_push); - p_optical_depth_save = optical_depth_save.dataPtr(); - } -#endif - amrex::ParallelFor( np_to_push, [=] AMREX_GPU_DEVICE (long i) { amrex::ParticleReal xp, yp, zp; @@ -229,13 +202,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, xp_save_ptr[i] = xp; yp_save_ptr[i] = yp; zp_save_ptr[i] = zp; - uxp_save_ptr[i] = ux[i]; - uyp_save_ptr[i] = uy[i]; - uzp_save_ptr[i] = uz[i]; -#ifdef WARPX_QED - if(loc_has_quantum_sync){ - p_optical_depth_save[i] = p_optical_depth[i];} -#endif }); } @@ -252,9 +218,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, amrex::ParticleReal* AMREX_RESTRICT x_save = xp_save.dataPtr(); amrex::ParticleReal* AMREX_RESTRICT y_save = yp_save.dataPtr(); amrex::ParticleReal* AMREX_RESTRICT z_save = zp_save.dataPtr(); - amrex::ParticleReal* AMREX_RESTRICT ux_save = uxp_save.dataPtr(); - amrex::ParticleReal* AMREX_RESTRICT uy_save = uyp_save.dataPtr(); - amrex::ParticleReal* AMREX_RESTRICT uz_save = uzp_save.dataPtr(); // Undo the push for particles not injected yet. // The zp are advanced a fixed amount. @@ -267,9 +230,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, amrex::ParticleReal xp, yp, zp; GetPosition(i, xp, yp, zp); if (zp <= z_plane_lev) { - ux[i] = ux_save[i]; - uy[i] = uy_save[i]; - uz[i] = uz_save[i]; xp = x_save[i]; yp = y_save[i]; if (rigid) { @@ -281,10 +241,6 @@ RigidInjectedParticleContainer::PushPX (WarpXParIter& pti, zp = z_save[i] + dt*uz[i]*gi; } SetPosition(i, xp, yp, zp); -#ifdef WARPX_QED - if(loc_has_quantum_sync){ - p_optical_depth[i] = p_optical_depth_save[i];} -#endif } }); } @@ -389,7 +345,7 @@ RigidInjectedParticleContainer::PushP (int lev, Real dt, int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr(); + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr(); } // Save the position and momenta, making copies diff --git a/Source/Particles/Sorting/SortingUtils.H b/Source/Particles/Sorting/SortingUtils.H index ba7761bf48a..49366e888ae 100644 --- a/Source/Particles/Sorting/SortingUtils.H +++ b/Source/Particles/Sorting/SortingUtils.H @@ -174,9 +174,9 @@ class fillBufferFlagRemainingParticles amrex::GpuArray m_inv_cell_size; amrex::Box m_domain; int* m_inexflag_ptr; - WarpXParticleContainer::ParticleTileType::ConstParticleTileDataType const m_ptd; + WarpXParticleContainer::ParticleTileType::ConstParticleTileDataType m_ptd; amrex::Array4 m_buffer_mask; - int const m_start_index; + int m_start_index; int const* m_indices_ptr; }; diff --git a/Source/Particles/WarpXParticleContainer.H b/Source/Particles/WarpXParticleContainer.H index 9c316b110ee..a4581d4415d 100644 --- a/Source/Particles/WarpXParticleContainer.H +++ b/Source/Particles/WarpXParticleContainer.H @@ -23,7 +23,6 @@ # include "ElementaryProcess/QEDInternals/QuantumSyncEngineWrapper_fwd.H" #endif #include "MultiParticleContainer_fwd.H" -#include "NamedComponentParticleContainer.H" #include @@ -49,6 +48,55 @@ #include #include +/** Real Particle Attributes stored in amrex::ParticleContainer's struct of array + */ +struct PIdx +{ + enum { +#if !defined (WARPX_DIM_1D_Z) + x, +#endif +#if defined (WARPX_DIM_3D) + y, +#endif + z, + w, ///< weight + ux, uy, uz, +#ifdef WARPX_DIM_RZ + theta, ///< RZ needs all three position components +#endif + nattribs ///< number of compile-time attributes + }; + + //! component names + static constexpr auto names = { +#if !defined (WARPX_DIM_1D_Z) + "x", +#endif +#if defined (WARPX_DIM_3D) + "y", +#endif + "z", + "w", + "ux", + "uy", + "uz", +#ifdef WARPX_DIM_RZ + "theta" +#endif + }; + + static_assert(names.size() == nattribs); +}; + +struct IntIdx { + enum + { + nattribs ///< the number of attributes above (always last) + }; + + static constexpr std::initializer_list names = {}; +}; class WarpXParIter : public amrex::ParIterSoA @@ -80,10 +128,35 @@ public: return GetStructOfArrays().GetRealData(comp); } + [[nodiscard]] const IntVector& GetiAttribs (int comp) const + { + return GetStructOfArrays().GetIntData(comp); + } + [[nodiscard]] IntVector& GetiAttribs (int comp) { return GetStructOfArrays().GetIntData(comp); } + + [[nodiscard]] const RealVector& GetAttribs (const std::string& name) const + { + return GetStructOfArrays().GetRealData(name); + } + + [[nodiscard]] RealVector& GetAttribs (const std::string& name) + { + return GetStructOfArrays().GetRealData(name); + } + + [[nodiscard]] const IntVector& GetiAttribs (const std::string& name) const + { + return GetStructOfArrays().GetIntData(name); + } + + [[nodiscard]] IntVector& GetiAttribs (const std::string& name) + { + return GetStructOfArrays().GetIntData(name); + } }; /** @@ -109,7 +182,7 @@ public: * derived classes, e.g., Evolve) or actual functions (e.g. CurrentDeposition). */ class WarpXParticleContainer - : public NamedComponentParticleContainer + : public amrex::ParticleContainerPureSoA { public: friend MultiParticleContainer; diff --git a/Source/Particles/WarpXParticleContainer.cpp b/Source/Particles/WarpXParticleContainer.cpp index 36793c8619b..8e91093d95b 100644 --- a/Source/Particles/WarpXParticleContainer.cpp +++ b/Source/Particles/WarpXParticleContainer.cpp @@ -89,10 +89,14 @@ WarpXParIter::WarpXParIter (ContainerType& pc, int level, MFItInfo& info) } WarpXParticleContainer::WarpXParticleContainer (AmrCore* amr_core, int ispecies) - : NamedComponentParticleContainer(amr_core->GetParGDB()) + : amrex::ParticleContainerPureSoA(amr_core->GetParGDB()) , species_id(ispecies) { SetParticleSize(); + SetSoACompileTimeNames( + {PIdx::names.begin(), PIdx::names.end()}, + {IntIdx::names.begin(), IntIdx::names.end()} + ); ReadParameters(); // Reading the external fields needs to be here since ReadParameters @@ -585,49 +589,64 @@ WarpXParticleContainer::DepositCurrent (WarpXParIter& pti, else { if (WarpX::current_deposition_algo == CurrentDepositionAlgo::Esirkepov) { if (push_type == PushType::Explicit) { - if (WarpX::nox == 1){ + + amrex::Array4 eb_reduce_particle_shape; + if (EB::enabled()) { + eb_reduce_particle_shape = (*warpx.GetEBReduceParticleShapeFlag()[lev])[pti].array(); + } + + if (WarpX::nox == 1){ doEsirkepovDepositionShapeN<1>( - GetPosition, wp.dataPtr() + offset, uxp.dataPtr() + offset, - uyp.dataPtr() + offset, uzp.dataPtr() + offset, ion_lev, - jx_arr, jy_arr, jz_arr, np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, - WarpX::n_rz_azimuthal_modes); + GetPosition, wp.dataPtr() + offset, uxp.dataPtr() + offset, + uyp.dataPtr() + offset, uzp.dataPtr() + offset, ion_lev, + jx_arr, jy_arr, jz_arr, + np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, + WarpX::n_rz_azimuthal_modes, + eb_reduce_particle_shape, EB::enabled() ); } else if (WarpX::nox == 2){ doEsirkepovDepositionShapeN<2>( GetPosition, wp.dataPtr() + offset, uxp.dataPtr() + offset, uyp.dataPtr() + offset, uzp.dataPtr() + offset, ion_lev, - jx_arr, jy_arr, jz_arr, np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, - WarpX::n_rz_azimuthal_modes); + jx_arr, jy_arr, jz_arr, + np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, + WarpX::n_rz_azimuthal_modes, + eb_reduce_particle_shape, EB::enabled() ); } else if (WarpX::nox == 3){ doEsirkepovDepositionShapeN<3>( GetPosition, wp.dataPtr() + offset, uxp.dataPtr() + offset, uyp.dataPtr() + offset, uzp.dataPtr() + offset, ion_lev, - jx_arr, jy_arr, jz_arr, np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, - WarpX::n_rz_azimuthal_modes); + jx_arr, jy_arr, jz_arr, + np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, + WarpX::n_rz_azimuthal_modes, + eb_reduce_particle_shape, EB::enabled() ); } else if (WarpX::nox == 4){ doEsirkepovDepositionShapeN<4>( GetPosition, wp.dataPtr() + offset, uxp.dataPtr() + offset, uyp.dataPtr() + offset, uzp.dataPtr() + offset, ion_lev, - jx_arr, jy_arr, jz_arr, np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, - WarpX::n_rz_azimuthal_modes); + jx_arr, jy_arr, jz_arr, + np_to_deposit, dt, relative_time, dinv, xyzmin, lo, q, + WarpX::n_rz_azimuthal_modes, + eb_reduce_particle_shape, EB::enabled() ); } + } else if (push_type == PushType::Implicit) { #if (AMREX_SPACEDIM >= 2) - auto& xp_n = pti.GetAttribs(particle_comps["x_n"]); + auto& xp_n = pti.GetAttribs("x_n"); const ParticleReal* xp_n_data = xp_n.dataPtr() + offset; #else const ParticleReal* xp_n_data = nullptr; #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - auto& yp_n = pti.GetAttribs(particle_comps["y_n"]); + auto& yp_n = pti.GetAttribs("y_n"); const ParticleReal* yp_n_data = yp_n.dataPtr() + offset; #else const ParticleReal* yp_n_data = nullptr; #endif - auto& zp_n = pti.GetAttribs(particle_comps["z_n"]); + auto& zp_n = pti.GetAttribs("z_n"); const ParticleReal* zp_n_data = zp_n.dataPtr() + offset; - auto& uxp_n = pti.GetAttribs(particle_comps["ux_n"]); - auto& uyp_n = pti.GetAttribs(particle_comps["uy_n"]); - auto& uzp_n = pti.GetAttribs(particle_comps["uz_n"]); + auto& uxp_n = pti.GetAttribs("ux_n"); + auto& uyp_n = pti.GetAttribs("uy_n"); + auto& uzp_n = pti.GetAttribs("uz_n"); if (WarpX::nox == 1){ doChargeConservingDepositionShapeNImplicit<1>( xp_n_data, yp_n_data, zp_n_data, @@ -665,22 +684,22 @@ WarpXParticleContainer::DepositCurrent (WarpXParIter& pti, } else if (WarpX::current_deposition_algo == CurrentDepositionAlgo::Villasenor) { if (push_type == PushType::Implicit) { #if (AMREX_SPACEDIM >= 2) - auto& xp_n = pti.GetAttribs(particle_comps["x_n"]); + auto& xp_n = pti.GetAttribs("x_n"); const ParticleReal* xp_n_data = xp_n.dataPtr() + offset; #else const ParticleReal* xp_n_data = nullptr; #endif #if defined(WARPX_DIM_3D) || defined(WARPX_DIM_RZ) - auto& yp_n = pti.GetAttribs(particle_comps["y_n"]); + auto& yp_n = pti.GetAttribs("y_n"); const ParticleReal* yp_n_data = yp_n.dataPtr() + offset; #else const ParticleReal* yp_n_data = nullptr; #endif - auto& zp_n = pti.GetAttribs(particle_comps["z_n"]); + auto& zp_n = pti.GetAttribs("z_n"); const ParticleReal* zp_n_data = zp_n.dataPtr() + offset; - auto& uxp_n = pti.GetAttribs(particle_comps["ux_n"]); - auto& uyp_n = pti.GetAttribs(particle_comps["uy_n"]); - auto& uzp_n = pti.GetAttribs(particle_comps["uz_n"]); + auto& uxp_n = pti.GetAttribs("ux_n"); + auto& uyp_n = pti.GetAttribs("uy_n"); + auto& uzp_n = pti.GetAttribs("uz_n"); if (WarpX::nox == 1){ doVillasenorDepositionShapeNImplicit<1>( xp_n_data, yp_n_data, zp_n_data, @@ -775,9 +794,9 @@ WarpXParticleContainer::DepositCurrent (WarpXParIter& pti, xyzmin, lo, q, WarpX::n_rz_azimuthal_modes); } } else if (push_type == PushType::Implicit) { - auto& uxp_n = pti.GetAttribs(particle_comps["ux_n"]); - auto& uyp_n = pti.GetAttribs(particle_comps["uy_n"]); - auto& uzp_n = pti.GetAttribs(particle_comps["uz_n"]); + auto& uxp_n = pti.GetAttribs("ux_n"); + auto& uyp_n = pti.GetAttribs("uy_n"); + auto& uzp_n = pti.GetAttribs("uz_n"); if (WarpX::nox == 1){ doDepositionShapeNImplicit<1>( GetPosition, wp.dataPtr() + offset, @@ -854,7 +873,7 @@ WarpXParticleContainer::DepositCurrent ( int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr(); + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr(); } DepositCurrent(pti, wp, uxp, uyp, uzp, ion_lev, @@ -1247,7 +1266,7 @@ WarpXParticleContainer::DepositCharge (amrex::MultiFab* rho, int* AMREX_RESTRICT ion_lev = nullptr; if (do_field_ionization) { - ion_lev = pti.GetiAttribs(particle_icomps["ionizationLevel"]).dataPtr(); + ion_lev = pti.GetiAttribs("ionizationLevel").dataPtr(); } DepositCharge(pti, wp, ion_lev, rho, icomp, 0, np, thread_num, lev, lev); @@ -1531,8 +1550,16 @@ WarpXParticleContainer::PushX (int lev, amrex::Real dt) // without runtime component). void WarpXParticleContainer::defineAllParticleTiles () noexcept { - // Call the parent class's method - NamedComponentParticleContainer::defineAllParticleTiles(); + for (int lev = 0; lev <= finestLevel(); ++lev) + { + for (auto mfi = MakeMFIter(lev); mfi.isValid(); ++mfi) + { + const int grid_id = mfi.index(); + const int tile_id = mfi.LocalTileIndex(); + DefineAndReturnParticleTile(lev, grid_id, tile_id); + } + } + // Resize the tmp_particle_data (no present in parent class) tmp_particle_data.resize(finestLevel()+1); @@ -1555,7 +1582,7 @@ WarpXParticleContainer::particlePostLocate(ParticleType& p, { if (not do_splitting) { return; } - // Tag particle if goes to higher level. + // Tag particle if it goes to a higher level. // It will be split later in the loop if (pld.m_lev == lev+1 and p.id() != amrex::LongParticleIds::NoSplitParticleID diff --git a/Source/Python/Particles/CMakeLists.txt b/Source/Python/Particles/CMakeLists.txt index eed1bb07c74..6b7754fdf2d 100644 --- a/Source/Python/Particles/CMakeLists.txt +++ b/Source/Python/Particles/CMakeLists.txt @@ -10,7 +10,6 @@ foreach(D IN LISTS WarpX_DIMS) # pybind11 ParticleBoundaryBuffer.cpp MultiParticleContainer.cpp - PinnedMemoryParticleContainer.cpp WarpXParticleContainer.cpp ) endif() diff --git a/Source/Python/Particles/PinnedMemoryParticleContainer.cpp b/Source/Python/Particles/PinnedMemoryParticleContainer.cpp deleted file mode 100644 index 21dd6a9d364..00000000000 --- a/Source/Python/Particles/PinnedMemoryParticleContainer.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright 2021-2023 The WarpX Community - * - * Authors: Axel Huebl, Remi Lehe, Roelof Groenewald - * License: BSD-3-Clause-LBNL - */ - -#include "Python/pyWarpX.H" - -#include - - -void init_PinnedMemoryParticleContainer (py::module& m) -{ - py::class_< - PinnedMemoryParticleContainer, - amrex::ParticleContainerPureSoA - > pmpc (m, "PinnedMemoryParticleContainer"); - pmpc - .def_property_readonly("real_comp_names", - [](PinnedMemoryParticleContainer& pc) - { - return pc.getParticleComps(); - } - ) - .def_property_readonly("int_comp_names", - [](PinnedMemoryParticleContainer& pc) - { - return pc.getParticleiComps(); - } - ); -} diff --git a/Source/Python/Particles/WarpXParticleContainer.cpp b/Source/Python/Particles/WarpXParticleContainer.cpp index 7bf02aab62b..73e0a8b0db0 100644 --- a/Source/Python/Particles/WarpXParticleContainer.cpp +++ b/Source/Python/Particles/WarpXParticleContainer.cpp @@ -30,7 +30,7 @@ void init_WarpXParticleContainer (py::module& m) > wpc (m, "WarpXParticleContainer"); wpc .def("add_real_comp", - [](WarpXParticleContainer& pc, const std::string& name, bool comm) { pc.NewRealComp(name, comm); }, + [](WarpXParticleContainer& pc, const std::string& name, bool comm) { pc.AddRealComp(name, comm); }, py::arg("name"), py::arg("comm") ) .def("add_n_particles", @@ -85,19 +85,19 @@ void init_WarpXParticleContainer (py::module& m) py::arg("nattr_int"), py::arg("attr_int"), py::arg("uniqueparticles"), py::arg("id")=-1 ) - .def("get_comp_index", + .def("get_comp_index", // deprecated: use pyAMReX get_real_comp_index [](WarpXParticleContainer& pc, std::string comp_name) { - auto particle_comps = pc.getParticleComps(); - return particle_comps.at(comp_name); + py::print("get_comp_index is deprecated. Use get_real_comp_index instead."); + return pc.GetRealCompIndex(comp_name); }, py::arg("comp_name") ) - .def("get_icomp_index", + .def("get_icomp_index", // deprecated: use pyAMReX get_int_comp_index [](WarpXParticleContainer& pc, std::string comp_name) { - auto particle_comps = pc.getParticleiComps(); - return particle_comps.at(comp_name); + py::print("get_icomp_index is deprecated. Use get_int_comp_index instead."); + return pc.GetIntCompIndex(comp_name); }, py::arg("comp_name") ) diff --git a/Source/Python/WarpX.cpp b/Source/Python/WarpX.cpp index 0b1ae49dfbc..5b4b07af07b 100644 --- a/Source/Python/WarpX.cpp +++ b/Source/Python/WarpX.cpp @@ -7,6 +7,7 @@ #include // see WarpX.cpp - full includes for _fwd.H headers +#include #include #include #include @@ -141,7 +142,7 @@ where 'prefix' is the part of 'internal_name';' before the [])doc" py::arg("scalar_name"), py::arg("level"), py::return_value_policy::reference_internal, - R"doc(Return scalar fields (MultiFabs) by name and level, e.g., ``\"rho_fp\"``, ``\"phi_fp"``, ... + R"doc(Return scalar fields (MultiFabs) by name and level. The name is in the form like``\"rho_fp\"``, ``\"phi_fp"``. The level is an integer with 0 being the lowest level. The physical fields in WarpX have the following naming: @@ -163,7 +164,30 @@ The physical fields in WarpX have the following naming: py::arg("dir"), py::arg("level"), py::return_value_policy::reference_internal, - R"doc(Return the component of a vector field (MultiFab) by name, direction, and level, e.g., ``\"Efield_aux\"``, ``\"Efield_fp"``, ... + R"doc(Return the component of a vector field (MultiFab) by name, direction, and level. The name is in the form like ``\"Efield_aux\"``, ``\"Efield_fp"``, etc. The direction is a Direction instance, Direction(idir) where idir is an integer 0, 1, or 2. The level is an integer with 0 being the lowest level. + +The physical fields in WarpX have the following naming: + +- ``_fp`` are the "fine" patches, the regular resolution of a current mesh-refinement level +- ``_aux`` are temporary (auxiliar) patches at the same resolution as ``_fp``. + They usually include contributions from other levels and can be interpolated for gather routines of particles. +- ``_cp`` are "coarse" patches, at the same resolution (but not necessary values) as the ``_fp`` of ``level - 1`` + (only for level 1 and higher).)doc" + ) + .def("multifab", + [](WarpX & wx, std::string vector_name, int idir, int level) { + Direction const dir{idir}; + if (wx.m_fields.has(vector_name, dir, level)) { + return wx.m_fields.get(vector_name, dir, level); + } else { + throw std::runtime_error("The vector field '" + vector_name + "' is unknown or is not allocated!"); + } + }, + py::arg("vector_name"), + py::arg("idir"), + py::arg("level"), + py::return_value_policy::reference_internal, + R"doc(Return the component of a vector field (MultiFab) by name, direction, and level. The name is in the form like ``\"Efield_aux\"``, ``\"Efield_fp"``, etc. The direction is an integer 0, 1, or 2. The level is an integer with 0 being the lowest level. The physical fields in WarpX have the following naming: @@ -242,10 +266,14 @@ The physical fields in WarpX have the following naming: py::arg("potential"), "Sets the EB potential string and updates the function parser." ) - .def_static("run_div_cleaner", - [] () { WarpX::ProjectionCleanDivB(); }, + .def("run_div_cleaner", + [] (WarpX& wx) { wx.ProjectionCleanDivB(); }, "Executes projection based divergence cleaner on loaded Bfield_fp_external." ) + .def_static("calculate_hybrid_external_curlA", + [] (WarpX& wx) { wx.CalculateExternalCurlA(); }, + "Executes calculation of the curl of the external A in the hybrid solver." + ) .def("synchronize", [] (WarpX& wx) { wx.Synchronize(); }, "Synchronize particle velocities and positions." diff --git a/Source/Python/callbacks.cpp b/Source/Python/callbacks.cpp index 79f15c62835..81d379b189a 100644 --- a/Source/Python/callbacks.cpp +++ b/Source/Python/callbacks.cpp @@ -33,8 +33,8 @@ void ExecutePythonCallback ( const std::string& name ) try { warpx_callback_py_map[name](); } catch (std::exception &e) { - std::cerr << "Python callback '" << name << "' failed!" << std::endl; - std::cerr << e.what() << std::endl; + std::cerr << "Python callback '" << name << "' failed!" << "\n"; + std::cerr << e.what() << "\n"; std::exit(3); // note: NOT amrex::Abort(), to avoid hangs with MPI // future note: diff --git a/Source/Python/pyWarpX.cpp b/Source/Python/pyWarpX.cpp index e128599abd0..8ae174b4d3e 100644 --- a/Source/Python/pyWarpX.cpp +++ b/Source/Python/pyWarpX.cpp @@ -34,7 +34,6 @@ void init_BoundaryBufferParIter (py::module&); void init_MultiParticleContainer (py::module&); void init_MultiFabRegister (py::module&); void init_ParticleBoundaryBuffer (py::module&); -void init_PinnedMemoryParticleContainer (py::module&); void init_WarpXParIter (py::module&); void init_WarpXParticleContainer (py::module&); void init_WarpX(py::module&); @@ -61,7 +60,6 @@ PYBIND11_MODULE(PYWARPX_MODULE_NAME, m) { // note: order from parent to child classes init_MultiFabRegister(m); - init_PinnedMemoryParticleContainer(m); init_WarpXParticleContainer(m); init_WarpXParIter(m); init_BoundaryBufferParIter(m); @@ -95,7 +93,7 @@ PYBIND11_MODULE(PYWARPX_MODULE_NAME, m) { // TODO broken numpy if not at least v1.15.0: raise warning // auto numpy = py::module::import("numpy"); // auto npversion = numpy.attr("__version__"); - // std::cout << "numpy version: " << py::str(npversion) << std::endl; + // std::cout << "numpy version: " << py::str(npversion) << "\n"; m.def("amrex_init", [](const py::list args) { diff --git a/Source/Utils/Parser/ParserUtils.H b/Source/Utils/Parser/ParserUtils.H index 96937abdbbe..19f976c3a6c 100644 --- a/Source/Utils/Parser/ParserUtils.H +++ b/Source/Utils/Parser/ParserUtils.H @@ -88,6 +88,20 @@ namespace utils::parser std::string& stored_string); + /** + * \brief If the input is provided, parse the string (typically a mathematical expression) from the + * input file and store it into a variable, replacing its contents. + * + * \param pp used to read the query_string `pp.=string` + * \param query_string ParmParse.query will look for this string + * \param stored_string variable in which the string to parse is stored + */ + bool Query_parserString( + amrex::ParmParse const& pp, + std::string const& query_string, + std::string& stored_string); + + /** Parse a string and return as a double precision floating point number * * In case the string cannot be interpreted as a double, diff --git a/Source/Utils/Parser/ParserUtils.cpp b/Source/Utils/Parser/ParserUtils.cpp index 0339b766e38..d017a6e019c 100644 --- a/Source/Utils/Parser/ParserUtils.cpp +++ b/Source/Utils/Parser/ParserUtils.cpp @@ -51,6 +51,19 @@ void utils::parser::Store_parserString( } } +bool utils::parser::Query_parserString( + amrex::ParmParse const& pp, + std::string const& query_string, + std::string& stored_string) +{ + bool const input_specified = pp.contains(query_string.c_str()); + if (input_specified) { + stored_string.clear(); + utils::parser::Store_parserString(pp, query_string, stored_string); + } + return input_specified; +} + int utils::parser::query (const amrex::ParmParse& a_pp, std::string const& group, char const * str, std::string& val) { const bool is_specified_without_group = a_pp.contains(str); diff --git a/Source/Utils/WarpXAlgorithmSelection.H b/Source/Utils/WarpXAlgorithmSelection.H index 99205c77a00..261decf768c 100644 --- a/Source/Utils/WarpXAlgorithmSelection.H +++ b/Source/Utils/WarpXAlgorithmSelection.H @@ -33,6 +33,7 @@ AMREX_ENUM(EvolveScheme, Explicit, ThetaImplicitEM, SemiImplicitEM, + StrangImplicitSpectralEM, Default = Explicit); /** @@ -62,6 +63,7 @@ AMREX_ENUM(ElectrostaticSolverAlgo, Relativistic, LabFrameElectroMagnetostatic, LabFrame, + LabFrameEffectivePotential, Default = None); AMREX_ENUM(PoissonSolverAlgo, @@ -123,16 +125,17 @@ AMREX_ENUM(FieldBoundaryType, Periodic, PEC, //!< perfect electric conductor (PEC) with E_tangential=0 PMC, //!< perfect magnetic conductor (PMC) with B_tangential=0 + Neumann = PMC, // For electrostatic, the normal E is set to zero Damped, // Fields in the guard cells are damped for PSATD //in the moving window direction Absorbing_SilverMueller, // Silver-Mueller boundary condition absorbingsilvermueller = Absorbing_SilverMueller, - Neumann, // For electrostatic, the normal E is set to zero None, // The fields values at the boundary are not updated. This is // useful for RZ simulations, at r=0. Open, // Used in the Integrated Green Function Poisson solver // Note that the solver implicitely assumes open BCs: // no need to enforce them separately + PECInsulator, // Mixed boundary with PEC and insulator Default = PML); /** Particle boundary conditions at the domain boundary diff --git a/Source/Utils/WarpXMovingWindow.cpp b/Source/Utils/WarpXMovingWindow.cpp index d5cebd69254..281aa5e75ba 100644 --- a/Source/Utils/WarpXMovingWindow.cpp +++ b/Source/Utils/WarpXMovingWindow.cpp @@ -57,6 +57,199 @@ using namespace amrex; +namespace +{ + + /** This function shifts a MultiFab in a given direction + * + * \param[in,out] mf the MultiFab to be shifted + * \param[in] geom the Geometry object associated to the level of the MultiFab mf + * \param[in] num_shift magnitude of the shift (cell number) + * \param[in] dir direction of the shift + * \param[in] safe_guard_cells flag to enable "safe mode" data exchanges with more guard cells + * \param[in] do_single_precision_comms flag to enable single precision communications + * \param[in,out] cost the pointer to the data structure holding costs for timer-based load-balance + * \param[in] external_field the external field (used to initialize EM fields) + * \param[in] useparser flag to enable the use of a field parser to initialize EM fields + * \param[in] field_parser the field parser + * \param[in] PMLRZ_flag flag to enable a special treatment for PML in RZ simulations + */ + void shiftMF ( + amrex::MultiFab& mf, const amrex::Geometry& geom, + int num_shift, int dir, + bool safe_guard_cells, bool do_single_precision_comms, + amrex::LayoutData* cost, + amrex::Real external_field=0.0, bool useparser = false, + amrex::ParserExecutor<3> const& field_parser={}, + const bool PMLRZ_flag = false) + { + using namespace amrex::literals; + WARPX_PROFILE("warpx::shiftMF()"); + const amrex::BoxArray& ba = mf.boxArray(); + const amrex::DistributionMapping& dm = mf.DistributionMap(); + const int nc = mf.nComp(); + const amrex::IntVect& ng = mf.nGrowVect(); + + AMREX_ALWAYS_ASSERT(ng[dir] >= std::abs(num_shift)); + + amrex::MultiFab tmpmf(ba, dm, nc, ng); + amrex::MultiFab::Copy(tmpmf, mf, 0, 0, nc, ng); + + if ( safe_guard_cells ) { + // Fill guard cells. + ablastr::utils::communication::FillBoundary(tmpmf, do_single_precision_comms, geom.periodicity()); + } else { + amrex::IntVect ng_mw = amrex::IntVect::TheUnitVector(); + // Enough guard cells in the MW direction + ng_mw[dir] = std::abs(num_shift); + // Make sure we don't exceed number of guard cells allocated + ng_mw = ng_mw.min(ng); + // Fill guard cells. + ablastr::utils::communication::FillBoundary(tmpmf, ng_mw, do_single_precision_comms, geom.periodicity()); + } + + // Make a box that covers the region that the window moved into + const amrex::IndexType& typ = ba.ixType(); + const amrex::Box& domainBox = geom.Domain(); + amrex::Box adjBox; + if (num_shift > 0) { + adjBox = adjCellHi(domainBox, dir, ng[dir]); + } else { + adjBox = adjCellLo(domainBox, dir, ng[dir]); + } + adjBox = amrex::convert(adjBox, typ); + + for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { + if (idim == dir and typ.nodeCentered(dir)) { + if (num_shift > 0) { + adjBox.growLo(idim, -1); + } else { + adjBox.growHi(idim, -1); + } + } else if (idim != dir) { + adjBox.growLo(idim, ng[idim]); + adjBox.growHi(idim, ng[idim]); + } + } + + amrex::IntVect shiftiv(0); + shiftiv[dir] = num_shift; + const amrex::Dim3 shift = shiftiv.dim3(); + + const amrex::RealBox& real_box = geom.ProbDomain(); + const auto dx = geom.CellSizeArray(); + +#ifdef AMREX_USE_OMP + #pragma omp parallel if (Gpu::notInLaunchRegion()) +#endif + for (amrex::MFIter mfi(tmpmf, TilingIfNotGPU()); mfi.isValid(); ++mfi ) + { + if (cost) + { + amrex::Gpu::synchronize(); + } + auto wt = static_cast(amrex::second()); + + auto const& dstfab = mf.array(mfi); + auto const& srcfab = tmpmf.array(mfi); + + const amrex::Box& outbox = mfi.growntilebox() & adjBox; + + if (outbox.ok()) { + if (!useparser) { + AMREX_PARALLEL_FOR_4D ( outbox, nc, i, j, k, n, + { + srcfab(i,j,k,n) = external_field; + }) + } else { + // index type of the src mf + auto const& mf_IndexType = (tmpmf).ixType(); + amrex::IntVect mf_type(AMREX_D_DECL(0,0,0)); + for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { + mf_type[idim] = mf_IndexType.nodeCentered(idim); + } + + amrex::ParallelFor (outbox, nc, + [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept + { + // Compute x,y,z co-ordinates based on index type of mf +#if defined(WARPX_DIM_1D_Z) + const amrex::Real x = 0.0_rt; + const amrex::Real y = 0.0_rt; + const amrex::Real fac_z = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; + const amrex::Real z = i*dx[0] + real_box.lo(0) + fac_z; +#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) + const amrex::Real fac_x = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; + const amrex::Real x = i*dx[0] + real_box.lo(0) + fac_x; + const amrex::Real y = 0.0; + const amrex::Real fac_z = (1.0_rt - mf_type[1]) * dx[1]*0.5_rt; + const amrex::Real z = j*dx[1] + real_box.lo(1) + fac_z; +#else + const amrex::Real fac_x = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; + const amrex::Real x = i*dx[0] + real_box.lo(0) + fac_x; + const amrex::Real fac_y = (1.0_rt - mf_type[1]) * dx[1]*0.5_rt; + const amrex::Real y = j*dx[1] + real_box.lo(1) + fac_y; + const amrex::Real fac_z = (1.0_rt - mf_type[2]) * dx[2]*0.5_rt; + const amrex::Real z = k*dx[2] + real_box.lo(2) + fac_z; +#endif + srcfab(i,j,k,n) = field_parser(x,y,z); + }); + } + + } + + amrex::Box dstBox = mf[mfi].box(); + if (num_shift > 0) { + dstBox.growHi(dir, -num_shift); + } else { + dstBox.growLo(dir, num_shift); + } + AMREX_PARALLEL_FOR_4D ( dstBox, nc, i, j, k, n, + { + dstfab(i,j,k,n) = srcfab(i+shift.x,j+shift.y,k+shift.z,n); + }) + + if (cost) + { + amrex::Gpu::synchronize(); + wt = static_cast(amrex::second()) - wt; + amrex::HostDevice::Atomic::Add( &(*cost)[mfi.index()], wt); + } + } + +#if (defined WARPX_DIM_RZ) && (defined WARPX_USE_FFT) + if (PMLRZ_flag) { + // This does the exchange of data in the corner guard cells, the cells that are in the + // guard region both radially and longitudinally. These are the PML cells in the overlapping + // longitudinal region. FillBoundary normally does not update these cells. + // This update is needed so that the cells at the end of the FABs are updated appropriately + // with the data shifted from the neighboring FAB. Without this update, the RZ PML becomes + // unstable with the moving grid. + // This code creates a temporary MultiFab using a BoxList where the radial size of all of + // its boxes is increased so that the radial guard cells are included in the boxes valid domain. + // The temporary MultiFab is setup to refer to the data of the original Multifab (this can + // be done since the shape of the data is all the same, just the indexing is different). + amrex::BoxList bl; + const auto ba_size = static_cast(ba.size()); + for (int i = 0; i < ba_size; ++i) { + bl.push_back(amrex::grow(ba[i], 0, mf.nGrowVect()[0])); + } + const amrex::BoxArray rba(std::move(bl)); + amrex::MultiFab rmf(rba, dm, mf.nComp(), IntVect(0,mf.nGrowVect()[1]), MFInfo().SetAlloc(false)); + + for (amrex::MFIter mfi(mf); mfi.isValid(); ++mfi) { + rmf.setFab(mfi, FArrayBox(mf[mfi], amrex::make_alias, 0, mf.nComp())); + } + rmf.FillBoundary(false); + } +#else + amrex::ignore_unused(PMLRZ_flag); +#endif + + } + +} + void WarpX::UpdateInjectionPosition (const amrex::Real a_dt) { @@ -143,6 +336,8 @@ WarpX::MoveWindow (const int step, bool move_j) using ablastr::fields::Direction; using warpx::fields::FieldType; + bool const skip_lev0_coarse_patch = true; + if (step == start_moving_window_step) { amrex::Print() << Utils::TextMsg::Info("Starting moving window"); } @@ -206,9 +401,6 @@ WarpX::MoveWindow (const int step, bool move_j) int num_shift = num_shift_base; int num_shift_crse = num_shift; - constexpr auto do_update_cost = true; - constexpr auto dont_update_cost = false; //We can't update cost for PML - // Shift the mesh fields for (int lev = 0; lev <= finest_level; ++lev) { @@ -217,6 +409,11 @@ WarpX::MoveWindow (const int step, bool move_j) num_shift *= refRatio(lev-1)[dir]; } + auto* cost_lev = + (WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) ? getCosts(lev) : nullptr; + + amrex::LayoutData* no_cost = nullptr ; //We can't update cost for PML + // Shift each component of vector fields (E, B, j) for (int dim = 0; dim < 3; ++dim) { // Fine grid @@ -238,59 +435,60 @@ WarpX::MoveWindow (const int step, bool move_j) if (dim == 1) { Efield_parser = m_p_ext_field_params->Eyfield_parser->compile<3>(); } if (dim == 2) { Efield_parser = m_p_ext_field_params->Ezfield_parser->compile<3>(); } } - shiftMF(*m_fields.get(FieldType::Bfield_fp, Direction{dim}, lev), geom[lev], num_shift, dir, lev, do_update_cost, + ::shiftMF(*m_fields.get(FieldType::Bfield_fp, Direction{dim}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->B_external_grid[dim], use_Bparser, Bfield_parser); - shiftMF(*m_fields.get(FieldType::Efield_fp, Direction{dim}, lev), geom[lev], num_shift, dir, lev, do_update_cost, + ::shiftMF(*m_fields.get(FieldType::Efield_fp, Direction{dim}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->E_external_grid[dim], use_Eparser, Efield_parser); if (fft_do_time_averaging) { ablastr::fields::MultiLevelVectorField Efield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_fp, finest_level); ablastr::fields::MultiLevelVectorField Bfield_avg_fp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_fp, finest_level); - shiftMF(*Bfield_avg_fp[lev][dim], geom[lev], num_shift, dir, lev, do_update_cost, + ::shiftMF(*Bfield_avg_fp[lev][dim], geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->B_external_grid[dim], use_Bparser, Bfield_parser); - shiftMF(*Efield_avg_fp[lev][dim], geom[lev], num_shift, dir, lev, do_update_cost, + ::shiftMF(*Efield_avg_fp[lev][dim], geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params-> E_external_grid[dim], use_Eparser, Efield_parser); } if (move_j) { - shiftMF(*m_fields.get(FieldType::current_fp, Direction{dim}, lev), geom[lev], num_shift, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::current_fp, Direction{dim}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); } if (pml[lev] && pml[lev]->ok()) { amrex::MultiFab* pml_B = m_fields.get(FieldType::pml_B_fp, Direction{dim}, lev); amrex::MultiFab* pml_E = m_fields.get(FieldType::pml_E_fp, Direction{dim}, lev); - shiftMF(*pml_B, geom[lev], num_shift, dir, lev, dont_update_cost); - shiftMF(*pml_E, geom[lev], num_shift, dir, lev, dont_update_cost); + ::shiftMF(*pml_B, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); + ::shiftMF(*pml_E, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } #if (defined WARPX_DIM_RZ) && (defined WARPX_USE_FFT) + const bool PMLRZ_flag = getPMLRZ(); if (pml_rz[lev] && dim < 2) { amrex::MultiFab* pml_rz_B = m_fields.get(FieldType::pml_B_fp, Direction{dim}, lev); amrex::MultiFab* pml_rz_E = m_fields.get(FieldType::pml_E_fp, Direction{dim}, lev); - shiftMF(*pml_rz_B, geom[lev], num_shift, dir, lev, dont_update_cost); - shiftMF(*pml_rz_E, geom[lev], num_shift, dir, lev, dont_update_cost); + ::shiftMF(*pml_rz_B, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost, 0.0_rt, false, amrex::ParserExecutor<3>{}, PMLRZ_flag); + ::shiftMF(*pml_rz_E, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost, 0.0_rt, false, amrex::ParserExecutor<3>{}, PMLRZ_flag); } #endif if (lev > 0) { // coarse grid - shiftMF(*m_fields.get(FieldType::Bfield_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost, + ::shiftMF(*m_fields.get(FieldType::Bfield_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->B_external_grid[dim], use_Bparser, Bfield_parser); - shiftMF(*m_fields.get(FieldType::Efield_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost, + ::shiftMF(*m_fields.get(FieldType::Efield_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->E_external_grid[dim], use_Eparser, Efield_parser); - shiftMF(*m_fields.get(FieldType::Bfield_aux, Direction{dim}, lev), geom[lev], num_shift, dir, lev, do_update_cost); - shiftMF(*m_fields.get(FieldType::Efield_aux, Direction{dim}, lev), geom[lev], num_shift, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::Bfield_aux, Direction{dim}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); + ::shiftMF(*m_fields.get(FieldType::Efield_aux, Direction{dim}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); if (fft_do_time_averaging) { - ablastr::fields::MultiLevelVectorField Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level); - ablastr::fields::MultiLevelVectorField Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level); - shiftMF(*Bfield_avg_cp[lev][dim], geom[lev-1], num_shift_crse, dir, lev, do_update_cost, + ablastr::fields::MultiLevelVectorField Efield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Efield_avg_cp, finest_level, skip_lev0_coarse_patch); + ablastr::fields::MultiLevelVectorField Bfield_avg_cp = m_fields.get_mr_levels_alldirs(FieldType::Bfield_avg_cp, finest_level, skip_lev0_coarse_patch); + ::shiftMF(*Bfield_avg_cp[lev][dim], geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->B_external_grid[dim], use_Bparser, Bfield_parser); - shiftMF(*Efield_avg_cp[lev][dim], geom[lev-1], num_shift_crse, dir, lev, do_update_cost, + ::shiftMF(*Efield_avg_cp[lev][dim], geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev, m_p_ext_field_params->E_external_grid[dim], use_Eparser, Efield_parser); } if (move_j) { - shiftMF(*m_fields.get(FieldType::current_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::current_cp, Direction{dim}, lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); } if (do_pml && pml[lev]->ok()) { amrex::MultiFab* pml_B_cp = m_fields.get(FieldType::pml_B_cp, Direction{dim}, lev); amrex::MultiFab* pml_E_cp = m_fields.get(FieldType::pml_E_cp, Direction{dim}, lev); - shiftMF(*pml_B_cp, geom[lev-1], num_shift_crse, dir, lev, dont_update_cost); - shiftMF(*pml_E_cp, geom[lev-1], num_shift_crse, dir, lev, dont_update_cost); + ::shiftMF(*pml_B_cp, geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); + ::shiftMF(*pml_E_cp, geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } } } @@ -300,11 +498,11 @@ WarpX::MoveWindow (const int step, bool move_j) if (m_fields.has(FieldType::F_fp, lev)) { // Fine grid - shiftMF(*m_fields.get(FieldType::F_fp, lev), geom[lev], num_shift, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::F_fp, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); if (lev > 0) { // Coarse grid - shiftMF(*m_fields.get(FieldType::F_cp, lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::F_cp, lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); } } @@ -315,7 +513,7 @@ WarpX::MoveWindow (const int step, bool move_j) if (do_pml && pml[lev]->ok()) { amrex::MultiFab* pml_F = m_fields.get(FieldType::pml_F_fp, lev); - shiftMF(*pml_F, geom[lev], num_shift, dir, lev, dont_update_cost); + ::shiftMF(*pml_F, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } if (lev > 0) { @@ -323,7 +521,7 @@ WarpX::MoveWindow (const int step, bool move_j) if (do_pml && pml[lev]->ok()) { amrex::MultiFab* pml_F = m_fields.get(FieldType::pml_F_cp, lev); - shiftMF(*pml_F, geom[lev-1], num_shift_crse, dir, lev, dont_update_cost); + ::shiftMF(*pml_F, geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } } } @@ -333,11 +531,11 @@ WarpX::MoveWindow (const int step, bool move_j) if (m_fields.has(FieldType::G_fp, lev)) { // Fine grid - shiftMF(*m_fields.get(FieldType::G_fp, lev), geom[lev], num_shift, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::G_fp, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); if (lev > 0) { // Coarse grid - shiftMF(*m_fields.get(FieldType::G_cp, lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::G_cp, lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); } } @@ -348,7 +546,7 @@ WarpX::MoveWindow (const int step, bool move_j) if (do_pml && pml[lev]->ok()) { amrex::MultiFab* pml_G = m_fields.get(FieldType::pml_G_fp, lev); - shiftMF(*pml_G, geom[lev], num_shift, dir, lev, dont_update_cost); + ::shiftMF(*pml_G, geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } if (lev > 0) { @@ -356,7 +554,7 @@ WarpX::MoveWindow (const int step, bool move_j) if (do_pml && pml[lev]->ok()) { amrex::MultiFab* pml_G = m_fields.get(FieldType::pml_G_cp, lev); - shiftMF(*pml_G, geom[lev-1], num_shift_crse, dir, lev, dont_update_cost); + ::shiftMF(*pml_G, geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, no_cost); } } } @@ -365,10 +563,10 @@ WarpX::MoveWindow (const int step, bool move_j) if (move_j) { if (m_fields.has(FieldType::rho_fp, lev)) { // Fine grid - shiftMF(*m_fields.get(FieldType::rho_fp,lev), geom[lev], num_shift, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::rho_fp,lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); if (lev > 0){ // Coarse grid - shiftMF(*m_fields.get(FieldType::rho_cp,lev), geom[lev-1], num_shift_crse, dir, lev, do_update_cost); + ::shiftMF(*m_fields.get(FieldType::rho_cp,lev), geom[lev-1], num_shift_crse, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev); } } } @@ -378,10 +576,10 @@ WarpX::MoveWindow (const int step, bool move_j) const int n_fluid_species = myfl->nSpecies(); for (int i=0; iGetFluidContainer(i); - shiftMF( *m_fields.get(fl.name_mf_N, lev), geom[lev], num_shift, dir, lev, do_update_cost ); - shiftMF( *m_fields.get(fl.name_mf_NU, Direction{0}, lev), geom[lev], num_shift, dir, lev, do_update_cost ); - shiftMF( *m_fields.get(fl.name_mf_NU, Direction{1}, lev), geom[lev], num_shift, dir, lev, do_update_cost ); - shiftMF( *m_fields.get(fl.name_mf_NU, Direction{2}, lev), geom[lev], num_shift, dir, lev, do_update_cost ); + ::shiftMF( *m_fields.get(fl.name_mf_N, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev ); + ::shiftMF( *m_fields.get(fl.name_mf_NU, Direction{0}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev ); + ::shiftMF( *m_fields.get(fl.name_mf_NU, Direction{1}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev ); + ::shiftMF( *m_fields.get(fl.name_mf_NU, Direction{2}, lev), geom[lev], num_shift, dir, m_safe_guard_cells, do_single_precision_comms, cost_lev ); } } } @@ -462,7 +660,7 @@ WarpX::MoveWindow (const int step, bool move_j) } // Recompute macroscopic properties of the medium - if (WarpX::em_solver_medium == MediumForEM::Macroscopic) { + if (m_em_solver_medium == MediumForEM::Macroscopic) { const int lev_zero = 0; m_macroscopic_properties->InitData( Geom(lev_zero), @@ -475,178 +673,6 @@ WarpX::MoveWindow (const int step, bool move_j) return num_shift_base; } -void -WarpX::shiftMF (amrex::MultiFab& mf, const amrex::Geometry& geom, - int num_shift, int dir, const int lev, bool update_cost_flag, - amrex::Real external_field, bool useparser, - amrex::ParserExecutor<3> const& field_parser) -{ - using namespace amrex::literals; - WARPX_PROFILE("WarpX::shiftMF()"); - const amrex::BoxArray& ba = mf.boxArray(); - const amrex::DistributionMapping& dm = mf.DistributionMap(); - const int nc = mf.nComp(); - const amrex::IntVect& ng = mf.nGrowVect(); - - AMREX_ALWAYS_ASSERT(ng[dir] >= num_shift); - - amrex::MultiFab tmpmf(ba, dm, nc, ng); - amrex::MultiFab::Copy(tmpmf, mf, 0, 0, nc, ng); - - if ( WarpX::safe_guard_cells ) { - // Fill guard cells. - ablastr::utils::communication::FillBoundary(tmpmf, WarpX::do_single_precision_comms, geom.periodicity()); - } else { - amrex::IntVect ng_mw = amrex::IntVect::TheUnitVector(); - // Enough guard cells in the MW direction - ng_mw[dir] = num_shift; - // Make sure we don't exceed number of guard cells allocated - ng_mw = ng_mw.min(ng); - // Fill guard cells. - ablastr::utils::communication::FillBoundary(tmpmf, ng_mw, WarpX::do_single_precision_comms, geom.periodicity()); - } - - // Make a box that covers the region that the window moved into - const amrex::IndexType& typ = ba.ixType(); - const amrex::Box& domainBox = geom.Domain(); - amrex::Box adjBox; - if (num_shift > 0) { - adjBox = adjCellHi(domainBox, dir, ng[dir]); - } else { - adjBox = adjCellLo(domainBox, dir, ng[dir]); - } - adjBox = amrex::convert(adjBox, typ); - - for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { - if (idim == dir and typ.nodeCentered(dir)) { - if (num_shift > 0) { - adjBox.growLo(idim, -1); - } else { - adjBox.growHi(idim, -1); - } - } else if (idim != dir) { - adjBox.growLo(idim, ng[idim]); - adjBox.growHi(idim, ng[idim]); - } - } - - amrex::IntVect shiftiv(0); - shiftiv[dir] = num_shift; - const amrex::Dim3 shift = shiftiv.dim3(); - - const amrex::RealBox& real_box = geom.ProbDomain(); - const auto dx = geom.CellSizeArray(); - - amrex::LayoutData* cost = WarpX::getCosts(lev); -#ifdef AMREX_USE_OMP -#pragma omp parallel if (Gpu::notInLaunchRegion()) -#endif - - for (amrex::MFIter mfi(tmpmf, TilingIfNotGPU()); mfi.isValid(); ++mfi ) - { - if (cost && WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) - { - amrex::Gpu::synchronize(); - } - auto wt = static_cast(amrex::second()); - - auto const& dstfab = mf.array(mfi); - auto const& srcfab = tmpmf.array(mfi); - - const amrex::Box& outbox = mfi.growntilebox() & adjBox; - - if (outbox.ok()) { - if (!useparser) { - AMREX_PARALLEL_FOR_4D ( outbox, nc, i, j, k, n, - { - srcfab(i,j,k,n) = external_field; - }) - } else { - // index type of the src mf - auto const& mf_IndexType = (tmpmf).ixType(); - amrex::IntVect mf_type(AMREX_D_DECL(0,0,0)); - for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { - mf_type[idim] = mf_IndexType.nodeCentered(idim); - } - - amrex::ParallelFor (outbox, nc, - [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept - { - // Compute x,y,z co-ordinates based on index type of mf -#if defined(WARPX_DIM_1D_Z) - const amrex::Real x = 0.0_rt; - const amrex::Real y = 0.0_rt; - const amrex::Real fac_z = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; - const amrex::Real z = i*dx[0] + real_box.lo(0) + fac_z; -#elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - const amrex::Real fac_x = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; - const amrex::Real x = i*dx[0] + real_box.lo(0) + fac_x; - const amrex::Real y = 0.0; - const amrex::Real fac_z = (1.0_rt - mf_type[1]) * dx[1]*0.5_rt; - const amrex::Real z = j*dx[1] + real_box.lo(1) + fac_z; -#else - const amrex::Real fac_x = (1.0_rt - mf_type[0]) * dx[0]*0.5_rt; - const amrex::Real x = i*dx[0] + real_box.lo(0) + fac_x; - const amrex::Real fac_y = (1.0_rt - mf_type[1]) * dx[1]*0.5_rt; - const amrex::Real y = j*dx[1] + real_box.lo(1) + fac_y; - const amrex::Real fac_z = (1.0_rt - mf_type[2]) * dx[2]*0.5_rt; - const amrex::Real z = k*dx[2] + real_box.lo(2) + fac_z; -#endif - srcfab(i,j,k,n) = field_parser(x,y,z); - }); - } - - } - - amrex::Box dstBox = mf[mfi].box(); - if (num_shift > 0) { - dstBox.growHi(dir, -num_shift); - } else { - dstBox.growLo(dir, num_shift); - } - AMREX_PARALLEL_FOR_4D ( dstBox, nc, i, j, k, n, - { - dstfab(i,j,k,n) = srcfab(i+shift.x,j+shift.y,k+shift.z,n); - }) - - if (cost && update_cost_flag && - WarpX::load_balance_costs_update_algo == LoadBalanceCostsUpdateAlgo::Timers) - { - amrex::Gpu::synchronize(); - wt = static_cast(amrex::second()) - wt; - amrex::HostDevice::Atomic::Add( &(*cost)[mfi.index()], wt); - } - } - -#if (defined WARPX_DIM_RZ) && (defined WARPX_USE_FFT) - if (WarpX::GetInstance().getPMLRZ()) { - // This does the exchange of data in the corner guard cells, the cells that are in the - // guard region both radially and longitudinally. These are the PML cells in the overlapping - // longitudinal region. FillBoundary normally does not update these cells. - // This update is needed so that the cells at the end of the FABs are updated appropriately - // with the data shifted from the neighboring FAB. Without this update, the RZ PML becomes - // unstable with the moving grid. - // This code creates a temporary MultiFab using a BoxList where the radial size of all of - // its boxes is increased so that the radial guard cells are included in the boxes valid domain. - // The temporary MultiFab is setup to refer to the data of the original Multifab (this can - // be done since the shape of the data is all the same, just the indexing is different). - amrex::BoxList bl; - const auto ba_size = static_cast(ba.size()); - for (int i = 0; i < ba_size; ++i) { - bl.push_back(amrex::grow(ba[i], 0, mf.nGrowVect()[0])); - } - const amrex::BoxArray rba(std::move(bl)); - amrex::MultiFab rmf(rba, dm, mf.nComp(), IntVect(0,mf.nGrowVect()[1]), MFInfo().SetAlloc(false)); - - for (amrex::MFIter mfi(mf); mfi.isValid(); ++mfi) { - rmf.setFab(mfi, FArrayBox(mf[mfi], amrex::make_alias, 0, mf.nComp())); - } - rmf.FillBoundary(false); - } -#endif - -} - void WarpX::ShiftGalileanBoundary () { diff --git a/Source/Utils/WarpXUtil.H b/Source/Utils/WarpXUtil.H index 46399b439d6..f76db974f9d 100644 --- a/Source/Utils/WarpXUtil.H +++ b/Source/Utils/WarpXUtil.H @@ -28,8 +28,6 @@ #include #include -void ParseGeometryInput(); - void ReadBoostedFrameParameters(amrex::Real& gamma_boost, amrex::Real& beta_boost, amrex::Vector& boost_direction); @@ -44,10 +42,6 @@ void ConvertLabParamsToBoost(); */ void ReadBCParams (); -/** Check the warpx.dims matches the binary name - */ -void CheckDims (); - /** Check the warpx.dims matches the binary name & set up RZ gridding * * Ensures that the blocks are setup correctly for the RZ spectral solver @@ -118,44 +112,6 @@ bool WriteBinaryDataOnFile(const std::string& filename, const amrex::Vector const mf_type, - amrex::GpuArray const domain_lo, - amrex::GpuArray const dx, - amrex::Real &x, amrex::Real &y, amrex::Real &z) -{ - using namespace amrex::literals; - x = domain_lo[0] + i*dx[0] + (1._rt - mf_type[0]) * dx[0]*0.5_rt; -#if defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) - amrex::ignore_unused(j); - y = 0._rt; - z = domain_lo[1] + k*dx[1] + (1._rt - mf_type[1]) * dx[1]*0.5_rt; -#else - y = domain_lo[1] + j*dx[1] + (1._rt - mf_type[1]) * dx[1]*0.5_rt; - z = domain_lo[2] + k*dx[2] + (1._rt - mf_type[2]) * dx[2]*0.5_rt; -#endif -} - -} - - namespace WarpXUtilLoadBalance { /** \brief We only want to update the cost data if the grids we are working on diff --git a/Source/Utils/WarpXUtil.cpp b/Source/Utils/WarpXUtil.cpp index d6f465fa901..ae2adfac043 100644 --- a/Source/Utils/WarpXUtil.cpp +++ b/Source/Utils/WarpXUtil.cpp @@ -43,74 +43,6 @@ using namespace amrex; -void PreparseAMReXInputIntArray(amrex::ParmParse& a_pp, char const * const input_str, const bool replace) -{ - const int cnt = a_pp.countval(input_str); - if (cnt > 0) { - Vector input_array; - utils::parser::getArrWithParser(a_pp, input_str, input_array); - if (replace) { - a_pp.remove(input_str); - } - a_pp.addarr(input_str, input_array); - } -} - -void ParseGeometryInput() -{ - // Ensure that geometry.dims is set properly. - CheckDims(); - - // Parse prob_lo and hi, evaluating any expressions since geometry does not - // parse its input - ParmParse pp_geometry("geometry"); - - Vector prob_lo(AMREX_SPACEDIM); - Vector prob_hi(AMREX_SPACEDIM); - - utils::parser::getArrWithParser( - pp_geometry, "prob_lo", prob_lo, 0, AMREX_SPACEDIM); - AMREX_ALWAYS_ASSERT(prob_lo.size() == AMREX_SPACEDIM); - utils::parser::getArrWithParser( - pp_geometry, "prob_hi", prob_hi, 0, AMREX_SPACEDIM); - AMREX_ALWAYS_ASSERT(prob_hi.size() == AMREX_SPACEDIM); - -#ifdef WARPX_DIM_RZ - const ParmParse pp_algo("algo"); - auto electromagnetic_solver_id = ElectromagneticSolverAlgo::Default; - pp_algo.query_enum_sloppy("maxwell_solver", electromagnetic_solver_id, "-_"); - if (electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD) - { - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(prob_lo[0] == 0., - "Lower bound of radial coordinate (prob_lo[0]) with RZ PSATD solver must be zero"); - } - else - { - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(prob_lo[0] >= 0., - "Lower bound of radial coordinate (prob_lo[0]) with RZ FDTD solver must be non-negative"); - } -#endif - - pp_geometry.addarr("prob_lo", prob_lo); - pp_geometry.addarr("prob_hi", prob_hi); - - // Parse amr input, evaluating any expressions since amr does not parse its input - ParmParse pp_amr("amr"); - - // Note that n_cell is replaced so that only the parsed version is written out to the - // warpx_job_info file. This must be done since yt expects to be able to parse - // the value of n_cell from that file. For the rest, this doesn't matter. - PreparseAMReXInputIntArray(pp_amr, "n_cell", true); - PreparseAMReXInputIntArray(pp_amr, "max_grid_size", false); - PreparseAMReXInputIntArray(pp_amr, "max_grid_size_x", false); - PreparseAMReXInputIntArray(pp_amr, "max_grid_size_y", false); - PreparseAMReXInputIntArray(pp_amr, "max_grid_size_z", false); - PreparseAMReXInputIntArray(pp_amr, "blocking_factor", false); - PreparseAMReXInputIntArray(pp_amr, "blocking_factor_x", false); - PreparseAMReXInputIntArray(pp_amr, "blocking_factor_y", false); - PreparseAMReXInputIntArray(pp_amr, "blocking_factor_z", false); -} - void ReadBoostedFrameParameters(Real& gamma_boost, Real& beta_boost, Vector& boost_direction) { @@ -352,40 +284,9 @@ namespace WarpXUtilIO{ } } -void CheckDims () -{ - // Ensure that geometry.dims is set properly. -#if defined(WARPX_DIM_3D) - std::string const dims_compiled = "3"; -#elif defined(WARPX_DIM_XZ) - std::string const dims_compiled = "2"; -#elif defined(WARPX_DIM_1D_Z) - std::string const dims_compiled = "1"; -#elif defined(WARPX_DIM_RZ) - std::string const dims_compiled = "RZ"; -#endif - const ParmParse pp_geometry("geometry"); - std::string dims; - std::string dims_error = "The selected WarpX executable was built as '"; - dims_error.append(dims_compiled).append("'-dimensional, but the "); - if (pp_geometry.contains("dims")) { - pp_geometry.get("dims", dims); - dims_error.append("inputs file declares 'geometry.dims = ").append(dims).append("'.\n"); - dims_error.append("Please re-compile with a different WarpX_DIMS option or select the right executable name."); - } else { - dims = "Not specified"; - dims_error.append("inputs file does not declare 'geometry.dims'. Please add 'geometry.dims = "); - dims_error.append(dims_compiled).append("' to inputs file."); - } - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(dims == dims_compiled, dims_error); -} - void CheckGriddingForRZSpectral () { #ifdef WARPX_DIM_RZ - // Ensure that geometry.dims is set properly. - CheckDims(); - const ParmParse pp_algo("algo"); auto electromagnetic_solver_id = ElectromagneticSolverAlgo::Default; pp_algo.query_enum_sloppy("maxwell_solver", electromagnetic_solver_id, "-_"); @@ -542,6 +443,15 @@ void ReadBCParams () "PEC boundary not implemented for PSATD, yet!" ); + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + (electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD) || + ( + WarpX::field_boundary_lo[idim] != FieldBoundaryType::PMC && + WarpX::field_boundary_hi[idim] != FieldBoundaryType::PMC + ), + "PMC boundary not implemented for PSATD, yet!" + ); + if(WarpX::field_boundary_lo[idim] == FieldBoundaryType::Open && WarpX::field_boundary_hi[idim] == FieldBoundaryType::Open){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( diff --git a/Source/WarpX.H b/Source/WarpX.H index bad63cd44d9..4f6024d426d 100644 --- a/Source/WarpX.H +++ b/Source/WarpX.H @@ -12,6 +12,7 @@ #ifndef WARPX_H_ #define WARPX_H_ +#include "BoundaryConditions/PEC_Insulator_fwd.H" #include "BoundaryConditions/PML_fwd.H" #include "Diagnostics/MultiDiagnostics_fwd.H" #include "Diagnostics/ReducedDiags/MultiReducedDiags_fwd.H" @@ -113,6 +114,16 @@ public: [[nodiscard]] int Verbose () const { return verbose; } + [[nodiscard]] const amrex::Array& GetFieldBoundaryLo () const + { + return field_boundary_lo; + } + + [[nodiscard]] const amrex::Array& GetFieldBoundaryHi () const + { + return field_boundary_hi; + } + void InitData (); void Evolve (int numsteps = -1); @@ -125,44 +136,34 @@ public: // // Functions used by implicit solvers // - void ImplicitPreRHSOp ( amrex::Real cur_time, - amrex::Real a_full_dt, - int a_nl_iter, - bool a_from_jacobian ); + void ImplicitPreRHSOp ( amrex::Real cur_time, + amrex::Real a_full_dt, + int a_nl_iter, + bool a_from_jacobian ); void SaveParticlesAtImplicitStepStart (); void FinishImplicitParticleUpdate (); - void SetElectricFieldAndApplyBCs ( const WarpXSolverVec& a_E ); - void UpdateMagneticFieldAndApplyBCs ( ablastr::fields::MultiLevelVectorField const& a_Bn, - amrex::Real a_thetadt ); - void ApplyMagneticFieldBCs (); - void FinishMagneticFieldAndApplyBCs ( ablastr::fields::MultiLevelVectorField const& a_Bn, - amrex::Real a_theta ); - void FinishImplicitField ( const ablastr::fields::MultiLevelVectorField& Field_fp, - const ablastr::fields::MultiLevelVectorField& Field_n, - amrex::Real theta ); + void SetElectricFieldAndApplyBCs ( const WarpXSolverVec& a_E, amrex::Real a_time ); + void UpdateMagneticFieldAndApplyBCs ( ablastr::fields::MultiLevelVectorField const& a_Bn, + amrex::Real a_thetadt, amrex::Real start_time ); + void SpectralSourceFreeFieldAdvance ( amrex::Real start_time); + void FinishMagneticFieldAndApplyBCs ( ablastr::fields::MultiLevelVectorField const& a_Bn, + amrex::Real a_theta, amrex::Real a_time ); + void FinishImplicitField ( const ablastr::fields::MultiLevelVectorField& Field_fp, + const ablastr::fields::MultiLevelVectorField& Field_n, + amrex::Real theta ); void ImplicitComputeRHSE ( amrex::Real dt, WarpXSolverVec& a_Erhs_vec); void ImplicitComputeRHSE (int lev, amrex::Real dt, WarpXSolverVec& a_Erhs_vec); void ImplicitComputeRHSE (int lev, PatchType patch_type, amrex::Real dt, WarpXSolverVec& a_Erhs_vec); MultiParticleContainer& GetPartContainer () { return *mypc; } MultiFluidContainer& GetFluidContainer () { return *myfl; } - MacroscopicProperties& GetMacroscopicProperties () { return *m_macroscopic_properties; } ElectrostaticSolver& GetElectrostaticSolver () {return *m_electrostatic_solver;} - HybridPICModel& GetHybridPICModel () { return *m_hybrid_pic_model; } [[nodiscard]] HybridPICModel * get_pointer_HybridPICModel () const { return m_hybrid_pic_model.get(); } MultiDiagnostics& GetMultiDiags () {return *multi_diags;} -#ifdef AMREX_USE_EB - ablastr::fields::MultiLevelScalarField GetDistanceToEB () { - using warpx::fields::FieldType; - return m_fields.get_mr_levels(FieldType::distance_to_eb, finestLevel()); - } -#endif ParticleBoundaryBuffer& GetParticleBoundaryBuffer () { return *m_particle_boundary_buffer; } - - static void shiftMF (amrex::MultiFab& mf, const amrex::Geometry& geom, - int num_shift, int dir, int lev, bool update_cost_flag, - amrex::Real external_field=0.0, bool useparser = false, - amrex::ParserExecutor<3> const& field_parser={}); + amrex::Vector,3 > >& GetEBUpdateEFlag() { return m_eb_update_E; } + amrex::Vector,3 > >& GetEBUpdateBFlag() { return m_eb_update_B; } + amrex::Vector< std::unique_ptr > const & GetEBReduceParticleShapeFlag() const { return m_eb_reduce_particle_shape; } /** * \brief @@ -189,7 +190,7 @@ public: //! Integer that corresponds to the type of Maxwell solver (Yee, CKC, PSATD, ECT) static inline auto electromagnetic_solver_id = ElectromagneticSolverAlgo::Default; //! Integer that corresponds to the evolve scheme (explicit, semi_implicit_em, theta_implicit_em) - static inline auto evolve_scheme = EvolveScheme::Default; + EvolveScheme evolve_scheme = EvolveScheme::Default; //! Maximum iterations used for self-consistent particle update in implicit particle-suppressed evolve schemes static int max_particle_its_in_implicit_scheme; //! Relative tolerance used for self-consistent particle update in implicit particle-suppressed evolve schemes @@ -198,23 +199,19 @@ public: * being used (0 or 1 corresponding to timers or heuristic). */ static inline auto load_balance_costs_update_algo = LoadBalanceCostsUpdateAlgo::Default; - //! Integer that corresponds to electromagnetic Maxwell solver (vacuum - 0, macroscopic - 1) - static inline auto em_solver_medium = MediumForEM::Default; /** Integer that correspond to macroscopic Maxwell solver algorithm * (BackwardEuler - 0, Lax-Wendroff - 1) */ static inline auto macroscopic_solver_algo = MacroscopicSolverAlgo::Default; - /** Integers that correspond to boundary condition applied to fields at the - * lower domain boundaries - * (0 to 6 correspond to PML, Periodic, PEC, PMC, Damped, Absorbing Silver-Mueller, None) + /** Boundary conditions applied to fields at the lower domain boundaries + * (Possible values PML, Periodic, PEC, PMC, Neumann, Damped, Absorbing Silver-Mueller, None) */ static inline amrex::Array field_boundary_lo {AMREX_D_DECL(FieldBoundaryType::Default, FieldBoundaryType::Default, FieldBoundaryType::Default)}; - /** Integers that correspond to boundary condition applied to fields at the - * upper domain boundaries - * (0 to 6 correspond to PML, Periodic, PEC, PMC, Damped, Absorbing Silver-Mueller, None) + /** Boundary conditions applied to fields at the upper domain boundaries + * (Possible values PML, Periodic, PEC, PMC, Neumann, Damped, Absorbing Silver-Mueller, None) */ static inline amrex::Array field_boundary_hi {AMREX_D_DECL(FieldBoundaryType::Default, @@ -237,11 +234,6 @@ public: ParticleBoundaryType::Default, ParticleBoundaryType::Default)}; - //! Integer that corresponds to the order of the PSATD solution - //! (whether the PSATD equations are derived from first-order or - //! second-order solution) - static inline auto psatd_solution_type = PSATDSolutionType::Default; - //! Integers that correspond to the time dependency of J (constant, linear) //! and rho (linear, quadratic) for the PSATD algorithm static inline auto J_in_time = JInTime::Default; @@ -287,10 +279,6 @@ public: //! Solve additional Maxwell equation for G in order to control errors in magnetic Gauss' law static bool do_divb_cleaning; - //! Solve Poisson equation when loading an external magnetic field to clean divergence - //! This is useful to remove errors that could lead to non-zero B field divergence - static bool do_divb_cleaning_external; - //! Order of the particle shape factors (splines) along x static int nox; //! Order of the particle shape factors (splines) along y @@ -334,10 +322,6 @@ public: //! small time steps. static bool galerkin_interpolation; - //! Flag whether the Verboncoeur correction is applied to the current and charge density - //! on the axis when using RZ. - static bool verboncoeur_axis_correction; - //! If true, a bilinear filter is used to smooth charge and currents static bool use_filter; //! If true, the bilinear filtering of charge and currents is done in Fourier space @@ -354,14 +338,7 @@ public: static amrex::Real beta_boost; //! Direction of the Lorentz transform that defines the boosted frame of the simulation static amrex::Vector boost_direction; - //! If specified, the maximum number of iterations is computed automatically so that - //! the lower end of the simulation domain along z reaches #zmax_plasma_to_compute_max_step - //! in the boosted frame - static amrex::Real zmax_plasma_to_compute_max_step; - //! Set to true if #zmax_plasma_to_compute_max_step is specified, in which case - //! the maximum number of iterations is computed automatically so that the lower end of the - //! simulation domain along z reaches #zmax_plasma_to_compute_max_step in the boosted frame - static bool do_compute_max_step_from_zmax; + //! store initial value of zmin_domain_boost because WarpX::computeMaxStepBoostAccelerator //! needs the initial value of zmin_domain_boost, even if restarting from a checkpoint file static amrex::Real zmin_domain_boost_step_0; @@ -380,13 +357,9 @@ public: //! Specifies the type of grid used for the above sorting, i.e. cell-centered, nodal, or mixed static amrex::IntVect sort_idx_type; - static bool do_subcycling; static bool do_multi_J; static int do_multi_J_n_depositions; - static bool do_device_synchronize; - static bool safe_guard_cells; - //! With mesh refinement, particles located inside a refinement patch, but within //! #n_field_gather_buffer cells of the edge of the patch, will gather the fields //! from the lower refinement level instead of the refinement patch itself @@ -418,7 +391,7 @@ public: * \param[in] name The name of the iMultiFab to use in the map * \param[in] initial_value The optional initial value */ - static void AllocInitMultiFab ( + void AllocInitMultiFab ( std::unique_ptr& mf, const amrex::BoxArray& ba, const amrex::DistributionMapping& dm, @@ -431,21 +404,14 @@ public: // Maps of all of the iMultiFabs used (this can include MFs from other classes) // This is a convenience for the Python interface, allowing all iMultiFabs // to be easily referenced from Python. - static std::map imultifab_map; + std::map imultifab_map; /** * \brief * Get pointer to the amrex::MultiFab containing the dotMask for the specified field */ [[nodiscard]] const amrex::iMultiFab* - getFieldDotMaskPointer (warpx::fields::FieldType field_type, int lev, int dir) const; - - /** - * \brief - * Set the dotMask container - */ - void SetDotMask( std::unique_ptr& field_dotMask, - std::string const & field_name, int lev, int dir ) const; + getFieldDotMaskPointer (warpx::fields::FieldType field_type, int lev, ablastr::fields::Direction dir) const; [[nodiscard]] bool DoPML () const {return do_pml;} [[nodiscard]] bool DoFluidSpecies () const {return do_fluid_species;} @@ -474,11 +440,6 @@ public: amrex::Vector m_v_comoving = amrex::Vector(3, amrex::Real(0.)); - static int num_mirrors; - amrex::Vector mirror_z; - amrex::Vector mirror_z_width; - amrex::Vector mirror_z_npoints; - /// object with all reduced diagnostics, similar to MultiParticleContainer for species. std::unique_ptr reduced_diags; @@ -499,9 +460,6 @@ public: /** Write a file that record all inputs: inputs file + command line options */ void WriteUsedInputsFile () const; - /** Print dt and dx,dy,dz */ - void PrintDtDxDyDz (); - /** * \brief * Compute the last time step of the simulation @@ -531,22 +489,22 @@ public: void UpdateInjectionPosition (amrex::Real dt); void ResetProbDomain (const amrex::RealBox& rb); - void EvolveE ( amrex::Real dt); - void EvolveE (int lev, amrex::Real dt); - void EvolveB ( amrex::Real dt, DtType dt_type); - void EvolveB (int lev, amrex::Real dt, DtType dt_type); + void EvolveE ( amrex::Real dt, amrex::Real start_time); + void EvolveE (int lev, amrex::Real dt, amrex::Real start_time); + void EvolveB ( amrex::Real dt, DtType dt_type, amrex::Real start_time); + void EvolveB (int lev, amrex::Real dt, DtType dt_type, amrex::Real start_time); void EvolveF ( amrex::Real dt, DtType dt_type); void EvolveF (int lev, amrex::Real dt, DtType dt_type); void EvolveG ( amrex::Real dt, DtType dt_type); void EvolveG (int lev, amrex::Real dt, DtType dt_type); - void EvolveB (int lev, PatchType patch_type, amrex::Real dt, DtType dt_type); - void EvolveE (int lev, PatchType patch_type, amrex::Real dt); + void EvolveB (int lev, PatchType patch_type, amrex::Real dt, DtType dt_type, amrex::Real start_time); + void EvolveE (int lev, PatchType patch_type, amrex::Real dt, amrex::Real start_time); void EvolveF (int lev, PatchType patch_type, amrex::Real dt, DtType dt_type); void EvolveG (int lev, PatchType patch_type, amrex::Real dt, DtType dt_type); - void MacroscopicEvolveE ( amrex::Real dt); - void MacroscopicEvolveE (int lev, amrex::Real dt); - void MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real dt); + void MacroscopicEvolveE ( amrex::Real dt, amrex::Real start_time); + void MacroscopicEvolveE (int lev, amrex::Real dt, amrex::Real start_time); + void MacroscopicEvolveE (int lev, PatchType patch_type, amrex::Real dt, amrex::Real start_time); /** * \brief Hybrid-PIC field evolve function. @@ -638,10 +596,10 @@ public: void ApplyInverseVolumeScalingToCurrentDensity(amrex::MultiFab* Jx, amrex::MultiFab* Jy, amrex::MultiFab* Jz, - int lev); + int lev) const; void ApplyInverseVolumeScalingToChargeDensity(amrex::MultiFab* Rho, - int lev); + int lev) const; #endif /** @@ -661,8 +619,8 @@ public: amrex::MultiFab* Jy, amrex::MultiFab* Jz, PatchType patch_type); - void ApplyEfieldBoundary (int lev, PatchType patch_type); - void ApplyBfieldBoundary (int lev, PatchType patch_type, DtType dt_type); + void ApplyEfieldBoundary (int lev, PatchType patch_type, amrex::Real cur_time); + void ApplyBfieldBoundary (int lev, PatchType patch_type, DtType dt_type, amrex::Real cur_time); #ifdef WARPX_DIM_RZ // Applies the boundary conditions that are specific to the axis when in RZ. @@ -700,18 +658,10 @@ public: /** Run the ionization module on all species */ void doFieldIonization (); - /** Run the ionization module on all species at level lev - * \param lev level - */ - void doFieldIonization (int lev); #ifdef WARPX_QED /** Run the QED module on all species */ void doQEDEvents (); - /** Run the QED module on all species at level lev - * \param lev level - */ - void doQEDEvents (int lev); #endif void PushParticlesandDeposit (int lev, amrex::Real cur_time, DtType a_dt_type=DtType::Full, bool skip_current=false, @@ -801,14 +751,6 @@ public: [[nodiscard]] amrex::Real stopTime () const {return stop_time;} void updateStopTime (const amrex::Real new_stop_time) {stop_time = new_stop_time;} - void AverageAndPackFields( amrex::Vector& varnames, - amrex::Vector& mf_avg, amrex::IntVect ngrow) const; - - void prepareFields( int step, amrex::Vector& varnames, - amrex::Vector& mf_avg, - amrex::Vector& output_mf, - amrex::Vector& output_geom ) const; - static std::array CellSize (int lev); static amrex::XDim3 InvCellSize (int lev); static amrex::RealBox getRealBox(const amrex::Box& bx, int lev); @@ -868,7 +810,8 @@ public: void ComputeDivE(amrex::MultiFab& divE, int lev); - static void ProjectionCleanDivB (); + void ProjectionCleanDivB (); + void CalculateExternalCurlA (); [[nodiscard]] amrex::IntVect getngEB() const { return guard_cells.ng_alloc_EB; } [[nodiscard]] amrex::IntVect getngF() const { return guard_cells.ng_alloc_F; } @@ -891,6 +834,8 @@ public: // Magnetostatic Solver Interface MagnetostaticSolver::VectorPoissonBoundaryHandler m_vector_poisson_boundary_handler; + int magnetostatic_solver_max_iters = 200; + int magnetostatic_solver_verbosity = 2; void ComputeMagnetostaticField (); void AddMagnetostaticFieldLabFrame (); void computeVectorPotential (ablastr::fields::MultiLevelVectorField const& curr, @@ -911,7 +856,42 @@ public: * on the staggered yee-grid or cell-centered grid, in the interior cells * and guard cells. * - * \param[in] field FieldType + * \param[in] field FieldType to grab from register to write into + * \param[in] fx_parser parser function to initialize x-field + * \param[in] fy_parser parser function to initialize y-field + * \param[in] fz_parser parser function to initialize z-field + * \param[in] lev level of the Multifabs that is initialized + * \param[in] patch_type PatchType on which the field is initialized (fine or coarse) + * \param[in] eb_update_field flag indicating which gridpoints should be modified by this functions + * \param[in] use_eb_flags (default:true) flag indicating if eb points should be excluded or not + */ + void ComputeExternalFieldOnGridUsingParser ( + warpx::fields::FieldType field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field, + bool use_eb_flags); + + void ComputeExternalFieldOnGridUsingParser ( + warpx::fields::FieldType field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector,3 > > const& eb_update_field); + + /** + * \brief + * This function computes the E, B, and J fields on each level + * using the parser and the user-defined function for the external fields. + * The subroutine will parse the x_/y_z_external_grid_function and + * then, the field multifab is initialized based on the (x,y,z) position + * on the staggered yee-grid or cell-centered grid, in the interior cells + * and guard cells. + * + * \param[in] field string containing field name to grab from register * \param[in] fx_parser parser function to initialize x-field * \param[in] fy_parser parser function to initialize y-field * \param[in] fz_parser parser function to initialize z-field @@ -920,15 +900,25 @@ public: * \param[in] topology flag indicating if field is edge-based or face-based * \param[in] lev level of the Multifabs that is initialized * \param[in] patch_type PatchType on which the field is initialized (fine or coarse) + * \param[in] eb_update_field flag indicating which gridpoints should be modified by this functions + * \param[in] use_eb_flags (default:true) flag indicating if eb points should be excluded or not */ void ComputeExternalFieldOnGridUsingParser ( - warpx::fields::FieldType field, + std::string const& field, amrex::ParserExecutor<4> const& fx_parser, amrex::ParserExecutor<4> const& fy_parser, amrex::ParserExecutor<4> const& fz_parser, - int lev, PatchType patch_type, [[maybe_unused]] char topology, - std::optional const& edge_lengths = std::nullopt, - std::optional const& face_areas = std::nullopt); + int lev, PatchType patch_type, + amrex::Vector< std::array< std::unique_ptr,3> > const& eb_update_field, + bool use_eb_flags); + + void ComputeExternalFieldOnGridUsingParser ( + std::string const& field, + amrex::ParserExecutor<4> const& fx_parser, + amrex::ParserExecutor<4> const& fy_parser, + amrex::ParserExecutor<4> const& fz_parser, + int lev, PatchType patch_type, + amrex::Vector< std::array< std::unique_ptr,3> > const& eb_update_field); /** * \brief Load field values from a user-specified openPMD file, @@ -963,16 +953,6 @@ public: void ApplyFilterandSumBoundaryRho (int lev, int glev, amrex::MultiFab& rho, int icomp, int ncomp); - /** - * \brief Returns an array of coefficients (Fornberg coefficients), corresponding - * to the weight of each point in a finite-difference approximation of a derivative - * (up to order \c n_order). - * - * \param[in] n_order order of the finite-difference approximation - * \param[in] a_grid_type type of grid (collocated or not) - */ - static amrex::Vector getFornbergStencilCoefficients (int n_order, ablastr::utils::enums::GridType a_grid_type); - // Device vectors of stencil coefficients used for finite-order centering of fields amrex::Gpu::DeviceVector device_field_centering_stencil_coeffs_x; amrex::Gpu::DeviceVector device_field_centering_stencil_coeffs_y; @@ -1001,41 +981,6 @@ public: void InitEB (); -#ifdef AMREX_USE_EB - /** - * \brief Compute the length of the mesh edges. Here the length is a value in [0, 1]. - * An edge of length 0 is fully covered. - */ - static void ComputeEdgeLengths (ablastr::fields::VectorField& edge_lengths, - const amrex::EBFArrayBoxFactory& eb_fact); - /** - * \brief Compute the area of the mesh faces. Here the area is a value in [0, 1]. - * An edge of area 0 is fully covered. - */ - static void ComputeFaceAreas (ablastr::fields::VectorField& face_areas, - const amrex::EBFArrayBoxFactory& eb_fact); - - /** - * \brief Scale the edges lengths by the mesh width to obtain the real lengths. - */ - static void ScaleEdges (ablastr::fields::VectorField& edge_lengths, - const std::array& cell_size); - /** - * \brief Scale the edges areas by the mesh width to obtain the real areas. - */ - static void ScaleAreas (ablastr::fields::VectorField& face_areas, - const std::array& cell_size); - /** - * \brief Initialize information for cell extensions. - * The flags convention for m_flag_info_face is as follows - * - 0 for unstable cells - * - 1 for stable cells which have not been intruded - * - 2 for stable cells which have been intruded - * Here we cannot know if a cell is intruded or not so we initialize all stable cells with 1 - */ - void MarkCells(); -#endif - /** * \brief Compute the level set function used for particle-boundary interaction. */ @@ -1082,13 +1027,7 @@ public: void PSATDSubtractCurrentPartialSumsAvg (); #ifdef WARPX_USE_FFT - -# ifdef WARPX_DIM_RZ - SpectralSolverRZ& -# else - SpectralSolver& -# endif - get_spectral_solver_fp (int lev) {return *spectral_solver_fp[lev];} + auto& get_spectral_solver_fp (int lev) {return *spectral_solver_fp[lev];} #endif FiniteDifferenceSolver * get_pointer_fdtd_solver_fp (int lev) { return m_fdtd_solver_fp[lev].get(); } @@ -1205,12 +1144,12 @@ private: int lev); void StoreCurrent (int lev); void RestoreCurrent (int lev); - void ApplyFilterJ ( - const ablastr::fields::MultiLevelVectorField& current, + void ApplyFilterMF ( + const ablastr::fields::MultiLevelVectorField& mfvec, int lev, int idim); - void ApplyFilterJ ( - const ablastr::fields::MultiLevelVectorField& current, + void ApplyFilterMF ( + const ablastr::fields::MultiLevelVectorField& mfvec, int lev); void SumBoundaryJ ( const ablastr::fields::MultiLevelVectorField& current, @@ -1221,11 +1160,6 @@ private: const ablastr::fields::MultiLevelVectorField& current, int lev, const amrex::Periodicity& period); - void NodalSyncJ ( - const ablastr::fields::MultiLevelVectorField& J_fp, - const ablastr::fields::MultiLevelVectorField& J_cp, - int lev, - PatchType patch_type); void RestrictRhoFromFineToCoarsePatch (int lev ); void ApplyFilterandSumBoundaryRho ( @@ -1242,13 +1176,6 @@ private: int lev, int icomp, int ncomp); - void NodalSyncRho ( - const amrex::Vector>& charge_fp, - const amrex::Vector>& charge_cp, - int lev, - PatchType patch_type, - int icomp, - int ncomp); void ReadParameters (); @@ -1298,18 +1225,6 @@ private: return gather_buffer_masks[lev].get(); } - /** - * \brief Re-orders the Fornberg coefficients so that they can be used more conveniently for - * finite-order centering operations. For example, for finite-order centering of order 6, - * the Fornberg coefficients \c (c_0,c_1,c_2) are re-ordered as \c (c_2,c_1,c_0,c_0,c_1,c_2). - * - * \param[in,out] ordered_coeffs host vector where the re-ordered Fornberg coefficients will be stored - * \param[in] unordered_coeffs host vector storing the original sequence of Fornberg coefficients - * \param[in] order order of the finite-order centering along a given direction - */ - void ReorderFornbergCoefficients (amrex::Vector& ordered_coeffs, - amrex::Vector& unordered_coeffs, - int order); /** * \brief Allocates and initializes the stencil coefficients used for the finite-order centering * of fields and currents, and stores them in the given device vectors. @@ -1361,7 +1276,9 @@ private: amrex::Vector t_new; amrex::Vector t_old; amrex::Vector dt; - static utils::parser::IntervalsParser dt_update_interval; // How often to update the timestep when using adaptive timestepping + utils::parser::IntervalsParser m_dt_update_interval = utils::parser::IntervalsParser{}; // How often to update the timestep when using adaptive timestepping + + bool m_safe_guard_cells = false; // Particle container std::unique_ptr mypc; @@ -1371,6 +1288,9 @@ private: bool do_fluid_species = false; std::unique_ptr myfl; + //! Integer that corresponds to electromagnetic Maxwell solver (vacuum - 0, macroscopic - 1) + MediumForEM m_em_solver_medium = MediumForEM::Default; + // // Fields: First array for level, second for direction // @@ -1382,17 +1302,30 @@ private: mutable amrex::Vector,3 > > Afield_dotMask; mutable amrex::Vector< std::unique_ptr > phi_dotMask; + /** EB: Flag to indicate whether a gridpoint is inside the embedded boundary and therefore + * whether the E or B should not be updated. (One array per level and per direction, due to staggering) + */ + amrex::Vector,3 > > m_eb_update_E; + amrex::Vector,3 > > m_eb_update_B; + + /** EB: Mask that indicates whether a particle should use its regular shape factor (mask set to 0) + * or a reduced, order-1 shape factor instead (mask set to 1) in a given cell, when depositing charge/current. + * The flag is typically set to 1 in cells that are close to the embedded boundary, in order to avoid + * errors in charge conservation when a particle is too close to the embedded boundary. + */ + amrex::Vector< std::unique_ptr > m_eb_reduce_particle_shape; + /** EB: for every mesh face flag_info_face contains a: * * 0 if the face needs to be extended * * 1 if the face is large enough to lend area to other faces * * 2 if the face is actually intruded by other face - * It is initialized in WarpX::MarkCells + * It is initialized in WarpX::MarkExtensionCells * This is only used for the ECT solver.*/ amrex::Vector, 3 > > m_flag_info_face; /** EB: for every mesh face face flag_ext_face contains a: * * 1 if the face needs to be extended * * 0 otherwise - * It is initialized in WarpX::MarkCells and then modified in WarpX::ComputeOneWayExtensions + * It is initialized in WarpX::MarkExtensionCells and then modified in WarpX::ComputeOneWayExtensions * and in WarpX::ComputeEightWaysExtensions * This is only used for the ECT solver.*/ amrex::Vector, 3 > > m_flag_ext_face; @@ -1425,11 +1358,20 @@ private: #endif amrex::Real v_particle_pml; + // Insulator boundary conditions + std::unique_ptr pec_insulator_boundary; + // External fields parameters std::unique_ptr m_p_ext_field_params; amrex::Real moving_window_x = std::numeric_limits::max(); + // Mirrors + int m_num_mirrors = 0; + amrex::Vector m_mirror_z; + amrex::Vector m_mirror_z_width; + amrex::Vector m_mirror_z_npoints; + // Plasma injection parameters int warpx_do_continuous_injection = 0; int num_injected_species = -1; @@ -1439,6 +1381,13 @@ private: std::optional m_const_dt; std::optional m_max_dt; + // whether to use subcycling + bool m_do_subcycling = false; + + //! Flag whether the Verboncoeur correction is applied to the current and charge density + //! on the axis when using RZ. + bool m_verboncoeur_axis_correction = true; + // Macroscopic properties std::unique_ptr m_macroscopic_properties; @@ -1494,6 +1443,11 @@ private: int max_step = std::numeric_limits::max(); amrex::Real stop_time = std::numeric_limits::max(); + //! If specified, the maximum number of iterations is computed automatically so that + //! the lower end of the simulation domain along z reaches #zmax_plasma_to_compute_max_step + //! in the boosted frame + std::optional m_zmax_plasma_to_compute_max_step = std::nullopt; + int regrid_int = -1; amrex::Real cfl = amrex::Real(0.999); @@ -1535,6 +1489,10 @@ private: int noy_fft = 16; int noz_fft = 16; + //! Solve Poisson equation when loading an external magnetic field to clean divergence + //! This is useful to remove errors that could lead to non-zero B field divergence + bool m_do_divb_cleaning_external = false; + //! Domain decomposition on Level 0 amrex::IntVect numprocs{0}; @@ -1566,13 +1524,6 @@ private: [[nodiscard]] bool checkStopSimulation (amrex::Real cur_time); - /** Print Unused Parameter Warnings after Step 1 - * - * Instead of waiting for a simulation to end, we already do an early "unused parameter check" - * after step 1 to inform users early of potential issues with their simulation setup. - */ - void checkEarlyUnusedParams (); - /** Perform essential particle house keeping at boundaries * * Inject, communicate, scrape and sort particles. @@ -1583,8 +1534,6 @@ private: */ void HandleParticlesAtBoundaries (int step, amrex::Real cur_time, int num_moved); - void ScrapeParticles (); - /** Update the E and B fields in the explicit em PIC scheme. * * At the beginning, we have B^{n} and E^{n}. @@ -1592,7 +1541,12 @@ private: */ void ExplicitFillBoundaryEBUpdateAux (); - void PushPSATD (); + //! Integer that corresponds to the order of the PSATD solution + //! (whether the PSATD equations are derived from first-order or + //! second-order solution) + PSATDSolutionType m_psatd_solution_type = PSATDSolutionType::Default; + + void PushPSATD (amrex::Real start_time); #ifdef WARPX_USE_FFT diff --git a/Source/WarpX.cpp b/Source/WarpX.cpp index d1e3108e32a..c9e90850ee1 100644 --- a/Source/WarpX.cpp +++ b/Source/WarpX.cpp @@ -11,6 +11,7 @@ */ #include "WarpX.H" +#include "BoundaryConditions/PEC_Insulator.H" #include "BoundaryConditions/PML.H" #include "Diagnostics/MultiDiagnostics.H" #include "Diagnostics/ReducedDiags/MultiReducedDiags.H" @@ -19,6 +20,7 @@ #include "FieldSolver/ElectrostaticSolvers/ElectrostaticSolver.H" #include "FieldSolver/ElectrostaticSolvers/LabFrameExplicitES.H" #include "FieldSolver/ElectrostaticSolvers/RelativisticExplicitES.H" +#include "FieldSolver/ElectrostaticSolvers/EffectivePotentialES.H" #include "FieldSolver/FiniteDifferenceSolver/FiniteDifferenceSolver.H" #include "FieldSolver/FiniteDifferenceSolver/MacroscopicProperties/MacroscopicProperties.H" #include "FieldSolver/FiniteDifferenceSolver/HybridPICModel/HybridPICModel.H" @@ -34,6 +36,7 @@ #include "FieldSolver/WarpX_FDTD.H" #include "Filter/NCIGodfreyFilter.H" #include "Initialization/ExternalField.H" +#include "Initialization/WarpXInit.H" #include "Particles/MultiParticleContainer.H" #include "Fluids/MultiFluidContainer.H" #include "Fluids/WarpXFluidContainer.H" @@ -47,6 +50,7 @@ #include "FieldSolver/ImplicitSolvers/ImplicitSolverLibrary.H" +#include #include #include @@ -108,16 +112,13 @@ amrex::IntVect WarpX::m_fill_guards_current = amrex::IntVect(0); Real WarpX::gamma_boost = 1._rt; Real WarpX::beta_boost = 0._rt; Vector WarpX::boost_direction = {0,0,0}; -bool WarpX::do_compute_max_step_from_zmax = false; bool WarpX::compute_max_step_from_btd = false; -Real WarpX::zmax_plasma_to_compute_max_step = 0._rt; Real WarpX::zmin_domain_boost_step_0 = 0._rt; int WarpX::max_particle_its_in_implicit_scheme = 21; ParticleReal WarpX::particle_tol_in_implicit_scheme = 1.e-10; bool WarpX::do_dive_cleaning = false; bool WarpX::do_divb_cleaning = false; -bool WarpX::do_divb_cleaning_external = false; bool WarpX::do_single_precision_comms = false; bool WarpX::do_shared_mem_charge_deposition = false; @@ -153,8 +154,6 @@ int WarpX::current_centering_noz = 2; bool WarpX::use_fdtd_nci_corr = false; bool WarpX::galerkin_interpolation = true; -bool WarpX::verboncoeur_axis_correction = true; - bool WarpX::use_filter = true; bool WarpX::use_kspace_filter = true; bool WarpX::use_filter_compensation = false; @@ -162,8 +161,6 @@ bool WarpX::use_filter_compensation = false; bool WarpX::serialize_initial_conditions = false; bool WarpX::refine_plasma = false; -int WarpX::num_mirrors = 0; - utils::parser::IntervalsParser WarpX::sort_intervals; amrex::IntVect WarpX::sort_bin_size(AMREX_D_DECL(1,1,1)); @@ -177,14 +174,8 @@ amrex::IntVect WarpX::sort_idx_type(AMREX_D_DECL(0,0,0)); bool WarpX::do_dynamic_scheduling = true; -bool WarpX::do_subcycling = false; bool WarpX::do_multi_J = false; int WarpX::do_multi_J_n_depositions; -bool WarpX::safe_guard_cells = false; - -utils::parser::IntervalsParser WarpX::dt_update_interval; - -std::map WarpX::imultifab_map; IntVect WarpX::filter_npass_each_dir(1); @@ -209,11 +200,32 @@ namespace std::any_of(field_boundary_hi.begin(), field_boundary_hi.end(), is_pml); return is_any_pml; } + + /** + * \brief + * Set the dotMask container + */ + void SetDotMask( std::unique_ptr& field_dotMask, + ablastr::fields::ConstScalarField const& field, + amrex::Periodicity const& periodicity) + + { + // Define the dot mask for this field_type needed to properly compute dotProduct() + // for field values that have shared locations on different MPI ranks + if (field_dotMask != nullptr) { return; } + + const auto& this_ba = field->boxArray(); + const auto tmp = amrex::MultiFab{ + this_ba, field->DistributionMap(), + 1, 0, amrex::MFInfo().SetAlloc(false)}; + + field_dotMask = tmp.OwnerMask(periodicity); + } } void WarpX::MakeWarpX () { - ParseGeometryInput(); + warpx::initialization::check_dims(); ReadMovingWindowParameters( do_moving_window, start_moving_window_step, end_moving_window_step, @@ -255,6 +267,8 @@ WarpX::Finalize() WarpX::WarpX () { + warpx::initialization::initialize_warning_manager(); + ReadParameters(); BackwardCompatibility(); @@ -271,12 +285,6 @@ WarpX::WarpX () istep.resize(nlevs_max, 0); nsubsteps.resize(nlevs_max, 1); -#if 0 - // no subcycling yet - for (int lev = 1; lev < nlevs_max; ++lev) { - nsubsteps[lev] = MaxRefRatio(lev-1); - } -#endif t_new.resize(nlevs_max, 0.0); t_old.resize(nlevs_max, std::numeric_limits::lowest()); @@ -321,6 +329,10 @@ WarpX::WarpX () Afield_dotMask.resize(nlevs_max); phi_dotMask.resize(nlevs_max); + m_eb_update_E.resize(nlevs_max); + m_eb_update_B.resize(nlevs_max); + m_eb_reduce_particle_shape.resize(nlevs_max); + m_flag_info_face.resize(nlevs_max); m_flag_ext_face.resize(nlevs_max); m_borrowing.resize(nlevs_max); @@ -331,6 +343,11 @@ WarpX::WarpX () { m_electrostatic_solver = std::make_unique(nlevs_max); } + // Initialize the effective potential electrostatic solver if required + else if (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameEffectivePotential) + { + m_electrostatic_solver = std::make_unique(nlevs_max); + } else { m_electrostatic_solver = std::make_unique(nlevs_max); @@ -358,7 +375,7 @@ WarpX::WarpX () m_field_factory.resize(nlevs_max); - if (em_solver_medium == MediumForEM::Macroscopic) { + if (m_em_solver_medium == MediumForEM::Macroscopic) { // create object for macroscopic solver m_macroscopic_properties = std::make_unique(); } @@ -441,7 +458,7 @@ WarpX::WarpX () // (e.g., use_fdtd_nci_corr) if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD) { AMREX_ALWAYS_ASSERT(use_fdtd_nci_corr == 0); - AMREX_ALWAYS_ASSERT(do_subcycling == 0); + AMREX_ALWAYS_ASSERT(m_do_subcycling == 0); } if (WarpX::current_deposition_algo != CurrentDepositionAlgo::Esirkepov) { @@ -465,9 +482,6 @@ WarpX::~WarpX () void WarpX::ReadParameters () { - // Ensure that geometry.dims is set properly. - CheckDims(); - { const ParmParse pp;// Traditionally, max_step and stop_time do not have prefix. utils::parser::queryWithParser(pp, "max_step", max_step); @@ -487,37 +501,25 @@ WarpX::ReadParameters () if (electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT && !EB::enabled()) { throw std::runtime_error("ECP Solver requires to enable embedded boundaries at runtime."); } +#ifdef WARPX_DIM_RZ + if (electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD) + { + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(Geom(0).ProbLo(0) == 0., + "Lower bound of radial coordinate (prob_lo[0]) with RZ PSATD solver must be zero"); + } + else + { + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(Geom(0).ProbLo(0) >= 0., + "Lower bound of radial coordinate (prob_lo[0]) with RZ FDTD solver must be non-negative"); + } +#endif + + pp_algo.query_enum_sloppy("evolve_scheme", evolve_scheme, "-_"); } { ParmParse const pp_warpx("warpx"); - //"Synthetic" warning messages may be injected in the Warning Manager via - // inputfile for debug&testing purposes. - ablastr::warn_manager::GetWMInstance().debug_read_warnings_from_input(pp_warpx); - - // Set the flag to control if WarpX has to emit a warning message as soon as a warning is recorded - bool always_warn_immediately = false; - pp_warpx.query("always_warn_immediately", always_warn_immediately); - ablastr::warn_manager::GetWMInstance().SetAlwaysWarnImmediately(always_warn_immediately); - - // Set the WarnPriority threshold to decide if WarpX has to abort when a warning is recorded - if(std::string str_abort_on_warning_threshold; - pp_warpx.query("abort_on_warning_threshold", str_abort_on_warning_threshold)){ - std::optional abort_on_warning_threshold = std::nullopt; - if (str_abort_on_warning_threshold == "high") { - abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::high; - } else if (str_abort_on_warning_threshold == "medium" ) { - abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::medium; - } else if (str_abort_on_warning_threshold == "low") { - abort_on_warning_threshold = ablastr::warn_manager::WarnPriority::low; - } else { - WARPX_ABORT_WITH_MESSAGE(str_abort_on_warning_threshold - +"is not a valid option for warpx.abort_on_warning_threshold (use: low, medium or high)"); - } - ablastr::warn_manager::GetWMInstance().SetAbortThreshold(abort_on_warning_threshold); - } - std::vector numprocs_in; utils::parser::queryArrWithParser( pp_warpx, "numprocs", numprocs_in, 0, AMREX_SPACEDIM); @@ -614,7 +616,7 @@ WarpX::ReadParameters () utils::parser::queryWithParser(pp_warpx, "cfl", cfl); pp_warpx.query("verbose", verbose); utils::parser::queryWithParser(pp_warpx, "regrid_int", regrid_int); - pp_warpx.query("do_subcycling", do_subcycling); + pp_warpx.query("do_subcycling", m_do_subcycling); pp_warpx.query("do_multi_J", do_multi_J); if (do_multi_J) { @@ -622,22 +624,22 @@ WarpX::ReadParameters () pp_warpx, "do_multi_J_n_depositions", do_multi_J_n_depositions); } pp_warpx.query("use_hybrid_QED", use_hybrid_QED); - pp_warpx.query("safe_guard_cells", safe_guard_cells); + pp_warpx.query("safe_guard_cells", m_safe_guard_cells); std::vector override_sync_intervals_string_vec = {"1"}; pp_warpx.queryarr("override_sync_intervals", override_sync_intervals_string_vec); override_sync_intervals = utils::parser::IntervalsParser(override_sync_intervals_string_vec); - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(do_subcycling != 1 || max_level <= 1, + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(m_do_subcycling != 1 || max_level <= 1, "Subcycling method 1 only works for 2 levels."); ReadBoostedFrameParameters(gamma_boost, beta_boost, boost_direction); // queryWithParser returns 1 if argument zmax_plasma_to_compute_max_step is // specified by the user, 0 otherwise. - do_compute_max_step_from_zmax = utils::parser::queryWithParser( - pp_warpx, "zmax_plasma_to_compute_max_step", - zmax_plasma_to_compute_max_step); + if(auto temp = 0.0_rt; utils::parser::queryWithParser(pp_warpx, "zmax_plasma_to_compute_max_step",temp)){ + m_zmax_plasma_to_compute_max_step = temp; + } pp_warpx.query("compute_max_step_from_btd", compute_max_step_from_btd); @@ -676,6 +678,8 @@ WarpX::ReadParameters () poisson_solver_id!=PoissonSolverAlgo::IntegratedGreenFunction, "To use the FFT Poisson solver, compile with WARPX_USE_FFT=ON."); #endif + utils::parser::queryWithParser(pp_warpx, "self_fields_max_iters", magnetostatic_solver_max_iters); + utils::parser::queryWithParser(pp_warpx, "self_fields_verbosity", magnetostatic_solver_verbosity); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( ( @@ -695,7 +699,7 @@ WarpX::ReadParameters () #ifdef WARPX_DIM_RZ const ParmParse pp_boundary("boundary"); - pp_boundary.query("verboncoeur_axis_correction", verboncoeur_axis_correction); + pp_boundary.query("verboncoeur_axis_correction", m_verboncoeur_axis_correction); #endif // Read timestepping options @@ -703,7 +707,12 @@ WarpX::ReadParameters () utils::parser::queryWithParser(pp_warpx, "max_dt", m_max_dt); std::vector dt_interval_vec = {"-1"}; pp_warpx.queryarr("dt_update_interval", dt_interval_vec); - dt_update_interval = utils::parser::IntervalsParser(dt_interval_vec); + m_dt_update_interval = utils::parser::IntervalsParser(dt_interval_vec); + + // Filter defaults to true for the explicit scheme, and false for the implicit schemes + if (evolve_scheme != EvolveScheme::Explicit) { + use_filter = false; + } // Filter currently not working with FDTD solver in RZ geometry: turn OFF by default // (see https://github.com/ECP-WarpX/WarpX/issues/1943) @@ -734,27 +743,37 @@ WarpX::ReadParameters () use_kspace_filter = use_filter; use_filter = false; } - else // FDTD + else { - // Filter currently not working with FDTD solver in RZ geometry along R - // (see https://github.com/ECP-WarpX/WarpX/issues/1943) - WARPX_ALWAYS_ASSERT_WITH_MESSAGE(!use_filter || filter_npass_each_dir[0] == 0, - "In RZ geometry with FDTD, filtering can only be apply along z. This can be controlled by setting warpx.filter_npass_each_dir"); + if (WarpX::electromagnetic_solver_id != ElectromagneticSolverAlgo::HybridPIC) { + // Filter currently not working with FDTD solver in RZ geometry along R + // (see https://github.com/ECP-WarpX/WarpX/issues/1943) + WARPX_ALWAYS_ASSERT_WITH_MESSAGE(!use_filter || filter_npass_each_dir[0] == 0, + "In RZ geometry with FDTD, filtering can only be applied along z. This can be controlled by setting warpx.filter_npass_each_dir"); + } else { + if (use_filter && filter_npass_each_dir[0] > 0) { + ablastr::warn_manager::WMRecordWarning( + "HybridPIC ElectromagneticSolver", + "Radial Filtering in RZ is not currently using radial geometric weighting to conserve charge. Use at your own risk.", + ablastr::warn_manager::WarnPriority::low + ); + } + } } #endif utils::parser::queryWithParser( - pp_warpx, "num_mirrors", num_mirrors); - if (num_mirrors>0){ - mirror_z.resize(num_mirrors); + pp_warpx, "num_mirrors", m_num_mirrors); + if (m_num_mirrors>0){ + m_mirror_z.resize(m_num_mirrors); utils::parser::getArrWithParser( - pp_warpx, "mirror_z", mirror_z, 0, num_mirrors); - mirror_z_width.resize(num_mirrors); + pp_warpx, "mirror_z", m_mirror_z, 0, m_num_mirrors); + m_mirror_z_width.resize(m_num_mirrors); utils::parser::getArrWithParser( - pp_warpx, "mirror_z_width", mirror_z_width, 0, num_mirrors); - mirror_z_npoints.resize(num_mirrors); + pp_warpx, "mirror_z_width", m_mirror_z_width, 0, m_num_mirrors); + m_mirror_z_npoints.resize(m_num_mirrors); utils::parser::getArrWithParser( - pp_warpx, "mirror_z_npoints", mirror_z_npoints, 0, num_mirrors); + pp_warpx, "mirror_z_npoints", m_mirror_z_npoints, 0, m_num_mirrors); } pp_warpx.query("do_single_precision_comms", do_single_precision_comms); @@ -1025,9 +1044,9 @@ WarpX::ReadParameters () || WarpX::electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic) && WarpX::poisson_solver_id == PoissonSolverAlgo::Multigrid))) { - do_divb_cleaning_external = true; + m_do_divb_cleaning_external = true; } - pp_warpx.query("do_divb_cleaning_external", do_divb_cleaning_external); + pp_warpx.query("do_divb_cleaning_external", m_do_divb_cleaning_external); // If true, the current is deposited on a nodal grid and centered onto // a staggered grid. Setting warpx.do_current_centering=1 makes sense @@ -1073,7 +1092,10 @@ WarpX::ReadParameters () WARPX_ALWAYS_ASSERT_WITH_MESSAGE( electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD, "algo.maxwell_solver = psatd is not supported because WarpX was built without spectral solvers"); #endif - +#if defined(WARPX_DIM_1D_Z) && defined(WARPX_USE_FFT) + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD, + "algo.maxwell_solver = psatd is not available for 1D geometry"); +#endif #ifdef WARPX_DIM_RZ WARPX_ALWAYS_ASSERT_WITH_MESSAGE(Geom(0).isPeriodic(0) == 0, "The problem must not be periodic in the radial direction"); @@ -1112,7 +1134,6 @@ WarpX::ReadParameters () pp_algo.query_enum_sloppy("current_deposition", current_deposition_algo, "-_"); pp_algo.query_enum_sloppy("charge_deposition", charge_deposition_algo, "-_"); pp_algo.query_enum_sloppy("particle_pusher", particle_pusher_algo, "-_"); - pp_algo.query_enum_sloppy("evolve_scheme", evolve_scheme, "-_"); // check for implicit evolve scheme if (evolve_scheme == EvolveScheme::SemiImplicitEM) { @@ -1121,11 +1142,14 @@ WarpX::ReadParameters () else if (evolve_scheme == EvolveScheme::ThetaImplicitEM) { m_implicit_solver = std::make_unique(); } + else if (evolve_scheme == EvolveScheme::StrangImplicitSpectralEM) { + m_implicit_solver = std::make_unique(); + } // implicit evolve schemes not setup to use mirrors if (evolve_scheme == EvolveScheme::SemiImplicitEM || evolve_scheme == EvolveScheme::ThetaImplicitEM) { - WARPX_ALWAYS_ASSERT_WITH_MESSAGE( num_mirrors == 0, + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( m_num_mirrors == 0, "Mirrors cannot be used with Implicit evolve schemes."); } @@ -1166,7 +1190,8 @@ WarpX::ReadParameters () if (current_deposition_algo == CurrentDepositionAlgo::Villasenor) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( evolve_scheme == EvolveScheme::SemiImplicitEM || - evolve_scheme == EvolveScheme::ThetaImplicitEM, + evolve_scheme == EvolveScheme::ThetaImplicitEM || + evolve_scheme == EvolveScheme::StrangImplicitSpectralEM, "Villasenor current deposition can only" "be used with Implicit evolve schemes."); } @@ -1230,14 +1255,15 @@ WarpX::ReadParameters () " combined with mesh refinement is currently not implemented"); } - pp_algo.query_enum_sloppy("em_solver_medium", em_solver_medium, "-_"); - if (em_solver_medium == MediumForEM::Macroscopic ) { + pp_algo.query_enum_sloppy("em_solver_medium", m_em_solver_medium, "-_"); + if (m_em_solver_medium == MediumForEM::Macroscopic ) { pp_algo.query_enum_sloppy("macroscopic_sigma_method", macroscopic_solver_algo, "-_"); } if (evolve_scheme == EvolveScheme::SemiImplicitEM || - evolve_scheme == EvolveScheme::ThetaImplicitEM) { + evolve_scheme == EvolveScheme::ThetaImplicitEM || + evolve_scheme == EvolveScheme::StrangImplicitSpectralEM) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( current_deposition_algo == CurrentDepositionAlgo::Esirkepov || @@ -1247,8 +1273,9 @@ WarpX::ReadParameters () WARPX_ALWAYS_ASSERT_WITH_MESSAGE( electromagnetic_solver_id == ElectromagneticSolverAlgo::Yee || - electromagnetic_solver_id == ElectromagneticSolverAlgo::CKC, - "Only the Yee EM solver is supported with the implicit and semi-implicit schemes"); + electromagnetic_solver_id == ElectromagneticSolverAlgo::CKC || + electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD, + "Only the Yee, CKC, and PSATD EM solvers are supported with the implicit and semi-implicit schemes"); WARPX_ALWAYS_ASSERT_WITH_MESSAGE( particle_pusher_algo == ParticlePusherAlgo::Boris || @@ -1259,6 +1286,11 @@ WarpX::ReadParameters () field_gathering_algo != GatheringAlgo::MomentumConserving, "With implicit and semi-implicit schemes, the momentum conserving field gather is not supported as it would not conserve energy"); } + if (evolve_scheme == EvolveScheme::StrangImplicitSpectralEM) { + WARPX_ALWAYS_ASSERT_WITH_MESSAGE( + electromagnetic_solver_id == ElectromagneticSolverAlgo::PSATD, + "With the strang_implicit_spectral_em evolve scheme, the algo.maxwell_solver must be psatd"); + } // Load balancing parameters std::vector load_balance_intervals_string_vec = {"0"}; @@ -1444,14 +1476,14 @@ WarpX::ReadParameters () // Integer that corresponds to the order of the PSATD solution // (whether the PSATD equations are derived from first-order or // second-order solution) - pp_psatd.query_enum_sloppy("solution_type", psatd_solution_type, "-_"); + pp_psatd.query_enum_sloppy("solution_type", m_psatd_solution_type, "-_"); // Integers that correspond to the time dependency of J (constant, linear) // and rho (linear, quadratic) for the PSATD algorithm pp_psatd.query_enum_sloppy("J_in_time", J_in_time, "-_"); pp_psatd.query_enum_sloppy("rho_in_time", rho_in_time, "-_"); - if (psatd_solution_type != PSATDSolutionType::FirstOrder || !do_multi_J) + if (m_psatd_solution_type != PSATDSolutionType::FirstOrder || !do_multi_J) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( rho_in_time == RhoInTime::Linear, @@ -1685,6 +1717,9 @@ WarpX::ReadParameters () } } + // Setup pec_insulator boundary conditions + pec_insulator_boundary = std::make_unique(); + // for slice generation // { const ParmParse pp_slice("slice"); @@ -2015,7 +2050,7 @@ WarpX::AllocLevelData (int lev, const BoxArray& ba, const DistributionMapping& d guard_cells.Init( dt[lev], dx, - do_subcycling, + m_do_subcycling, WarpX::use_fdtd_nci_corr, grid_type, do_moving_window, @@ -2027,7 +2062,7 @@ WarpX::AllocLevelData (int lev, const BoxArray& ba, const DistributionMapping& d maxLevel(), WarpX::m_v_galilean, WarpX::m_v_comoving, - safe_guard_cells, + m_safe_guard_cells, WarpX::do_multi_J, WarpX::fft_do_time_averaging, ::isAnyBoundaryPML(field_boundary_lo, field_boundary_hi), @@ -2071,7 +2106,7 @@ WarpX::AllocLevelData (int lev, const BoxArray& ba, const DistributionMapping& d guard_cells.ng_alloc_Rho, guard_cells.ng_alloc_F, guard_cells.ng_alloc_G, aux_is_nodal); m_accelerator_lattice[lev] = std::make_unique(); - m_accelerator_lattice[lev]->InitElementFinder(lev, ba, dm); + m_accelerator_lattice[lev]->InitElementFinder(lev, gamma_boost, ba, dm); } @@ -2232,8 +2267,9 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm { m_hybrid_pic_model->AllocateLevelMFs( m_fields, - lev, ba, dm, ncomps, ngJ, ngRho, jx_nodal_flag, jy_nodal_flag, - jz_nodal_flag, rho_nodal_flag + lev, ba, dm, ncomps, ngJ, ngRho, ngEB, jx_nodal_flag, jy_nodal_flag, + jz_nodal_flag, rho_nodal_flag, Ex_nodal_flag, Ey_nodal_flag, Ez_nodal_flag, + Bx_nodal_flag, By_nodal_flag, Bz_nodal_flag ); } @@ -2246,7 +2282,7 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm } // Allocate extra multifabs for macroscopic properties of the medium - if (em_solver_medium == MediumForEM::Macroscopic) { + if (m_em_solver_medium == MediumForEM::Macroscopic) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( lev==0, "Macroscopic properties are not supported with mesh refinement."); m_macroscopic_properties->AllocateLevelMFs(ba, dm, ngEB); @@ -2268,10 +2304,31 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm amrex::IntVect const ng_ls(2); //EB level set m_fields.alloc_init(FieldType::distance_to_eb, lev, amrex::convert(ba, IntVect::TheNodeVector()), dm, nc_ls, ng_ls, 0.0_rt); + // Whether to reduce the particle shape to order 1 when close to the EB + AllocInitMultiFab(m_eb_reduce_particle_shape[lev], amrex::convert(ba, IntVect::TheCellVector()), dm, ncomps, + ngRho, lev, "m_eb_reduce_particle_shape"); // EB info are needed only at the finest level if (lev == maxLevel()) { + if (WarpX::electromagnetic_solver_id != ElectromagneticSolverAlgo::PSATD) { + + AllocInitMultiFab(m_eb_update_E[lev][0], amrex::convert(ba, Ex_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_E[x]"); + AllocInitMultiFab(m_eb_update_E[lev][1], amrex::convert(ba, Ey_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_E[y]"); + AllocInitMultiFab(m_eb_update_E[lev][2], amrex::convert(ba, Ez_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_E[z]"); + + AllocInitMultiFab(m_eb_update_B[lev][0], amrex::convert(ba, Bx_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_B[x]"); + AllocInitMultiFab(m_eb_update_B[lev][1], amrex::convert(ba, By_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_B[y]"); + AllocInitMultiFab(m_eb_update_B[lev][2], amrex::convert(ba, Bz_nodal_flag), dm, ncomps, + guard_cells.ng_FieldSolver, lev, "m_eb_update_B[z]"); + } + if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { + //! EB: Lengths of the mesh edges m_fields.alloc_init(FieldType::edge_lengths, Direction{0}, lev, amrex::convert(ba, Ex_nodal_flag), dm, ncomps, guard_cells.ng_FieldSolver, 0.0_rt); @@ -2287,8 +2344,7 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm dm, ncomps, guard_cells.ng_FieldSolver, 0.0_rt); m_fields.alloc_init(FieldType::face_areas, Direction{2}, lev, amrex::convert(ba, Bz_nodal_flag), dm, ncomps, guard_cells.ng_FieldSolver, 0.0_rt); - } - if (WarpX::electromagnetic_solver_id == ElectromagneticSolverAlgo::ECT) { + AllocInitMultiFab(m_flag_info_face[lev][0], amrex::convert(ba, Bx_nodal_flag), dm, ncomps, guard_cells.ng_FieldSolver, lev, "m_flag_info_face[x]"); AllocInitMultiFab(m_flag_info_face[lev][1], amrex::convert(ba, By_nodal_flag), dm, ncomps, @@ -2349,6 +2405,7 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm int rho_ncomps = 0; if( (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrame) || (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic) || + (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameEffectivePotential) || (electromagnetic_solver_id == ElectromagneticSolverAlgo::HybridPIC) ) { rho_ncomps = ncomps; } @@ -2369,14 +2426,15 @@ WarpX::AllocLevelMFs (int lev, const BoxArray& ba, const DistributionMapping& dm } if (electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrame || - electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic) + electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameElectroMagnetostatic || + electrostatic_solver_id == ElectrostaticSolverAlgo::LabFrameEffectivePotential ) { const IntVect ngPhi = IntVect( AMREX_D_DECL(1,1,1) ); m_fields.alloc_init(FieldType::phi_fp, lev, amrex::convert(ba, phi_nodal_flag), dm, ncomps, ngPhi, 0.0_rt ); } - if (do_subcycling && lev == 0) + if (m_do_subcycling && lev == 0) { m_fields.alloc_init(FieldType::current_store, Direction{0}, lev, amrex::convert(ba,jx_nodal_flag), dm, ncomps, ngJ, 0.0_rt); m_fields.alloc_init(FieldType::current_store, Direction{1}, lev, amrex::convert(ba,jy_nodal_flag), dm, ncomps, ngJ, 0.0_rt); @@ -2748,6 +2806,10 @@ void WarpX::AllocLevelSpectralSolverRZ (amrex::Vector(WarpX::do_multi_J_n_depositions); } + if (evolve_scheme == EvolveScheme::StrangImplicitSpectralEM) { + // The step is Strang split into two half steps + solver_dt /= 2.; + } auto pss = std::make_unique(lev, realspace_ba, @@ -2801,6 +2863,10 @@ void WarpX::AllocLevelSpectralSolver (amrex::Vector(WarpX::do_multi_J_n_depositions); } + if (evolve_scheme == EvolveScheme::StrangImplicitSpectralEM) { + // The step is Strang split into two half steps + solver_dt /= 2.; + } auto pss = std::make_unique(lev, realspace_ba, @@ -2817,7 +2883,7 @@ void WarpX::AllocLevelSpectralSolver (amrex::Vector WarpX::getFornbergStencilCoefficients (const int n_order, ablastr::utils::enums::GridType a_grid_type) -{ - AMREX_ALWAYS_ASSERT_WITH_MESSAGE(n_order % 2 == 0, "n_order must be even"); - - const int m = n_order / 2; - amrex::Vector coeffs; - coeffs.resize(m); - - // There are closed-form formula for these coefficients, but they result in - // an overflow when evaluated numerically. One way to avoid the overflow is - // to calculate the coefficients by recurrence. - - // Coefficients for collocated (nodal) finite-difference approximation - if (a_grid_type == GridType::Collocated) - { - // First coefficient - coeffs.at(0) = m * 2._rt / (m+1); - // Other coefficients by recurrence - for (int n = 1; n < m; n++) - { - coeffs.at(n) = - (m-n) * 1._rt / (m+n+1) * coeffs.at(n-1); - } - } - // Coefficients for staggered finite-difference approximation - else - { - Real prod = 1.; - for (int k = 1; k < m+1; k++) - { - prod *= (m + k) / (4._rt * k); - } - // First coefficient - coeffs.at(0) = 4_rt * m * prod * prod; - // Other coefficients by recurrence - for (int n = 1; n < m; n++) - { - coeffs.at(n) = - ((2_rt*n-1) * (m-n)) * 1._rt / ((2_rt*n+1) * (m+n)) * coeffs.at(n-1); - } - } - - return coeffs; -} - -void WarpX::ReorderFornbergCoefficients (amrex::Vector& ordered_coeffs, - amrex::Vector& unordered_coeffs, - const int order) -{ - const int n = order / 2; - for (int i = 0; i < n; i++) { - ordered_coeffs[i] = unordered_coeffs[n-1-i]; - } - for (int i = n; i < order; i++) { - ordered_coeffs[i] = unordered_coeffs[i-n]; - } -} - void WarpX::AllocateCenteringCoefficients (amrex::Gpu::DeviceVector& device_centering_stencil_coeffs_x, amrex::Gpu::DeviceVector& device_centering_stencil_coeffs_y, amrex::Gpu::DeviceVector& device_centering_stencil_coeffs_z, @@ -3190,9 +3200,9 @@ void WarpX::AllocateCenteringCoefficients (amrex::Gpu::DeviceVector amrex::Vector host_centering_stencil_coeffs_y; amrex::Vector host_centering_stencil_coeffs_z; - Fornberg_stencil_coeffs_x = getFornbergStencilCoefficients(centering_nox, a_grid_type); - Fornberg_stencil_coeffs_y = getFornbergStencilCoefficients(centering_noy, a_grid_type); - Fornberg_stencil_coeffs_z = getFornbergStencilCoefficients(centering_noz, a_grid_type); + Fornberg_stencil_coeffs_x = ablastr::math::getFornbergStencilCoefficients(centering_nox, a_grid_type); + Fornberg_stencil_coeffs_y = ablastr::math::getFornbergStencilCoefficients(centering_noy, a_grid_type); + Fornberg_stencil_coeffs_z = ablastr::math::getFornbergStencilCoefficients(centering_noz, a_grid_type); host_centering_stencil_coeffs_x.resize(centering_nox); host_centering_stencil_coeffs_y.resize(centering_noy); @@ -3200,12 +3210,21 @@ void WarpX::AllocateCenteringCoefficients (amrex::Gpu::DeviceVector // Re-order Fornberg stencil coefficients: // example for order 6: (c_0,c_1,c_2) becomes (c_2,c_1,c_0,c_0,c_1,c_2) - ReorderFornbergCoefficients(host_centering_stencil_coeffs_x, - Fornberg_stencil_coeffs_x, centering_nox); - ReorderFornbergCoefficients(host_centering_stencil_coeffs_y, - Fornberg_stencil_coeffs_y, centering_noy); - ReorderFornbergCoefficients(host_centering_stencil_coeffs_z, - Fornberg_stencil_coeffs_z, centering_noz); + ablastr::math::ReorderFornbergCoefficients( + host_centering_stencil_coeffs_x, + Fornberg_stencil_coeffs_x, + centering_nox + ); + ablastr::math::ReorderFornbergCoefficients( + host_centering_stencil_coeffs_y, + Fornberg_stencil_coeffs_y, + centering_noy + ); + ablastr::math::ReorderFornbergCoefficients( + host_centering_stencil_coeffs_z, + Fornberg_stencil_coeffs_z, + centering_noz + ); // Device vectors of stencil coefficients used for finite-order centering @@ -3281,14 +3300,6 @@ WarpX::isAnyParticleBoundaryThermal () return false; } -std::string -TagWithLevelSuffix (std::string name, int const level) -{ - // Add the suffix "[level=level]" - name.append("[level=").append(std::to_string(level)).append("]"); - return name; -} - void WarpX::AllocInitMultiFab ( std::unique_ptr& mf, @@ -3300,7 +3311,8 @@ WarpX::AllocInitMultiFab ( const std::string& name, std::optional initial_value) { - const auto name_with_suffix = TagWithLevelSuffix(name, level); + // Add the suffix "[level=level]" + const auto name_with_suffix = name + "[level=" + std::to_string(level) + "]"; const auto tag = amrex::MFInfo().SetTag(name_with_suffix); mf = std::make_unique(ba, dm, ncomp, ngrow, tag); if (initial_value) { @@ -3336,40 +3348,25 @@ WarpX::MakeDistributionMap (int lev, amrex::BoxArray const& ba) } const amrex::iMultiFab* -WarpX::getFieldDotMaskPointer ( FieldType field_type, int lev, int dir ) const +WarpX::getFieldDotMaskPointer ( FieldType field_type, int lev, ablastr::fields::Direction dir ) const { + const auto periodicity = Geom(lev).periodicity(); switch(field_type) { case FieldType::Efield_fp : - SetDotMask( Efield_dotMask[lev][dir], "Efield_fp", lev, dir ); + ::SetDotMask( Efield_dotMask[lev][dir], m_fields.get("Efield_fp", dir, lev), periodicity); return Efield_dotMask[lev][dir].get(); case FieldType::Bfield_fp : - SetDotMask( Bfield_dotMask[lev][dir], "Bfield_fp", lev, dir ); + ::SetDotMask( Bfield_dotMask[lev][dir], m_fields.get("Bfield_fp", dir, lev), periodicity); return Bfield_dotMask[lev][dir].get(); case FieldType::vector_potential_fp : - SetDotMask( Afield_dotMask[lev][dir], "vector_potential_fp", lev, dir ); + ::SetDotMask( Afield_dotMask[lev][dir], m_fields.get("vector_potential_fp", dir, lev), periodicity); return Afield_dotMask[lev][dir].get(); case FieldType::phi_fp : - SetDotMask( phi_dotMask[lev], "phi_fp", lev, 0 ); + ::SetDotMask( phi_dotMask[lev], m_fields.get("phi_fp", dir, lev), periodicity); return phi_dotMask[lev].get(); default: WARPX_ABORT_WITH_MESSAGE("Invalid field type for dotMask"); return Efield_dotMask[lev][dir].get(); } } - -void WarpX::SetDotMask( std::unique_ptr& field_dotMask, - std::string const & field_name, int lev, int dir ) const -{ - // Define the dot mask for this field_type needed to properly compute dotProduct() - // for field values that have shared locations on different MPI ranks - if (field_dotMask != nullptr) { return; } - - ablastr::fields::ConstVectorField const& this_field = m_fields.get_alldirs(field_name,lev); - const amrex::BoxArray& this_ba = this_field[dir]->boxArray(); - const amrex::MultiFab tmp( this_ba, this_field[dir]->DistributionMap(), - 1, 0, amrex::MFInfo().SetAlloc(false) ); - const amrex::Periodicity& period = Geom(lev).periodicity(); - field_dotMask = tmp.OwnerMask(period); - -} diff --git a/Source/ablastr/fields/EffectivePotentialPoissonSolver.H b/Source/ablastr/fields/EffectivePotentialPoissonSolver.H new file mode 100644 index 00000000000..80e899df027 --- /dev/null +++ b/Source/ablastr/fields/EffectivePotentialPoissonSolver.H @@ -0,0 +1,274 @@ +/* Copyright 2024 The WarpX Community + * + * This file is part of WarpX. + * + * Authors: Roelof Groenewald (TAE Technologies) + * + * License: BSD-3-Clause-LBNL + */ +/* + * This file was copied and edited from PoissonSolver.H in the same directory. + */ +#ifndef ABLASTR_EFFECTIVE_POTENTIAL_POISSON_SOLVER_H +#define ABLASTR_EFFECTIVE_POTENTIAL_POISSON_SOLVER_H + +#include +#include +#include +#include +#include +#include +#include +#include "PoissonSolver.H" + +#if defined(WARPX_USE_FFT) && defined(WARPX_DIM_3D) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef AMREX_USE_EB +# include +#endif + +#include +#include + + +namespace ablastr::fields { + +/** Compute the potential `phi` by solving the Poisson equation with a modifed dielectric function + * + * Uses `rho` as a source. This uses the AMReX solver. + * + * More specifically, this solves the equation + * \f[ + * \nabla \cdot \sigma \nabla \phi = - \rho/\epsilon_0 + * \f] + * + * \tparam T_PostPhiCalculationFunctor a calculation per level directly after phi was calculated + * \tparam T_BoundaryHandler handler for boundary conditions, for example @see ElectrostaticSolver::PoissonBoundaryHandler + * \tparam T_FArrayBoxFactory usually nothing or an amrex::EBFArrayBoxFactory (EB ONLY) + * \param[in] rho The charge density a given species + * \param[out] phi The potential to be computed by this function + * \param[in] sigma The matrix representing the mass operator used to lower the local plasma frequency + * \param[in] relative_tolerance The relative convergence threshold for the MLMG solver + * \param[in] absolute_tolerance The absolute convergence threshold for the MLMG solver + * \param[in] max_iters The maximum number of iterations allowed for the MLMG solver + * \param[in] verbosity The verbosity setting for the MLMG solver + * \param[in] geom the geometry per level (e.g., from AmrMesh) + * \param[in] dmap the distribution mapping per level (e.g., from AmrMesh) + * \param[in] grids the grids per level (e.g., from AmrMesh) + * \param[in] is_solver_igf_on_lev0 boolean to select the Poisson solver: 1 for FFT on level 0 & Multigrid on other levels, 0 for Multigrid on all levels + * \param[in] do_single_precision_comms perform communications in single precision + * \param[in] rel_ref_ratio mesh refinement ratio between levels (default: 1) + * \param[in] post_phi_calculation perform a calculation per level directly after phi was calculated; required for embedded boundaries (default: none) + * \param[in] boundary_handler a handler for boundary conditions, for example @see ElectrostaticSolver::PoissonBoundaryHandler + * \param[in] current_time the current time; required for embedded boundaries (default: none) + * \param[in] eb_farray_box_factory a factory for field data, @see amrex::EBFArrayBoxFactory; required for embedded boundaries (default: none) + */ +template< + typename T_PostPhiCalculationFunctor = std::nullopt_t, + typename T_BoundaryHandler = std::nullopt_t, + typename T_FArrayBoxFactory = void +> +void +computeEffectivePotentialPhi ( + ablastr::fields::MultiLevelScalarField const& rho, + ablastr::fields::MultiLevelScalarField const& phi, + amrex::MultiFab const & sigma, + amrex::Real relative_tolerance, + amrex::Real absolute_tolerance, + int max_iters, + int verbosity, + amrex::Vector const& geom, + amrex::Vector const& dmap, + amrex::Vector const& grids, + [[maybe_unused]] utils::enums::GridType grid_type, + bool is_solver_igf_on_lev0, + bool eb_enabled = false, + bool do_single_precision_comms = false, + std::optional > rel_ref_ratio = std::nullopt, + [[maybe_unused]] T_PostPhiCalculationFunctor post_phi_calculation = std::nullopt, + [[maybe_unused]] T_BoundaryHandler const boundary_handler = std::nullopt, + [[maybe_unused]] std::optional current_time = std::nullopt, // only used for EB + [[maybe_unused]] std::optional > eb_farray_box_factory = std::nullopt // only used for EB +) { + using namespace amrex::literals; + + ABLASTR_PROFILE("computeEffectivePotentialPhi"); + + if (!rel_ref_ratio.has_value()) { + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE(rho.size() == 1u, + "rel_ref_ratio must be set if mesh-refinement is used"); + rel_ref_ratio = amrex::Vector{{amrex::IntVect(AMREX_D_DECL(1, 1, 1))}}; + } + +#if !defined(AMREX_USE_EB) + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE(!eb_enabled, + "Embedded boundary solve requested but not compiled in"); +#endif + if (eb_enabled && std::is_same_v) { + throw std::runtime_error("EB requested by eb_farray_box_factory not provided!"); + } + + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE( !is_solver_igf_on_lev0, + "FFT solver cannot be used with effective potential Poisson solve"); + +#ifdef WARPX_DIM_RZ + constexpr bool is_rz = true; +#else + constexpr bool is_rz = false; +#endif + + auto const finest_level = static_cast(rho.size() - 1); + + // determine if rho is zero everywhere + const amrex::Real max_norm_b = getMaxNormRho( + amrex::GetVecOfConstPtrs(rho), finest_level, absolute_tolerance); + + const amrex::LPInfo info; + + for (int lev=0; lev<=finest_level; lev++) { + + // Use the Multigrid (MLMG) solver but first scale rho appropriately + using namespace ablastr::constant::SI; + rho[lev]->mult(-1._rt/ep0); + + std::unique_ptr linop; + // In the presence of EB or RZ the EB enabled linear solver is used + if (eb_enabled) + { +#if defined(AMREX_USE_EB) + auto linop_nodelap = std::make_unique(); + linop_nodelap->define( + amrex::Vector{geom[lev]}, + amrex::Vector{grids[lev]}, + amrex::Vector{dmap[lev]}, + info, + amrex::Vector{eb_farray_box_factory.value()[lev]} + ); + if constexpr (!std::is_same_v) { + // if the EB potential only depends on time, the potential can be passed + // as a float instead of a callable + if (boundary_handler.phi_EB_only_t) { + linop_nodelap->setEBDirichlet(boundary_handler.potential_eb_t(current_time.value())); + } else { + linop_nodelap->setEBDirichlet(boundary_handler.getPhiEB(current_time.value())); + } + } + linop_nodelap->setSigma(lev, sigma); + linop = std::move(linop_nodelap); +#endif + } + else if (is_rz) + { + auto linop_nodelap = std::make_unique(); + linop_nodelap->define( + amrex::Vector{geom[lev]}, + amrex::Vector{grids[lev]}, + amrex::Vector{dmap[lev]}, + info + ); + linop_nodelap->setRZ(true); + linop_nodelap->setSigma(lev, sigma); + linop = std::move(linop_nodelap); + } + else + { + auto linop_nodelap = std::make_unique(); + linop_nodelap->define( + amrex::Vector{geom[lev]}, + amrex::Vector{grids[lev]}, + amrex::Vector{dmap[lev]}, + info + ); + linop_nodelap->setSigma(lev, sigma); + linop = std::move(linop_nodelap); + } + + // Set domain boundary conditions + if constexpr (std::is_same_v) { + amrex::Array const lobc = {AMREX_D_DECL( + amrex::LinOpBCType::Dirichlet, + amrex::LinOpBCType::Dirichlet, + amrex::LinOpBCType::Dirichlet + )}; + amrex::Array const hibc = lobc; + linop->setDomainBC(lobc, hibc); + } else { + linop->setDomainBC(boundary_handler.lobc, boundary_handler.hibc); + } + + // Solve the Poisson equation + amrex::MLMG mlmg(*linop); // actual solver defined here + mlmg.setVerbose(verbosity); + mlmg.setMaxIter(max_iters); + mlmg.setAlwaysUseBNorm((max_norm_b > 0)); + + const int ng = int(grid_type == utils::enums::GridType::Collocated); // ghost cells + if (ng) { + // In this case, computeE needs to use ghost nodes data. So we + // ask MLMG to fill BC for us after it solves the problem. + mlmg.setFinalFillBC(true); + } + + // Solve Poisson equation at lev + mlmg.solve( {phi[lev]}, {rho[lev]}, + relative_tolerance, absolute_tolerance ); + + // needed for solving the levels by levels: + // - coarser level is initial guess for finer level + // - coarser level provides boundary values for finer level patch + // Interpolation from phi[lev] to phi[lev+1] + // (This provides both the boundary conditions and initial guess for phi[lev+1]) + if (lev < finest_level) { + const amrex::IntVect& refratio = rel_ref_ratio.value()[lev]; + const int ncomp = linop->getNComp(); + interpolatePhiBetweenLevels(phi[lev], + phi[lev+1], + geom[lev], + do_single_precision_comms, + refratio, + ncomp, + ng); + } + + // Run additional operations, such as calculation of the E field for embedded boundaries + if constexpr (!std::is_same_v) { + if (post_phi_calculation.has_value()) { + post_phi_calculation.value()(mlmg, lev); + } + } + rho[lev]->mult(-ep0); // Multiply rho by epsilon again + } // loop over lev(els) +} + +} // namespace ablastr::fields + +#endif // ABLASTR_EFFECTIVE_POTENTIAL_POISSON_SOLVER_H diff --git a/Source/ablastr/fields/IntegratedGreenFunctionSolver.H b/Source/ablastr/fields/IntegratedGreenFunctionSolver.H old mode 100644 new mode 100755 index 28885e167a3..b34678055a8 --- a/Source/ablastr/fields/IntegratedGreenFunctionSolver.H +++ b/Source/ablastr/fields/IntegratedGreenFunctionSolver.H @@ -15,13 +15,14 @@ #include #include - #include #include namespace ablastr::fields { + using namespace amrex::literals; + /** @brief Implements equation 2 in https://doi.org/10.1103/PhysRevSTAB.10.129901 * with some modification to symmetrize the function. @@ -30,54 +31,92 @@ namespace ablastr::fields * @param[in] y y-coordinate of given location * @param[in] z z-coordinate of given location * - * @return the integrated Green function G + * @return the integrated Green function G in 3D */ AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real - IntegratedPotential (amrex::Real x, amrex::Real y, amrex::Real z) + IntegratedPotential3D (amrex::Real x, amrex::Real y, amrex::Real z) { - using namespace amrex::literals; - amrex::Real const r = std::sqrt( x*x + y*y + z*z ); - amrex::Real const G = - - 0.5_rt * z*z * std::atan( x*y/(z*r) ) - - 0.5_rt * y*y * std::atan( x*z/(y*r) ) - - 0.5_rt * x*x * std::atan( y*z/(x*r) ) - + y*z*std::asinh( x/std::sqrt(y*y + z*z) ) - + x*z*std::asinh( y/std::sqrt(x*x + z*z) ) - + x*y*std::asinh( z/std::sqrt(x*x + y*y) ); + amrex::Real const G = - 0.5_rt * z*z * std::atan( x*y/(z*r) ) + - 0.5_rt * y*y * std::atan( x*z/(y*r) ) + - 0.5_rt * x*x * std::atan( y*z/(x*r) ) + + y*z*std::asinh( x/std::sqrt(y*y + z*z) ) + + x*z*std::asinh( y/std::sqrt(x*x + z*z) ) + + x*y*std::asinh( z/std::sqrt(x*x + y*y) ); + return G; + } + + + /** @brief Implements equation 58 in https://doi.org/10.1016/j.jcp.2004.01.008 + * + * @param[in] x x-coordinate of given location + * @param[in] y y-coordinate of given location + * + * @return the integrated Green function G in 2D + */ + AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE + amrex::Real + IntegratedPotential2D (amrex::Real x, amrex::Real y) + { + amrex::Real const G = 3_rt*x*y + - x*x * std::atan(y/x) + - y*y * std::atan(x/y) + - x*y * std::log(x*x + y*y); return G; } + /** @brief add * * @param[in] x x-coordinate of given location * @param[in] y y-coordinate of given location * @param[in] z z-coordinate of given location + * @param[in] dx cell size along x + * @param[in] dy cell size along y + * @param[in] dz cell size along z * - * @return the sum of integrated Green function G + * @return the sum of integrated Green function G in 3D */ AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real - SumOfIntegratedPotential (amrex::Real x, amrex::Real y, amrex::Real z, amrex::Real dx, amrex::Real dy, amrex::Real dz) + SumOfIntegratedPotential3D (amrex::Real x, amrex::Real y, amrex::Real z, amrex::Real dx, amrex::Real dy, amrex::Real dz) { - using namespace amrex::literals; - + return 1._rt/(4._rt*ablastr::constant::math::pi*ablastr::constant::SI::ep0) * ( + IntegratedPotential3D( x+0.5_rt*dx, y+0.5_rt*dy, z+0.5_rt*dz ) + - IntegratedPotential3D( x-0.5_rt*dx, y+0.5_rt*dy, z+0.5_rt*dz ) + - IntegratedPotential3D( x+0.5_rt*dx, y-0.5_rt*dy, z+0.5_rt*dz ) + + IntegratedPotential3D( x-0.5_rt*dx, y-0.5_rt*dy, z+0.5_rt*dz ) + - IntegratedPotential3D( x+0.5_rt*dx, y+0.5_rt*dy, z-0.5_rt*dz ) + + IntegratedPotential3D( x-0.5_rt*dx, y+0.5_rt*dy, z-0.5_rt*dz ) + + IntegratedPotential3D( x+0.5_rt*dx, y-0.5_rt*dy, z-0.5_rt*dz ) + - IntegratedPotential3D( x-0.5_rt*dx, y-0.5_rt*dy, z-0.5_rt*dz ) + ); + } - amrex::Real const G_value = 1._rt/(4._rt*ablastr::constant::math::pi*ablastr::constant::SI::ep0) * ( - IntegratedPotential( x+0.5_rt*dx, y+0.5_rt*dy, z+0.5_rt*dz ) - - IntegratedPotential( x-0.5_rt*dx, y+0.5_rt*dy, z+0.5_rt*dz ) - - IntegratedPotential( x+0.5_rt*dx, y-0.5_rt*dy, z+0.5_rt*dz ) - + IntegratedPotential( x-0.5_rt*dx, y-0.5_rt*dy, z+0.5_rt*dz ) - - IntegratedPotential( x+0.5_rt*dx, y+0.5_rt*dy, z-0.5_rt*dz ) - + IntegratedPotential( x-0.5_rt*dx, y+0.5_rt*dy, z-0.5_rt*dz ) - + IntegratedPotential( x+0.5_rt*dx, y-0.5_rt*dy, z-0.5_rt*dz ) - - IntegratedPotential( x-0.5_rt*dx, y-0.5_rt*dy, z-0.5_rt*dz ) - ); - return G_value; + /** @brief add + * + * @param[in] x x-coordinate of given location + * @param[in] y y-coordinate of given location + * @param[in] dx cell size along x + * @param[in] dy cell size along y + * + * @return the sum of integrated Green function G in 2D + */ + AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE + amrex::Real + SumOfIntegratedPotential2D (amrex::Real x, amrex::Real y, amrex::Real dx, amrex::Real dy) + { + return 1._rt/(4._rt*ablastr::constant::math::pi*ablastr::constant::SI::ep0) * ( + IntegratedPotential2D( x+0.5_rt*dx, y+0.5_rt*dy ) + - IntegratedPotential2D( x+0.5_rt*dx, y-0.5_rt*dy ) + - IntegratedPotential2D( x-0.5_rt*dx, y+0.5_rt*dy ) + + IntegratedPotential2D( x-0.5_rt*dx, y-0.5_rt*dy ) + ); } + /** @brief Compute the electrostatic potential using the Integrated Green Function method * as in http://dx.doi.org/10.1103/PhysRevSTAB.9.044204 * @@ -85,12 +124,14 @@ namespace ablastr::fields * @param[out] phi the electrostatic potential amrex::MultiFab * @param[in] cell_size an arreay of 3 reals dx dy dz * @param[in] ba amrex::BoxArray with the grid of a given level + * @param[in] is_igf_2d boolean to select between fully 3D Poisson solver and quasi-3D, i.e. one 2D Poisson solve on every z slice (default: false) */ void computePhiIGF (amrex::MultiFab const & rho, amrex::MultiFab & phi, std::array const & cell_size, - amrex::BoxArray const & ba); + amrex::BoxArray const & ba, + bool is_igf_2d_slices); } // namespace ablastr::fields diff --git a/Source/ablastr/fields/IntegratedGreenFunctionSolver.cpp b/Source/ablastr/fields/IntegratedGreenFunctionSolver.cpp old mode 100644 new mode 100755 index 40b36740ae5..31d8136e175 --- a/Source/ablastr/fields/IntegratedGreenFunctionSolver.cpp +++ b/Source/ablastr/fields/IntegratedGreenFunctionSolver.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include @@ -18,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -25,27 +25,20 @@ #include #include #include +#include #include -#if defined(ABLASTR_USE_FFT) && defined(ABLASTR_USE_HEFFTE) -#include -#endif - - namespace ablastr::fields { void computePhiIGF ( amrex::MultiFab const & rho, amrex::MultiFab & phi, std::array const & cell_size, - amrex::BoxArray const & ba) + amrex::BoxArray const & ba, + bool const is_igf_2d_slices) { using namespace amrex::literals; - BL_PROFILE_VAR_NS("ablastr::fields::computePhiIGF: FFTs", timer_ffts); - BL_PROFILE_VAR_NS("ablastr::fields::computePhiIGF: FFT plans", timer_plans); - BL_PROFILE_VAR_NS("ablastr::fields::computePhiIGF: parallel copies", timer_pcopies); - BL_PROFILE("ablastr::fields::computePhiIGF"); // Define box that encompasses the full domain @@ -53,240 +46,60 @@ computePhiIGF ( amrex::MultiFab const & rho, domain.surroundingNodes(); // get nodal points, since `phi` and `rho` are nodal domain.grow( phi.nGrowVect() ); // include guard cells - int const nx = domain.length(0); - int const ny = domain.length(1); - int const nz = domain.length(2); - - // Allocate 2x wider arrays for the convolution of rho with the Green function - amrex::Box const realspace_box = amrex::Box( - {domain.smallEnd(0), domain.smallEnd(1), domain.smallEnd(2)}, - {2*nx-1+domain.smallEnd(0), 2*ny-1+domain.smallEnd(1), 2*nz-1+domain.smallEnd(2)}, - amrex::IntVect::TheNodeVector() ); - -#if !defined(ABLASTR_USE_HEFFTE) - // Without distributed FFTs (i.e. without heFFTe): - // allocate the 2x wider array on a single box - amrex::BoxArray const realspace_ba = amrex::BoxArray( realspace_box ); - // Define a distribution mapping for the global FFT, with only one box - amrex::DistributionMapping dm_global_fft; - dm_global_fft.define( realspace_ba ); -#elif defined(ABLASTR_USE_HEFFTE) - // With distributed FFTs (i.e. with heFFTe): - // Define a new distribution mapping which is decomposed purely along z - // and has one box per MPI rank - int const nprocs = amrex::ParallelDescriptor::NProcs(); - amrex::BoxArray realspace_ba; - amrex::DistributionMapping dm_global_fft; + int nprocs = amrex::ParallelDescriptor::NProcs(); { - int realspace_nx = realspace_box.length(0); - int realspace_ny = realspace_box.length(1); - int realspace_nz = realspace_box.length(2); - int minsize_z = realspace_nz / nprocs; - int nleft_z = realspace_nz - minsize_z*nprocs; - - AMREX_ALWAYS_ASSERT(realspace_nz >= nprocs); - // We are going to split realspace_box in such a way that the first - // nleft boxes has minsize_z+1 nodes and the others minsize - // nodes. We do it this way instead of BoxArray::maxSize to make - // sure there are exactly nprocs boxes and there are no overlaps. - amrex::BoxList bl(amrex::IndexType::TheNodeType()); - for (int iproc = 0; iproc < nprocs; ++iproc) { - int zlo, zhi; - if (iproc < nleft_z) { - zlo = iproc*(minsize_z+1); - zhi = zlo + minsize_z; - - } else { - zlo = iproc*minsize_z + nleft_z; - zhi = zlo + minsize_z - 1; - - } - amrex::Box tbx(amrex::IntVect(0,0,zlo),amrex::IntVect(realspace_nx-1,realspace_ny-1,zhi),amrex::IntVect(1)); - - tbx.shift(realspace_box.smallEnd()); - bl.push_back(tbx); - } - realspace_ba.define(std::move(bl)); - amrex::Vector pmap(nprocs); - std::iota(pmap.begin(), pmap.end(), 0); - dm_global_fft.define(std::move(pmap)); + amrex::ParmParse pp("ablastr"); + pp.queryAdd("nprocs_igf_fft", nprocs); + nprocs = std::max(1,std::min(nprocs, amrex::ParallelDescriptor::NProcs())); } -#endif - - // Allocate required arrays - amrex::MultiFab tmp_rho = amrex::MultiFab(realspace_ba, dm_global_fft, 1, 0); - tmp_rho.setVal(0); - amrex::MultiFab tmp_G = amrex::MultiFab(realspace_ba, dm_global_fft, 1, 0); - tmp_G.setVal(0); - - BL_PROFILE_VAR_START(timer_pcopies); - // Copy from rho including its ghost cells to tmp_rho - tmp_rho.ParallelCopy( rho, 0, 0, 1, amrex::IntVect::TheZeroVector(), amrex::IntVect::TheZeroVector() ); - BL_PROFILE_VAR_STOP(timer_pcopies); - -#if !defined(ABLASTR_USE_HEFFTE) - // Without distributed FFTs (i.e. without heFFTe): - // We loop over the original box (not the 2x wider one), and the other quadrants by periodicity - amrex::BoxArray const& igf_compute_box = amrex::BoxArray( domain ); -#else - // With distributed FFTs (i.e. with heFFTe): - // We loop over the full 2x wider box, since 1 MPI rank does not necessarily own the data for the other quadrants - amrex::BoxArray const& igf_compute_box = tmp_G.boxArray(); -#endif - // Compute the integrated Green function -#ifdef AMREX_USE_OMP -#pragma omp parallel if (amrex::Gpu::notInLaunchRegion()) -#endif - for (amrex::MFIter mfi(igf_compute_box, dm_global_fft, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) { - - amrex::Box const bx = mfi.tilebox(); - - amrex::IntVect const lo = realspace_box.smallEnd(); - amrex::IntVect const hi = realspace_box.bigEnd(); - - // Fill values of the Green function - amrex::Real const dx = cell_size[0]; - amrex::Real const dy = cell_size[1]; - amrex::Real const dz = cell_size[2]; - - amrex::Array4 const tmp_G_arr = tmp_G.array(mfi); - amrex::ParallelFor( bx, - [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept - { - int const i0 = i - lo[0]; - int const j0 = j - lo[1]; - int const k0 = k - lo[2]; - amrex::Real const x = i0*dx; - amrex::Real const y = j0*dy; - amrex::Real const z = k0*dz; - -#if !defined(ABLASTR_USE_HEFFTE) - // Without distributed FFTs (i.e. without heFFTe): - amrex::Real const G_value = SumOfIntegratedPotential(x , y , z , dx, dy, dz); - tmp_G_arr(i,j,k) = G_value; - // Fill the rest of the array by periodicity - if (i0>0) {tmp_G_arr(hi[0]+1-i0, j , k ) = G_value;} - if (j0>0) {tmp_G_arr(i , hi[1]+1-j0, k ) = G_value;} - if (k0>0) {tmp_G_arr(i , j , hi[2]+1-k0) = G_value;} - if ((i0>0)&&(j0>0)) {tmp_G_arr(hi[0]+1-i0, hi[1]+1-j0, k ) = G_value;} - if ((j0>0)&&(k0>0)) {tmp_G_arr(i , hi[1]+1-j0, hi[2]+1-k0) = G_value;} - if ((i0>0)&&(k0>0)) {tmp_G_arr(hi[0]+1-i0, j , hi[2]+1-k0) = G_value;} - if ((i0>0)&&(j0>0)&&(k0>0)) {tmp_G_arr(hi[0]+1-i0, hi[1]+1-j0, hi[2]+1-k0) = G_value;} -#else - // With distributed FFTs (i.e. with heFFTe): - amrex::Real x_hi = dx*(hi[0]+2); - amrex::Real y_hi = dy*(hi[1]+2); - amrex::Real z_hi = dz*(hi[2]+2); - if ((i0< nx)&&(j0< ny)&&(k0< nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x , y , z , dx, dy, dz); } - if ((i0< nx)&&(j0> ny)&&(k0< nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x , y_hi-y, z , dx, dy, dz); } - if ((i0< nx)&&(j0< ny)&&(k0> nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x , y , z_hi-z, dx, dy, dz); } - if ((i0> nx)&&(j0> ny)&&(k0< nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x_hi-x, y_hi-y, z , dx, dy, dz); } - if ((i0< nx)&&(j0> ny)&&(k0> nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x , y_hi-y, z_hi-z, dx, dy, dz); } - if ((i0> nx)&&(j0< ny)&&(k0> nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x_hi-x, y , z_hi-z, dx, dy, dz); } - if ((i0> nx)&&(j0> ny)&&(k0> nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x_hi-x, y_hi-y, z_hi-z, dx, dy, dz); } - if ((i0> nx)&&(j0< ny)&&(k0< nz)) { tmp_G_arr(i,j,k) = SumOfIntegratedPotential(x_hi-x, y , z , dx, dy, dz); } -#endif - } - ); + static std::unique_ptr> obc_solver; + if (!obc_solver) { + amrex::ExecOnFinalize([&] () { obc_solver.reset(); }); + } + if (!obc_solver || obc_solver->Domain() != domain) { + amrex::FFT::Info info{}; + if (is_igf_2d_slices) { info.setTwoDMode(true); } // do 2D FFTs + info.setNumProcs(nprocs); + obc_solver = std::make_unique>(domain, info); } - // Prepare to perform global FFT - // Since there is 1 MPI rank per box, here each MPI rank obtains its local box and the associated boxid - const int local_boxid = amrex::ParallelDescriptor::MyProc(); // because of how we made the DistributionMapping - if (local_boxid < realspace_ba.size()) { - // When not using heFFTe, there is only one box (the global box) - // It is taken care of my MPI rank 0 ; other ranks have no work (hence the if condition) - - const amrex::Box local_nodal_box = realspace_ba[local_boxid]; - amrex::Box local_box(local_nodal_box.smallEnd(), local_nodal_box.bigEnd()); - local_box.shift(-realspace_box.smallEnd()); // This simplifies the setup because the global lo is zero now - // Since we the domain decompostion is in the z-direction, setting up c_local_box is simple. - amrex::Box c_local_box = local_box; - c_local_box.setBig(0, local_box.length(0)/2+1); - - // Allocate array in spectral space - using SpectralField = amrex::BaseFab< amrex::GpuComplex< amrex::Real > > ; - SpectralField tmp_rho_fft(c_local_box, 1, amrex::The_Device_Arena()); - SpectralField tmp_G_fft(c_local_box, 1, amrex::The_Device_Arena()); - tmp_rho_fft.shift(realspace_box.smallEnd()); - tmp_G_fft.shift(realspace_box.smallEnd()); - - // Create FFT plans - BL_PROFILE_VAR_START(timer_plans); -#if !defined(ABLASTR_USE_HEFFTE) - const amrex::IntVect fft_size = realspace_ba[local_boxid].length(); - ablastr::math::anyfft::FFTplan forward_plan_rho = ablastr::math::anyfft::CreatePlan( - fft_size, tmp_rho[local_boxid].dataPtr(), - reinterpret_cast(tmp_rho_fft.dataPtr()), - ablastr::math::anyfft::direction::R2C, AMREX_SPACEDIM); - ablastr::math::anyfft::FFTplan forward_plan_G = ablastr::math::anyfft::CreatePlan( - fft_size, tmp_G[local_boxid].dataPtr(), - reinterpret_cast(tmp_G_fft.dataPtr()), - ablastr::math::anyfft::direction::R2C, AMREX_SPACEDIM); - ablastr::math::anyfft::FFTplan backward_plan = ablastr::math::anyfft::CreatePlan( - fft_size, tmp_G[local_boxid].dataPtr(), - reinterpret_cast( tmp_G_fft.dataPtr()), - ablastr::math::anyfft::direction::C2R, AMREX_SPACEDIM); -#elif defined(ABLASTR_USE_HEFFTE) -#if defined(AMREX_USE_CUDA) - heffte::fft3d_r2c fft -#elif defined(AMREX_USE_HIP) - heffte::fft3d_r2c fft -#else - heffte::fft3d_r2c fft -#endif - ({{local_box.smallEnd(0), local_box.smallEnd(1), local_box.smallEnd(2)}, - {local_box.bigEnd(0), local_box.bigEnd(1), local_box.bigEnd(2)}}, - {{c_local_box.smallEnd(0), c_local_box.smallEnd(1), c_local_box.smallEnd(2)}, - {c_local_box.bigEnd(0), c_local_box.bigEnd(1), c_local_box.bigEnd(2)}}, - 0, amrex::ParallelDescriptor::Communicator()); - using heffte_complex = typename heffte::fft_output::type; - heffte_complex* rho_fft_data = (heffte_complex*) tmp_rho_fft.dataPtr(); - heffte_complex* G_fft_data = (heffte_complex*) tmp_G_fft.dataPtr(); -#endif - BL_PROFILE_VAR_STOP(timer_plans); - - // Perform forward FFTs - BL_PROFILE_VAR_START(timer_ffts); -#if !defined(ABLASTR_USE_HEFFTE) - ablastr::math::anyfft::Execute(forward_plan_rho); - ablastr::math::anyfft::Execute(forward_plan_G); -#elif defined(ABLASTR_USE_HEFFTE) - fft.forward(tmp_rho[local_boxid].dataPtr(), rho_fft_data); - fft.forward(tmp_G[local_boxid].dataPtr(), G_fft_data); -#endif - BL_PROFILE_VAR_STOP(timer_ffts); - - // Multiply tmp_G_fft and tmp_rho_fft in spectral space - // Store the result in-place in Gtmp_G_fft, to save memory - tmp_G_fft.template mult(tmp_rho_fft, 0, 0, 1); - amrex::Gpu::streamSynchronize(); - - // Perform backward FFT - BL_PROFILE_VAR_START(timer_ffts); -#if !defined(ABLASTR_USE_HEFFTE) - ablastr::math::anyfft::Execute(backward_plan); -#elif defined(ABLASTR_USE_HEFFTE) - fft.backward(G_fft_data, tmp_G[local_boxid].dataPtr()); -#endif - BL_PROFILE_VAR_STOP(timer_ffts); + auto const& lo = domain.smallEnd(); + amrex::Real const dx = cell_size[0]; + amrex::Real const dy = cell_size[1]; + amrex::Real const dz = cell_size[2]; + + if (!is_igf_2d_slices){ + // fully 3D solver + obc_solver->setGreensFunction( + [=] AMREX_GPU_DEVICE (int i, int j, int k) -> amrex::Real + { + int const i0 = i - lo[0]; + int const j0 = j - lo[1]; + int const k0 = k - lo[2]; + amrex::Real const x = i0*dx; + amrex::Real const y = j0*dy; + amrex::Real const z = k0*dz; + + return SumOfIntegratedPotential3D(x, y, z, dx, dy, dz); + }); + }else{ + // 2D sliced solver + obc_solver->setGreensFunction( + [=] AMREX_GPU_DEVICE (int i, int j, int k) -> amrex::Real + { + int const i0 = i - lo[0]; + int const j0 = j - lo[1]; + amrex::Real const x = i0*dx; + amrex::Real const y = j0*dy; + amrex::ignore_unused(k); + + return SumOfIntegratedPotential2D(x, y, dx, dy); + }); -#if !defined(ABLASTR_USE_HEFFTE) - // Loop to destroy FFT plans - ablastr::math::anyfft::DestroyPlan(forward_plan_G); - ablastr::math::anyfft::DestroyPlan(forward_plan_rho); - ablastr::math::anyfft::DestroyPlan(backward_plan); -#endif } - // Normalize, since (FFT + inverse FFT) results in a factor N - const amrex::Real normalization = 1._rt / realspace_box.numPts(); - tmp_G.mult( normalization ); + obc_solver->solve(phi, rho); +} // computePhiIGF - BL_PROFILE_VAR_START(timer_pcopies); - // Copy from tmp_G to phi - phi.ParallelCopy( tmp_G, 0, 0, 1, amrex::IntVect::TheZeroVector(), phi.nGrowVect()); - BL_PROFILE_VAR_STOP(timer_pcopies); -} } // namespace ablastr::fields diff --git a/Source/ablastr/fields/Interpolate.H b/Source/ablastr/fields/Interpolate.H index a9f0a7fc75f..dc4ad47df94 100644 --- a/Source/ablastr/fields/Interpolate.H +++ b/Source/ablastr/fields/Interpolate.H @@ -11,12 +11,9 @@ #include #include -#include - #include #include - namespace ablastr::fields::details { /** Local interpolation from phi_cp to phi[lev+1] @@ -46,9 +43,9 @@ namespace ablastr::fields::details { 0, m_refratio); } - amrex::Array4 const m_phi_fp_arr; - amrex::Array4 const m_phi_cp_arr; - amrex::IntVect const m_refratio; + amrex::Array4 m_phi_fp_arr; + amrex::Array4 m_phi_cp_arr; + amrex::IntVect m_refratio; }; } // namespace ablastr::fields::details diff --git a/Source/ablastr/fields/MultiFabRegister.H b/Source/ablastr/fields/MultiFabRegister.H index 21df20c1678..11cf932c12c 100644 --- a/Source/ablastr/fields/MultiFabRegister.H +++ b/Source/ablastr/fields/MultiFabRegister.H @@ -472,6 +472,7 @@ namespace ablastr::fields * * @param name the name of the field * @param finest_level the highest MR level to return + * @param skip_level_0 return a nullptr for level 0 * @return non-owning pointers to the MultiFab (field) on all levels */ //@{ @@ -479,24 +480,28 @@ namespace ablastr::fields [[nodiscard]] MultiLevelScalarField get_mr_levels ( T name, - int finest_level + int finest_level, + bool skip_level_0=false ) { return internal_get_mr_levels( getExtractedName(name), - finest_level + finest_level, + skip_level_0 ); } template [[nodiscard]] ConstMultiLevelScalarField get_mr_levels ( T name, - int finest_level + int finest_level, + bool skip_level_0=false ) const { return internal_get_mr_levels( getExtractedName(name), - finest_level + finest_level, + skip_level_0 ); } //@} @@ -543,6 +548,7 @@ namespace ablastr::fields * * @param name the name of the field * @param finest_level the highest MR level to return + * @param skip_level_0 return a nullptr for level 0 * @return non-owning pointers to all components of a vector field on all MR levels */ //@{ @@ -550,24 +556,28 @@ namespace ablastr::fields [[nodiscard]] MultiLevelVectorField get_mr_levels_alldirs ( T name, - int finest_level + int finest_level, + bool skip_level_0=false ) { return internal_get_mr_levels_alldirs( getExtractedName(name), - finest_level + finest_level, + skip_level_0 ); } template [[nodiscard]] ConstMultiLevelVectorField get_mr_levels_alldirs ( T name, - int finest_level + int finest_level, + bool skip_level_0=false ) const { return internal_get_mr_levels_alldirs( getExtractedName(name), - finest_level + finest_level, + skip_level_0 ); } //@} @@ -762,12 +772,14 @@ namespace ablastr::fields [[nodiscard]] MultiLevelScalarField internal_get_mr_levels ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ); [[nodiscard]] ConstMultiLevelScalarField internal_get_mr_levels ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) const; [[nodiscard]] VectorField internal_get_alldirs ( @@ -782,12 +794,14 @@ namespace ablastr::fields [[nodiscard]] MultiLevelVectorField internal_get_mr_levels_alldirs ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ); [[nodiscard]] ConstMultiLevelVectorField internal_get_mr_levels_alldirs ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) const; void diff --git a/Source/ablastr/fields/MultiFabRegister.cpp b/Source/ablastr/fields/MultiFabRegister.cpp index 2c384a90089..a1266deeab0 100644 --- a/Source/ablastr/fields/MultiFabRegister.cpp +++ b/Source/ablastr/fields/MultiFabRegister.cpp @@ -350,9 +350,7 @@ namespace ablastr::fields ) { if (m_mf_register.count(internal_name) == 0) { - // FIXME: temporary, throw a std::runtime_error - // throw std::runtime_error("MultiFabRegister::get name does not exist in register: " + key); - return nullptr; + throw std::runtime_error("MultiFabRegister::get name does not exist in register: " + internal_name); } amrex::MultiFab & mf = m_mf_register.at(internal_name).m_mf; @@ -365,9 +363,7 @@ namespace ablastr::fields ) const { if (m_mf_register.count(internal_name) == 0) { - // FIXME: temporary, throw a std::runtime_error - // throw std::runtime_error("MultiFabRegister::get name does not exist in register: " + internal_name); - return nullptr; + throw std::runtime_error("MultiFabRegister::get name does not exist in register: " + internal_name); } amrex::MultiFab const & mf = m_mf_register.at(internal_name).m_mf; @@ -419,14 +415,22 @@ namespace ablastr::fields MultiLevelScalarField MultiFabRegister::internal_get_mr_levels ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) { MultiLevelScalarField field_on_level; field_on_level.reserve(finest_level+1); for (int lvl = 0; lvl <= finest_level; lvl++) { - field_on_level.push_back(internal_get(name, lvl)); + if (lvl == 0 && skip_level_0) + { + field_on_level.push_back(nullptr); + } + else + { + field_on_level.push_back(internal_get(name, lvl)); + } } return field_on_level; } @@ -434,14 +438,22 @@ namespace ablastr::fields ConstMultiLevelScalarField MultiFabRegister::internal_get_mr_levels ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) const { ConstMultiLevelScalarField field_on_level; field_on_level.reserve(finest_level+1); for (int lvl = 0; lvl <= finest_level; lvl++) { - field_on_level.push_back(internal_get(name, lvl)); + if (lvl == 0 && skip_level_0) + { + field_on_level.push_back(nullptr); + } + else + { + field_on_level.push_back(internal_get(name, lvl)); + } } return field_on_level; } @@ -483,7 +495,8 @@ namespace ablastr::fields MultiLevelVectorField MultiFabRegister::internal_get_mr_levels_alldirs ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) { MultiLevelVectorField field_on_level; @@ -497,7 +510,14 @@ namespace ablastr::fields // insert components for (Direction const & dir : m_all_dirs) { - field_on_level[lvl][dir] = internal_get(name, dir, lvl); + if (lvl == 0 && skip_level_0) + { + field_on_level[lvl][dir] = nullptr; + } + else + { + field_on_level[lvl][dir] = internal_get(name, dir, lvl); + } } } return field_on_level; @@ -506,7 +526,8 @@ namespace ablastr::fields ConstMultiLevelVectorField MultiFabRegister::internal_get_mr_levels_alldirs ( std::string const & name, - int finest_level + int finest_level, + bool skip_level_0 ) const { ConstMultiLevelVectorField field_on_level; @@ -520,7 +541,14 @@ namespace ablastr::fields // insert components for (Direction const & dir : m_all_dirs) { - field_on_level[lvl][dir] = internal_get(name, dir, lvl); + if (lvl == 0 && skip_level_0) + { + field_on_level[lvl][dir] = nullptr; + } + else + { + field_on_level[lvl][dir] = internal_get(name, dir, lvl); + } } } return field_on_level; diff --git a/Source/ablastr/fields/PoissonSolver.H b/Source/ablastr/fields/PoissonSolver.H old mode 100644 new mode 100755 index d7eeecead1b..c79736e0d1b --- a/Source/ablastr/fields/PoissonSolver.H +++ b/Source/ablastr/fields/PoissonSolver.H @@ -178,12 +178,13 @@ inline void interpolatePhiBetweenLevels ( * \param[in] dmap the distribution mapping per level (e.g., from AmrMesh) * \param[in] grids the grids per level (e.g., from AmrMesh) * \param[in] grid_type Integer that corresponds to the type of grid used in the simulation (collocated, staggered, hybrid) - * \param[in] boundary_handler a handler for boundary conditions, for example @see ElectrostaticSolver::PoissonBoundaryHandler * \param[in] is_solver_igf_on_lev0 boolean to select the Poisson solver: 1 for FFT on level 0 & Multigrid on other levels, 0 for Multigrid on all levels + * \param[in] is_igf_2d boolean to select between fully 3D Poisson solver and quasi-3D, i.e. one 2D Poisson solve on every z slice (default: false) * \param[in] eb_enabled solve with embedded boundaries * \param[in] do_single_precision_comms perform communications in single precision * \param[in] rel_ref_ratio mesh refinement ratio between levels (default: 1) * \param[in] post_phi_calculation perform a calculation per level directly after phi was calculated; required for embedded boundaries (default: none) + * \param[in] boundary_handler a handler for boundary conditions, for example @see ElectrostaticSolver::PoissonBoundaryHandler * \param[in] current_time the current time; required for embedded boundaries (default: none) * \param[in] eb_farray_box_factory a factory for field data, @see amrex::EBFArrayBoxFactory; required for embedded boundaries (default: none) */ @@ -206,11 +207,12 @@ computePhi ( amrex::Vector const& grids, utils::enums::GridType grid_type, bool is_solver_igf_on_lev0, + [[maybe_unused]] bool const is_igf_2d, bool eb_enabled = false, bool do_single_precision_comms = false, std::optional > rel_ref_ratio = std::nullopt, [[maybe_unused]] T_PostPhiCalculationFunctor post_phi_calculation = std::nullopt, - [[maybe_unused]] T_BoundaryHandler const boundary_handler = std::nullopt, // only used for EB + [[maybe_unused]] T_BoundaryHandler const boundary_handler = std::nullopt, [[maybe_unused]] std::optional current_time = std::nullopt, // only used for EB [[maybe_unused]] std::optional > eb_farray_box_factory = std::nullopt // only used for EB ) @@ -233,13 +235,13 @@ computePhi ( #endif #if !defined(ABLASTR_USE_FFT) - ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE( !is_solver_igf_on_lev0, - "Must compile with FFT support to use the IGF solver!"); + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE( !is_solver_igf_on_lev0, + "Must compile with FFT support to use the IGF solver!"); #endif #if !defined(WARPX_DIM_3D) - ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE( !is_solver_igf_on_lev0, - "The FFT Poisson solver is currently only implemented for 3D!"); + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE( !is_solver_igf_on_lev0, + "The FFT Poisson solver is currently only implemented for 3D!"); #endif // Set the value of beta @@ -270,7 +272,7 @@ computePhi ( if ( max_norm_b == 0 ) { phi[lev]->setVal(0); } else { - computePhiIGF( *rho[lev], *phi[lev], dx_scaled, grids[lev] ); + computePhiIGF( *rho[lev], *phi[lev], dx_scaled, grids[lev], is_igf_2d); } continue; } diff --git a/Source/ablastr/fields/VectorPoissonSolver.H b/Source/ablastr/fields/VectorPoissonSolver.H index f6dd2a99cf1..16863320c1e 100644 --- a/Source/ablastr/fields/VectorPoissonSolver.H +++ b/Source/ablastr/fields/VectorPoissonSolver.H @@ -1,4 +1,4 @@ -/* Copyright 2022 S. Eric Clark, LLNL +/* Copyright 2022-2024 S. Eric Clark (Helion Energy, formerly LLNL) * * This file is part of WarpX. * @@ -110,11 +110,6 @@ computeVectorPotential ( amrex::Vector > co rel_ref_ratio = amrex::Vector{{amrex::IntVect(AMREX_D_DECL(1, 1, 1))}}; } -#if !defined(AMREX_USE_EB) - ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE(!eb_enabled, - "Embedded boundary solve requested but not compiled in"); -#endif - auto const finest_level = static_cast(curr.size()) - 1; // scale J appropriately; also determine if current is zero everywhere @@ -137,10 +132,41 @@ computeVectorPotential ( amrex::Vector > co ); } - const amrex::LPInfo& info = amrex::LPInfo(); - // Loop over dimensions of A to solve each component individually for (int lev=0; lev<=finest_level; lev++) { + amrex::LPInfo info; + +#ifdef WARPX_DIM_RZ + constexpr bool is_rz = true; +#else + constexpr bool is_rz = false; +#endif + + amrex::Array const dx + {AMREX_D_DECL(geom[lev].CellSize(0), + geom[lev].CellSize(1), + geom[lev].CellSize(2))}; + + + if (!eb_enabled && !is_rz) { + // Determine whether to use semi-coarsening + int max_semicoarsening_level = 0; + int semicoarsening_direction = -1; + const auto min_dir = static_cast(std::distance(dx.begin(), + std::min_element(dx.begin(), dx.end()))); + const auto max_dir = static_cast(std::distance(dx.begin(), + std::max_element(dx.begin(), dx.end()))); + if (dx[max_dir] > dx[min_dir]) { + semicoarsening_direction = max_dir; + max_semicoarsening_level = static_cast(std::log2(dx[max_dir] / dx[min_dir])); + } + if (max_semicoarsening_level > 0) { + info.setSemicoarsening(true); + info.setMaxSemicoarseningLevel(max_semicoarsening_level); + info.setSemicoarseningDirection(semicoarsening_direction); + } + } + amrex::MLEBNodeFDLaplacian linopx, linopy, linopz; if (eb_enabled) { #ifdef AMREX_USE_EB diff --git a/Source/ablastr/math/CMakeLists.txt b/Source/ablastr/math/CMakeLists.txt index 9093da83ae1..0ad3fe80b87 100644 --- a/Source/ablastr/math/CMakeLists.txt +++ b/Source/ablastr/math/CMakeLists.txt @@ -1 +1,9 @@ +foreach(D IN LISTS WarpX_DIMS) + warpx_set_suffix_dims(SD ${D}) + target_sources(ablastr_${SD} + PRIVATE + FiniteDifference.cpp + ) +endforeach() + add_subdirectory(fft) diff --git a/Source/ablastr/math/FiniteDifference.H b/Source/ablastr/math/FiniteDifference.H new file mode 100644 index 00000000000..8761318eb81 --- /dev/null +++ b/Source/ablastr/math/FiniteDifference.H @@ -0,0 +1,44 @@ +/* Copyright 2021-2025 Edoardo Zoni, Luca Fedeli + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ +#ifndef ABLASTR_MATH_FINITE_DIFFERENCE_H_ +#define ABLASTR_MATH_FINITE_DIFFERENCE_H_ + +#include "ablastr/utils/Enums.H" + +#include +#include + +namespace ablastr::math +{ + /** + * \brief Returns an array of coefficients (Fornberg coefficients), corresponding + * to the weight of each point in a finite-difference approximation of a derivative + * (up to order \c n_order). + * + * \param[in] n_order order of the finite-difference approximation + * \param[in] a_grid_type type of grid (collocated or not) + */ + [[nodiscard]] amrex::Vector + getFornbergStencilCoefficients ( + int n_order, ablastr::utils::enums::GridType a_grid_type); + + /** + * \brief Re-orders the Fornberg coefficients so that they can be used more conveniently for + * finite-order centering operations. For example, for finite-order centering of order 6, + * the Fornberg coefficients \c (c_0,c_1,c_2) are re-ordered as \c (c_2,c_1,c_0,c_0,c_1,c_2). + * + * \param[in,out] ordered_coeffs host vector where the re-ordered Fornberg coefficients will be stored + * \param[in] unordered_coeffs host vector storing the original sequence of Fornberg coefficients + * \param[in] order order of the finite-order centering along a given direction + */ + void + ReorderFornbergCoefficients ( + amrex::Vector& ordered_coeffs, + const amrex::Vector& unordered_coeffs, int order); +} + +#endif //ABLASTR_MATH_FINITE_DIFFERENCE_H_ diff --git a/Source/ablastr/math/FiniteDifference.cpp b/Source/ablastr/math/FiniteDifference.cpp new file mode 100644 index 00000000000..85d0b332131 --- /dev/null +++ b/Source/ablastr/math/FiniteDifference.cpp @@ -0,0 +1,77 @@ +/* Copyright 2021-2025 Edoardo Zoni, Luca Fedeli + * + * This file is part of WarpX. + * + * License: BSD-3-Clause-LBNL + */ + +#include "FiniteDifference.H" + +#include "ablastr/utils/TextMsg.H" + +using namespace ablastr::utils::enums; +using namespace amrex; + +namespace ablastr::math +{ + + amrex::Vector + getFornbergStencilCoefficients (const int n_order, GridType a_grid_type) + { + ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE(n_order % 2 == 0, "n_order must be even"); + + const int m = n_order / 2; + amrex::Vector coeffs; + coeffs.resize(m); + + // There are closed-form formula for these coefficients, but they result in + // an overflow when evaluated numerically. One way to avoid the overflow is + // to calculate the coefficients by recurrence. + + // Coefficients for collocated (nodal) finite-difference approximation + if (a_grid_type == GridType::Collocated) + { + // First coefficient + coeffs.at(0) = m * 2._rt / (m+1); + // Other coefficients by recurrence + for (int n = 1; n < m; n++) + { + coeffs.at(n) = - (m-n) * 1._rt / (m+n+1) * coeffs.at(n-1); + } + } + // Coefficients for staggered finite-difference approximation + else + { + amrex::Real prod = 1.; + for (int k = 1; k < m+1; k++) + { + prod *= (m + k) / (4._rt * k); + } + // First coefficient + coeffs.at(0) = 4_rt * m * prod * prod; + // Other coefficients by recurrence + for (int n = 1; n < m; n++) + { + coeffs.at(n) = - ((2_rt*n-1) * (m-n)) * 1._rt / ((2_rt*n+1) * (m+n)) * coeffs.at(n-1); + } + } + + return coeffs; + } + + void + ReorderFornbergCoefficients ( + amrex::Vector& ordered_coeffs, + const amrex::Vector& unordered_coeffs, + const int order) + { + const int n = order / 2; + for (int i = 0; i < n; i++) { + ordered_coeffs[i] = unordered_coeffs[n-1-i]; + } + for (int i = n; i < order; i++) { + ordered_coeffs[i] = unordered_coeffs[i-n]; + } + } + +} diff --git a/Source/Utils/Algorithms/LinearInterpolation.H b/Source/ablastr/math/LinearInterpolation.H similarity index 79% rename from Source/Utils/Algorithms/LinearInterpolation.H rename to Source/ablastr/math/LinearInterpolation.H index 716c2d829b6..502ef68c080 100644 --- a/Source/Utils/Algorithms/LinearInterpolation.H +++ b/Source/ablastr/math/LinearInterpolation.H @@ -1,24 +1,25 @@ -/* Copyright 2022 Luca Fedeli +/* Copyright 2022-2025 Luca Fedeli * * This file is part of WarpX. * * License: BSD-3-Clause-LBNL */ -#ifndef WARPX_UTILS_ALGORITHMS_LINEAR_INTERPOLATION_H_ -#define WARPX_UTILS_ALGORITHMS_LINEAR_INTERPOLATION_H_ +#ifndef ABLASTR_MATH_LINEAR_INTERPOLATION_H_ +#define ABLASTR_MATH_LINEAR_INTERPOLATION_H_ #include #include -namespace utils::algorithms +namespace ablastr::math { /** \brief Performs a linear interpolation * * Performs a linear interpolation at x given the 2 points * (x0, f0) and (x1, f1) */ - template AMREX_GPU_DEVICE AMREX_FORCE_INLINE + template + AMREX_GPU_DEVICE AMREX_FORCE_INLINE constexpr auto linear_interp( TCoord x0, TCoord x1, TVal f0, TVal f1, @@ -32,7 +33,8 @@ namespace utils::algorithms * Performs a bilinear interpolation at (x,y) given the 4 points * (x0, y0, f00), (x0, y1, f01), (x1, y0, f10), (x1, y1, f11). */ - template AMREX_GPU_DEVICE AMREX_FORCE_INLINE + template + AMREX_GPU_DEVICE AMREX_FORCE_INLINE constexpr auto bilinear_interp( TCoord x0, TCoord x1, TCoord y0, TCoord y1, TVal f00, TVal f01, TVal f10, TVal f11, @@ -49,7 +51,8 @@ namespace utils::algorithms * (x0, y0, z0, f000), (x0, y0, z1, f001), (x0, y1, z0, f010), (x0, y1, z1, f011), * (x1, y0, z0, f100), (x1, y0, z1, f101), (x1, y1, z0, f110), (x1, y1, z1, f111) */ - template AMREX_GPU_DEVICE AMREX_FORCE_INLINE + template + AMREX_GPU_DEVICE AMREX_FORCE_INLINE constexpr auto trilinear_interp( TCoord x0, TCoord x1, TCoord y0, TCoord y1, TCoord z0, TCoord z1, TVal f000, TVal f001, TVal f010, TVal f011, TVal f100, TVal f101, TVal f110, TVal f111, @@ -63,4 +66,4 @@ namespace utils::algorithms } } -#endif //WARPX_UTILS_ALGORITHMS_LINEAR_INTERPOLATION_H_ +#endif //ABLASTR_MATH_LINEAR_INTERPOLATION_H_ diff --git a/Source/ablastr/math/Make.package b/Source/ablastr/math/Make.package index a0e95b11225..5e3fd22dc81 100644 --- a/Source/ablastr/math/Make.package +++ b/Source/ablastr/math/Make.package @@ -1,3 +1,5 @@ -include $(WARPX_HOME)/Source/ablastr/math/fft/Make.package +CEXE_sources += FiniteDifference.cpp + +VPATH_LOCATIONS += $(WARPX_HOME)/Source/ablastr/math -VPATH_LOCATIONS += $(WARPX_HOME)/Source/ablastr +include $(WARPX_HOME)/Source/ablastr/math/fft/Make.package diff --git a/Source/ablastr/utils/SignalHandling.cpp b/Source/ablastr/utils/SignalHandling.cpp index 5eeaeec259f..bf4874b4536 100644 --- a/Source/ablastr/utils/SignalHandling.cpp +++ b/Source/ablastr/utils/SignalHandling.cpp @@ -37,7 +37,7 @@ SignalHandling::parseSignalNameToNumber (const std::string &str) #if defined(__linux__) || defined(__APPLE__) const struct { const char* abbrev; - const int value; + int value; } signals_to_parse[] = { {"ABRT", SIGABRT}, {"ALRM", SIGALRM}, diff --git a/Source/ablastr/utils/msg_logger/MsgLogger.H b/Source/ablastr/utils/msg_logger/MsgLogger.H index 401432f5dda..088a613bc87 100644 --- a/Source/ablastr/utils/msg_logger/MsgLogger.H +++ b/Source/ablastr/utils/msg_logger/MsgLogger.H @@ -79,10 +79,10 @@ namespace ablastr::utils::msg_logger * \brief Same as static Msg deserialize(std::vector::const_iterator& it) * but accepting an rvalue as an argument * - * @param[in] it iterator of a byte array + * @param[in] rit iterator of a byte array * @return a Msg struct */ - static Msg deserialize(std::vector::const_iterator&& it); + static Msg deserialize(std::vector::const_iterator&& rit); }; /** @@ -115,10 +115,10 @@ namespace ablastr::utils::msg_logger * \brief Same as static Msg MsgWithCounter(std::vector::const_iterator& it) * but accepting an rvalue as an argument * - * @param[in] it iterator of a byte array + * @param[in] rit iterator of a byte array * @return a MsgWithCounter struct */ - static MsgWithCounter deserialize(std::vector::const_iterator&& it); + static MsgWithCounter deserialize(std::vector::const_iterator&& rit); }; /** @@ -154,10 +154,10 @@ namespace ablastr::utils::msg_logger * \brief Same as static Msg MsgWithCounterAndRanks(std::vector::const_iterator& it) * but accepting an rvalue as an argument * - * @param[in] it iterator of a byte array + * @param[in] rit iterator of a byte array * @return a MsgWithCounterAndRanks struct */ - static MsgWithCounterAndRanks deserialize(std::vector::const_iterator&& it); + static MsgWithCounterAndRanks deserialize(std::vector::const_iterator&& rit); }; /** @@ -280,9 +280,9 @@ namespace ablastr::utils::msg_logger #endif - const int m_rank /*! MPI rank of the current process*/; - const int m_num_procs /*! Number of MPI ranks*/; - const int m_io_rank /*! Rank of the I/O process*/; + int m_rank /*! MPI rank of the current process*/; + int m_num_procs /*! Number of MPI ranks*/; + int m_io_rank /*! Rank of the I/O process*/; std::map m_messages /*! This stores a map to associate warning messages with the corresponding counters*/; }; diff --git a/Source/ablastr/utils/msg_logger/MsgLogger.cpp b/Source/ablastr/utils/msg_logger/MsgLogger.cpp index 6537a8f61e5..6597588d085 100644 --- a/Source/ablastr/utils/msg_logger/MsgLogger.cpp +++ b/Source/ablastr/utils/msg_logger/MsgLogger.cpp @@ -147,9 +147,10 @@ Msg Msg::deserialize (std::vector::const_iterator& it) return msg; } -Msg Msg::deserialize (std::vector::const_iterator&& it) +Msg Msg::deserialize (std::vector::const_iterator&& rit) { - return Msg::deserialize(it); + auto lit = std::vector::const_iterator{std::move(rit)}; + return Msg::deserialize(lit); } std::vector MsgWithCounter::serialize() const @@ -174,9 +175,10 @@ MsgWithCounter MsgWithCounter::deserialize (std::vector::const_iterator& i return msg_with_counter; } -MsgWithCounter MsgWithCounter::deserialize (std::vector::const_iterator&& it) +MsgWithCounter MsgWithCounter::deserialize (std::vector::const_iterator&& rit) { - return MsgWithCounter::deserialize(it); + auto lit = std::vector::const_iterator{std::move(rit)}; + return MsgWithCounter::deserialize(lit); } std::vector MsgWithCounterAndRanks::serialize() const @@ -205,9 +207,10 @@ MsgWithCounterAndRanks::deserialize (std::vector::const_iterator& it) } MsgWithCounterAndRanks -MsgWithCounterAndRanks::deserialize (std::vector::const_iterator&& it) +MsgWithCounterAndRanks::deserialize (std::vector::const_iterator&& rit) { - return MsgWithCounterAndRanks::deserialize(it); + auto lit = std::vector::const_iterator{std::move(rit)}; + return MsgWithCounterAndRanks::deserialize(lit); } Logger::Logger() : diff --git a/Tools/Algorithms/psatd.ipynb b/Tools/Algorithms/psatd.ipynb index 3e8b2a82d2e..6153b904968 100644 --- a/Tools/Algorithms/psatd.ipynb +++ b/Tools/Algorithms/psatd.ipynb @@ -64,9 +64,9 @@ " Wd[i, j] = Wd[i, j].expand().simplify()\n", " diff = W[i, j] - Wd[i, j]\n", " diff = diff.expand().simplify()\n", - " assert (\n", - " diff == 0\n", - " ), f\"Diagonalization failed: W[{i},{j}] - Wd[{i},{j}] = {diff} is not zero\"\n", + " assert diff == 0, (\n", + " f\"Diagonalization failed: W[{i},{j}] - Wd[{i},{j}] = {diff} is not zero\"\n", + " )\n", "\n", "\n", "def simple_mat(W):\n", diff --git a/Tools/Algorithms/stencil.py b/Tools/Algorithms/stencil.py index 2fe67d1c681..1fafd3837a7 100644 --- a/Tools/Algorithms/stencil.py +++ b/Tools/Algorithms/stencil.py @@ -361,10 +361,10 @@ def run_main( print("\nCell size:") print(f"- dx = {dx_boosted}") if dims > 1: - print(f"- dx[1:]/dx[0] = {dx_boosted[1:]/dx_boosted[0]}") + print(f"- dx[1:]/dx[0] = {dx_boosted[1:] / dx_boosted[0]}") print("\nTime step:") print(f"- dt = {dt}") - print(f"- c*dt/dx = {c*dt/dx_boosted}") + print(f"- c*dt/dx = {c * dt / dx_boosted}") print("\nSpectral order:") print(f"- order = {psatd_order}") print("\nLorentz boost, Galilean velocity:") diff --git a/Tools/Linter/runClangTidy.sh b/Tools/Linter/runClangTidy.sh index 046c72d7b27..4c1948cf372 100755 --- a/Tools/Linter/runClangTidy.sh +++ b/Tools/Linter/runClangTidy.sh @@ -55,13 +55,13 @@ ${CTIDY} --version echo echo "This can be overridden by setting the environment" echo "variables CLANG, CLANGXX, and CLANGTIDY e.g.: " -echo "$ export CLANG=clang-15" -echo "$ export CLANGXX=clang++-15" -echo "$ export CTIDCLANGTIDYY=clang-tidy-15" +echo "$ export CLANG=clang-17" +echo "$ export CLANGXX=clang++-17" +echo "$ export CTIDCLANGTIDYY=clang-tidy-17" echo "$ ./Tools/Linter/runClangTidy.sh" echo echo "******************************************************" -echo "* Warning: clang v15 is currently used in CI tests. *" +echo "* Warning: clang v17 is currently used in CI tests. *" echo "* It is therefore recommended to use this version. *" echo "* Otherwise, a newer version may find issues not *" echo "* currently covered by CI tests while older versions *" diff --git a/Tools/PostProcessing/plot_distribution_mapping.py b/Tools/PostProcessing/plot_distribution_mapping.py index 899ea4678c4..07a353cdc3d 100644 --- a/Tools/PostProcessing/plot_distribution_mapping.py +++ b/Tools/PostProcessing/plot_distribution_mapping.py @@ -119,9 +119,9 @@ def _get_costs_reduced_diagnostics(self, directory, prange): kcoords = k.astype(int) // k_blocking_factor # Fill in cost array - shape = (kmax + 1, jmax + 1, imax + 1)[: 2 + self.is_3D] + shape = (kmax + 1, jmax + 1, imax + 1)[1 - self.is_3D :] coords = [ - coord[: 2 + self.is_3D] for coord in zip(kcoords, jcoords, icoords) + coord[1 - self.is_3D :] for coord in zip(kcoords, jcoords, icoords) ] cost_arr = np.full(shape, 0.0) diff --git a/Tools/PostProcessing/read_raw_data.py b/Tools/PostProcessing/read_raw_data.py index a180cad18e0..bc63b43f3cf 100644 --- a/Tools/PostProcessing/read_raw_data.py +++ b/Tools/PostProcessing/read_raw_data.py @@ -202,7 +202,7 @@ def _read_field(raw_file, field_name): f.seek(offset) if header.version == 1: f.readline() # skip the first line - arr = np.fromfile(f, "float64", np.product(shape)) + arr = np.fromfile(f, "float64", np.prod(shape)) arr = arr.reshape(shape, order="F") box_shape = [slice(low, hig + 1) for low, hig in zip(lo, hi)] if header.ncomp > 1: @@ -225,7 +225,7 @@ def _read_buffer(snapshot, header_fn, _component_names): lo = box[0] - dom_lo hi = box[1] - dom_lo shape = hi - lo + 1 - size = np.product(shape) + size = np.prod(shape) with open(snapshot + "/Level_0/" + fn, "rb") as f: f.seek(offset) if header.version == 1: diff --git a/Tools/QedTablesUtils/Source/QedTableCommons.H b/Tools/QedTablesUtils/Source/QedTableCommons.H index 2233513bc97..903ba4623a8 100644 --- a/Tools/QedTablesUtils/Source/QedTableCommons.H +++ b/Tools/QedTablesUtils/Source/QedTableCommons.H @@ -12,8 +12,8 @@ bool Contains (const ContainerType& container, const ElementType& el) void AbortWithMessage(const std::string& msg) { - std::cout << "### ABORT : " << msg << std::endl; - std::cout << "___________________________" << std::endl; + std::cerr << "### ABORT : " << msg << "\n"; + std::cerr << "___________________________\n"; exit(1); } diff --git a/Tools/Release/releasePR.py b/Tools/Release/releasePR.py new file mode 100755 index 00000000000..47a380901b1 --- /dev/null +++ b/Tools/Release/releasePR.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +# +# Copyright 2025 The WarpX Community +# +# This file is part of WarpX. +# +# Authors: Axel Huebl +# + +# This file is a maintainer tool to open a release PR for WarpX. +# It is highly automated and does a few assumptions, e.g., that you +# are releasing for the current month. +# +# You also need to have git and the GitHub CLI tool "gh" installed and properly +# configured for it to work: +# https://cli.github.com/ +# +import subprocess +import sys +from datetime import datetime +from pathlib import Path + +# Maintainer Inputs ########################################################### + +print("""Hi there, this is a WarpX maintainer tool to ...\n. +For it to work, you need write access on the source directory and +you should be working in a clean git branch without ongoing +rebase/merge/conflict resolves and without unstaged changes.""") + +# check source dir +REPO_DIR = Path(__file__).parent.parent.parent.absolute() +print(f"\nYour current source directory is: {REPO_DIR}") + +REPLY = input("Are you sure you want to continue? [y/N] ") +print() +if REPLY not in ["Y", "y"]: + print("You did not confirm with 'y', aborting.") + sys.exit(1) + +release_repo = input("What is the name of your git remote? (e.g., ax3l) ") +commit_sign = input("How to sign the commit? (e.g., -sS) ") + + +# Helpers ##################################################################### + + +def concat_answers(answers): + return "\n".join(answers) + "\n" + + +# Stash current work ########################################################## + +subprocess.run(["git", "stash"], capture_output=True, text=True) + + +# Git Branch ################################################################## + +WarpX_version_yr = f"{datetime.now().strftime('%y')}" +WarpX_version_mn = f"{datetime.now().strftime('%m')}" +WarpX_version = f"{WarpX_version_yr}.{WarpX_version_mn}" +release_branch = f"release-{WarpX_version}" +subprocess.run(["git", "checkout", "development"], capture_output=True, text=True) +subprocess.run(["git", "fetch"], capture_output=True, text=True) +subprocess.run(["git", "pull", "--ff-only"], capture_output=True, text=True) +subprocess.run(["git", "branch", "-D", release_branch], capture_output=True, text=True) +subprocess.run( + ["git", "checkout", "-b", release_branch], capture_output=True, text=True +) + + +# AMReX New Version ########################################################### + +AMReX_version = f"{datetime.now().strftime('%y')}.{datetime.now().strftime('%m')}" +answers = concat_answers(["y", AMReX_version, AMReX_version, "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updateAMReX.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +subprocess.run( + ["git", "commit", commit_sign, "-m", f"AMReX: {AMReX_version}"], text=True +) + + +# PICSAR New Version ########################################################## + +PICSAR_version = "25.01" +answers = concat_answers(["y", PICSAR_version, PICSAR_version, "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updatePICSAR.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +subprocess.run( + ["git", "commit", commit_sign, "-m", f"PICSAR: {PICSAR_version}"], text=True +) + + +# pyAMReX New Version ######################################################### + +pyAMReX_version = f"{datetime.now().strftime('%y')}.{datetime.now().strftime('%m')}" +answers = concat_answers(["y", pyAMReX_version, pyAMReX_version, "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updatepyAMReX.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +subprocess.run( + ["git", "commit", commit_sign, "-m", f"pyAMReX: {pyAMReX_version}"], text=True +) + + +# WarpX New Version ########################################################### + +answers = concat_answers(["y", WarpX_version_yr, WarpX_version_mn, "", "", "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/newVersion.sh")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +subprocess.run( + ["git", "commit", commit_sign, "-m", f"WarpX: {WarpX_version}"], text=True +) + + +# GitHub PR ################################################################### + +subprocess.run(["git", "push", "-u", release_repo, release_branch], text=True) + +subprocess.run( + [ + "gh", + "pr", + "create", + "--title", + f"Release {WarpX_version}", + "--body", + f"""Prepare the {datetime.now().strftime("%B")} release of WarpX: +```bash +# update dependencies +./Tools/Release/updateAMReX.py +./Tools/Release/updatePICSAR.py # no changes, still {PICSAR_version} +./Tools/Release/updatepyAMReX.py +# bump version number +./Tools/Release/newVersion.sh +``` + +Following this workflow: https://warpx.readthedocs.io/en/latest/maintenance/release.html +""", + "--label", + "component: documentation", + "--label", + "component: third party", + "--web", + ], + text=True, +) + + +# Epilogue #################################################################### + +print("""Done. Please check your source, e.g. via + git diff +now and commit the changes if no errors occurred.""") diff --git a/Tools/Release/updateAMReX.py b/Tools/Release/updateAMReX.py index beeb12e85ff..99bd4899826 100755 --- a/Tools/Release/updateAMReX.py +++ b/Tools/Release/updateAMReX.py @@ -75,8 +75,8 @@ print(f"AMReX HEAD commit (development branch): {amrex_HEAD}") amrex_new_branch = input("Update AMReX commit/branch/sha: ").strip() if not amrex_new_branch: - amrex_new_branch = amrex_branch - print(f"--> Nothing entered, will keep: {amrex_branch}") + amrex_new_branch = amrex_HEAD + print(f"--> Nothing entered, use: {amrex_HEAD}") print() print( diff --git a/Tools/Release/updatePICSAR.py b/Tools/Release/updatePICSAR.py index 5148c16727e..90c928472a5 100755 --- a/Tools/Release/updatePICSAR.py +++ b/Tools/Release/updatePICSAR.py @@ -75,8 +75,8 @@ print(f"PICSAR HEAD commit (development branch): {PICSAR_HEAD}") PICSAR_new_branch = input("Update PICSAR commit/branch/sha: ").strip() if not PICSAR_new_branch: - PICSAR_new_branch = PICSAR_branch - print(f"--> Nothing entered, will keep: {PICSAR_branch}") + PICSAR_new_branch = PICSAR_HEAD + print(f"--> Nothing entered, will use: {PICSAR_HEAD}") print() print( diff --git a/Tools/Release/updatepyAMReX.py b/Tools/Release/updatepyAMReX.py index 68001222241..13c044b3bdd 100755 --- a/Tools/Release/updatepyAMReX.py +++ b/Tools/Release/updatepyAMReX.py @@ -77,8 +77,8 @@ print(f"pyAMReX HEAD commit (development branch): {pyamrex_HEAD}") pyamrex_new_branch = input("Update pyAMReX commit/branch/sha: ").strip() if not pyamrex_new_branch: - pyamrex_new_branch = pyamrex_branch - print(f"--> Nothing entered, will keep: {pyamrex_branch}") + pyamrex_new_branch = pyamrex_HEAD + print(f"--> Nothing entered, will use: {pyamrex_HEAD}") print() print( diff --git a/Tools/Release/weeklyUpdate.py b/Tools/Release/weeklyUpdate.py new file mode 100755 index 00000000000..6c32993f79e --- /dev/null +++ b/Tools/Release/weeklyUpdate.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +# +# Copyright 2025 The WarpX Community +# +# This file is part of WarpX. +# +# Authors: Axel Huebl +# + +# This file is a maintainer tool to open a weekly dependency update PR for WarpX. +# +# You also need to have git and the GitHub CLI tool "gh" installed and properly +# configured for it to work: +# https://cli.github.com/ +# +import subprocess +import sys +from pathlib import Path + +# Maintainer Inputs ########################################################### + +print("""Hi there, this is a WarpX maintainer tool to ...\n. +For it to work, you need write access on the source directory and +you should be working in a clean git branch without ongoing +rebase/merge/conflict resolves and without unstaged changes.""") + +# check source dir +REPO_DIR = Path(__file__).parent.parent.parent.absolute() +print(f"\nYour current source directory is: {REPO_DIR}") + +REPLY = input("Are you sure you want to continue? [y/N] ") +print() +if REPLY not in ["Y", "y"]: + print("You did not confirm with 'y', aborting.") + sys.exit(1) + +update_repo = input("What is the name of your git remote? (e.g., ax3l) ") +commit_sign = input("How to sign the commit? (e.g., -sS) ") + + +# Helpers ##################################################################### + + +def concat_answers(answers): + return "\n".join(answers) + "\n" + + +# Stash current work ########################################################## + +subprocess.run(["git", "stash"], capture_output=True, text=True) + + +# Git Branch ################################################################## + +update_branch = "topic-amrexWeekly" +subprocess.run(["git", "checkout", "development"], capture_output=True, text=True) +subprocess.run(["git", "fetch"], capture_output=True, text=True) +subprocess.run(["git", "pull", "--ff-only"], capture_output=True, text=True) +subprocess.run(["git", "branch", "-D", update_branch], capture_output=True, text=True) +subprocess.run(["git", "checkout", "-b", update_branch], capture_output=True, text=True) + + +# AMReX New Version ########################################################### + +answers = concat_answers(["y", "", "", "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updateAMReX.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +amrex_diff = subprocess.run(["git", "diff", "--cached"], capture_output=True, text=True) +print("AMReX Commit...") +subprocess.run( + ["git", "commit", commit_sign, "-m", "AMReX: Weekly Update"], + capture_output=True, + text=True, +) + + +# PICSAR New Version ########################################################## + +PICSAR_version = "25.01" +answers = concat_answers(["y", PICSAR_version, PICSAR_version, "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updatePICSAR.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +picsar_diff = subprocess.run( + ["git", "diff", "--cached"], capture_output=True, text=True +) +print("PICSAR Commit...") +subprocess.run( + ["git", "commit", commit_sign, "-m", "PICSAR: Weekly Update"], + capture_output=True, + text=True, +) + + +# pyAMReX New Version ######################################################### + +answers = concat_answers(["y", "", "", "y"]) + +process = subprocess.Popen( + [Path(REPO_DIR).joinpath("Tools/Release/updatepyAMReX.py")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, +) + +process.communicate(answers) +del process + +# commit +subprocess.run(["git", "add", "-u"], capture_output=True, text=True) +pyamrex_diff = subprocess.run( + ["git", "diff", "--cached"], capture_output=True, text=True +) +print("pyAMReX Commit...") +subprocess.run( + ["git", "commit", commit_sign, "-m", "pyAMReX: Weekly Update"], + capture_output=True, + text=True, +) + +# GitHub PR ################################################################### + +subprocess.run(["git", "push", "-f", "-u", update_repo, update_branch], text=True) + +amrex_changes = " (no changes)" if amrex_diff.stdout == "" else "" +picsar_changes = " (no changes)" if picsar_diff.stdout == "" else "" +pyamrex_changes = " (no changes)" if pyamrex_diff.stdout == "" else "" + +subprocess.run( + [ + "gh", + "pr", + "create", + "--title", + "AMReX/pyAMReX/PICSAR: Weekly Update", + "--body", + f"""Weekly update to latest AMReX{amrex_changes}. +Weekly update to latest pyAMReX{pyamrex_changes}. +Weekly update to latest PICSAR{picsar_changes}. + +```console +./Tools/Release/updateAMReX.py +./Tools/Release/updatepyAMReX.py +./Tools/Release/updatePICSAR.py +``` +""", + "--label", + "component: documentation", + "--label", + "component: third party", + "--web", + ], + text=True, +) + + +# Epilogue #################################################################### + +print("""Done. Please check your source, e.g. via + git diff +now and commit the changes if no errors occurred.""") diff --git a/Tools/machines/adastra-cines/adastra_warpx.profile.example b/Tools/machines/adastra-cines/adastra_warpx.profile.example index 8aaff6e4450..de7a325139a 100644 --- a/Tools/machines/adastra-cines/adastra_warpx.profile.example +++ b/Tools/machines/adastra-cines/adastra_warpx.profile.example @@ -4,12 +4,12 @@ # required dependencies module purge -module load cpe/23.12 +module load cpe/24.07 module load craype-accel-amd-gfx90a craype-x86-trento module load PrgEnv-cray -module load CCE-GPU-3.0.0 -module load amd-mixed/5.7.1 module load develop +module load CCE-GPU-4.0.0 +module load amd-mixed/6.2.1 module load cmake/3.27.9 # optional: for PSATD in RZ geometry support @@ -19,14 +19,14 @@ export LD_LIBRARY_PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/blaspp-2024.05.31/lib64:$ export LD_LIBRARY_PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH # optional: for QED lookup table generation support -module load boost/1.83.0-mpi-python3 +module load boost/1.86.0-mpi # optional: for openPMD support module load cray-hdf5-parallel export CMAKE_PREFIX_PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/adios2-2.10.2:$CMAKE_PREFIX_PATH -export PATH=${HOME}/sw/adastra/gpu/adios2-2.8.3/bin:${PATH} +export PATH=${SHAREDHOMEDIR}/sw/adastra/gpu/adios2-2.10.2/bin:${PATH} # optional: for Python bindings or libEnsemble module load cray-python/3.11.5 diff --git a/Tools/machines/adastra-cines/install_dependencies.sh b/Tools/machines/adastra-cines/install_dependencies.sh index 242f5fc664c..896b775db3b 100755 --- a/Tools/machines/adastra-cines/install_dependencies.sh +++ b/Tools/machines/adastra-cines/install_dependencies.sh @@ -76,16 +76,18 @@ cmake -S $SHAREDHOMEDIR/src/c-blosc -B $SHAREDHOMEDIR/src/c-blosc-ad-build -DBUI cmake --build $SHAREDHOMEDIR/src/c-blosc-ad-build --target install --parallel 16 rm -rf $SHAREDHOMEDIR/src/c-blosc-ad-build -# ADIOS2 v. 2.8.3 (for OpenPMD) +# ADIOS2 v. 2.10.2 (for OpenPMD) if [ -d $SHAREDHOMEDIR/src/adios2 ] then - # git repository is already there - : + cd $SHAREDHOMEDIR/src/adios2 + git fetch --prune + git checkout v2.10.2 + cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $SHAREDHOMEDIR/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $SHAREDHOMEDIR/src/adios2 fi rm -rf $SHAREDHOMEDIR/src/adios2-ad-build -cmake -S $SHAREDHOMEDIR/src/adios2 -B $SHAREDHOMEDIR/src/adios2-ad-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 +cmake -S $SHAREDHOMEDIR/src/adios2 -B $SHAREDHOMEDIR/src/adios2-ad-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build $SHAREDHOMEDIR/src/adios2-ad-build --target install -j 16 rm -rf $SHAREDHOMEDIR/src/adios2-ad-build diff --git a/Tools/machines/quartz-llnl/quartz.sbatch b/Tools/machines/dane-llnl/dane.sbatch similarity index 78% rename from Tools/machines/quartz-llnl/quartz.sbatch rename to Tools/machines/dane-llnl/dane.sbatch index 4c1a82ff8e9..b2a114b3f1b 100644 --- a/Tools/machines/quartz-llnl/quartz.sbatch +++ b/Tools/machines/dane-llnl/dane.sbatch @@ -15,15 +15,14 @@ # one MPI rank per half-socket (see below) #SBATCH --tasks-per-node=2 # request all logical (virtual) cores per half-socket -#SBATCH --cpus-per-task=18 +#SBATCH --cpus-per-task=112 -# each Quartz node has 1 socket of Intel Xeon E5-2695 v4 -# each Xeon CPU is divided into 2 bus rings that each have direct L3 access +# each Dane node has 2 sockets of Intel Sapphire Rapids with 56 cores each export WARPX_NMPI_PER_NODE=2 -# each MPI rank per half-socket has 9 physical cores -# or 18 logical (virtual) cores +# each MPI rank per half-socket has 56 physical cores +# or 112 logical (virtual) cores # over-subscribing each physical core with 2x # hyperthreading led to a slight (3.5%) speedup on Cori's Intel Xeon E5-2698 v3, # so we do the same here @@ -33,7 +32,7 @@ export WARPX_NMPI_PER_NODE=2 # for N>9, also equally over close-by logical cores export OMP_PROC_BIND=spread export OMP_PLACES=threads -export OMP_NUM_THREADS=18 +export OMP_NUM_THREADS=112 EXE="" # e.g. ./warpx diff --git a/Tools/machines/quartz-llnl/quartz_warpx.profile.example b/Tools/machines/dane-llnl/dane_warpx.profile.example similarity index 51% rename from Tools/machines/quartz-llnl/quartz_warpx.profile.example rename to Tools/machines/dane-llnl/dane_warpx.profile.example index f296a0738ff..8992871f0e5 100644 --- a/Tools/machines/quartz-llnl/quartz_warpx.profile.example +++ b/Tools/machines/dane-llnl/dane_warpx.profile.example @@ -2,7 +2,7 @@ #export proj="" # edit this and comment in # required dependencies -module load cmake/3.23.1 +module load cmake/3.26.3 module load clang/14.0.6-magic module load mvapich2/2.3.7 @@ -15,38 +15,38 @@ module load boost/1.80.0 # optional: for openPMD support module load hdf5-parallel/1.14.0 -SW_DIR="/usr/workspace/${USER}/quartz" -export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.8.3:$CMAKE_PREFIX_PATH -export PATH=${SW_DIR}/adios2-2.8.3/bin:${PATH} +SW_DIR="/usr/workspace/${USER}/dane" +export CMAKE_PREFIX_PATH=${SW_DIR}/install/c-blosc-1.21.6:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/install/adios2-2.10.2:$CMAKE_PREFIX_PATH +export PATH=${SW_DIR}/install/adios2-2.10.2/bin:${PATH} # optional: for PSATD in RZ geometry support -export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH -export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/install/blaspp-2024.10.26:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/install/lapackpp-2024.10.26:$CMAKE_PREFIX_PATH +export LD_LIBRARY_PATH=${SW_DIR}/install/blaspp-2024.10.26/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/install/lapackpp-2024.10.26/lib64:$LD_LIBRARY_PATH # optional: for Python bindings -module load python/3.9.12 +module load python/3.12.2 -if [ -d "${SW_DIR}/venvs/warpx-quartz" ] +if [ -d "${SW_DIR}/venvs/warpx-dane" ] then - source ${SW_DIR}/venvs/warpx-quartz/bin/activate + source ${SW_DIR}/venvs/warpx-dane/bin/activate fi # optional: an alias to request an interactive node for two hours -alias getNode="srun --time=0:30:00 --nodes=1 --ntasks-per-node=2 --cpus-per-task=18 -p pdebug --pty bash" +alias getNode="srun --time=0:30:00 --nodes=1 --ntasks-per-node=2 --cpus-per-task=56 -p pdebug --pty bash" # an alias to run a command on a batch node for up to 30min # usage: runNode -alias runNode="srun --time=0:30:00 --nodes=1 --ntasks-per-node=2 --cpus-per-task=18 -p pdebug" +alias runNode="srun --time=0:30:00 --nodes=1 --ntasks-per-node=2 --cpus-per-task=56 -p pdebug" # fix system defaults: do not escape $ with a \ on tab completion shopt -s direxpand -# optimize CPU microarchitecture for Intel Xeon E5-2695 v4 +# optimize CPU microarchitecture for Intel Sapphire Rapids # note: the cc/CC/ftn wrappers below add those -export CXXFLAGS="-march=broadwell" -export CFLAGS="-march=broadwell" +export CXXFLAGS="-march=sapphirerapids" +export CFLAGS="-march=sapphirerapids" # compiler environment hints export CC=$(which clang) diff --git a/Tools/machines/quartz-llnl/install_dependencies.sh b/Tools/machines/dane-llnl/install_dependencies.sh similarity index 52% rename from Tools/machines/quartz-llnl/install_dependencies.sh rename to Tools/machines/dane-llnl/install_dependencies.sh index cfb01769384..25e8e965777 100755 --- a/Tools/machines/quartz-llnl/install_dependencies.sh +++ b/Tools/machines/dane-llnl/install_dependencies.sh @@ -1,10 +1,10 @@ #!/bin/bash # -# Copyright 2023 The WarpX Community +# Copyright 2024 The WarpX Community # # This file is part of WarpX. # -# Author: Axel Huebl +# Author: Axel Huebl, David Grote # License: BSD-3-Clause-LBNL # Exit on first error encountered ############################################# @@ -14,15 +14,15 @@ set -eu -o pipefail # Check: ###################################################################### # -# Was quartz_warpx.profile sourced and configured correctly? -if [ -z ${proj-} ]; then echo "WARNING: The 'proj' variable is not yet set in your quartz_warpx.profile file! Please edit its line 2 to continue!"; exit 1; fi +# Was dane_warpx.profile sourced and configured correctly? +if [ -z ${proj-} ]; then echo "WARNING: The 'proj' variable is not yet set in your dane_warpx.profile file! Please edit its line 2 to continue!"; exit 1; fi -# Remove old dependencies ##################################################### +# The src directory should have already been created when cloning WarpX ####### # -SW_DIR="/usr/workspace/${USER}/quartz" -rm -rf ${SW_DIR} -mkdir -p ${SW_DIR} +SW_DIR="/usr/workspace/${USER}/dane" +rm -rf ${SW_DIR}/install +mkdir -p ${SW_DIR}/install # remove common user mistakes in python, located in .local instead of a venv python3 -m pip uninstall -qq -y pywarpx @@ -37,66 +37,66 @@ python3 -m pip uninstall -qqq -y mpi4py 2>/dev/null || true build_dir=$(mktemp -d) # c-blosc (I/O compression) -if [ -d ${HOME}/src/c-blosc ] +if [ -d ${SW_DIR}/src/c-blosc ] then - cd ${HOME}/src/c-blosc + cd ${SW_DIR}/src/c-blosc git fetch --prune - git checkout v1.21.1 + git checkout v1.21.6 cd - else - git clone -b v1.21.1 https://github.com/Blosc/c-blosc.git ${HOME}/src/c-blosc + git clone -b v1.21.6 https://github.com/Blosc/c-blosc.git ${SW_DIR}/src/c-blosc fi -cmake -S ${HOME}/src/c-blosc -B ${build_dir}/c-blosc-quartz-build -DBUILD_TESTS=OFF -DBUILD_BENCHMARKS=OFF -DDEACTIVATE_AVX2=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/c-blosc-1.21.1 -cmake --build ${build_dir}/c-blosc-quartz-build --target install --parallel 6 +cmake -S ${SW_DIR}/src/c-blosc -B ${build_dir}/c-blosc-dane-build -DBUILD_TESTS=OFF -DBUILD_BENCHMARKS=OFF -DDEACTIVATE_AVX2=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/install/c-blosc-1.21.6 +cmake --build ${build_dir}/c-blosc-dane-build --target install --parallel 6 # ADIOS2 -if [ -d ${HOME}/src/adios2 ] +if [ -d ${SW_DIR}/src/adios2 ] then - cd ${HOME}/src/adios2 + cd ${SW_DIR}/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git ${HOME}/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SW_DIR}/src/adios2 fi -cmake -S ${HOME}/src/adios2 -B ${build_dir}/adios2-quartz-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_SST=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 -cmake --build ${build_dir}/adios2-quartz-build --target install -j 6 +cmake -S ${SW_DIR}/src/adios2 -B ${build_dir}/adios2-dane-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_SST=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/install/adios2-2.10.2 +cmake --build ${build_dir}/adios2-dane-build --target install -j 6 # BLAS++ (for PSATD+RZ) -if [ -d ${HOME}/src/blaspp ] +if [ -d ${SW_DIR}/src/blaspp ] then - cd ${HOME}/src/blaspp + cd ${SW_DIR}/src/blaspp git fetch --prune - git checkout v2024.05.31 + git checkout v2024.10.26 cd - else - git clone -b v2024.05.31 https://github.com/icl-utk-edu/blaspp.git ${HOME}/src/blaspp + git clone -b v2024.10.26 https://github.com/icl-utk-edu/blaspp.git ${SW_DIR}/src/blaspp fi -cmake -S ${HOME}/src/blaspp -B ${build_dir}/blaspp-quartz-build -Duse_openmp=ON -Duse_cmake_find_blas=ON -DCMAKE_CXX_STANDARD=17 -DCMAKE_INSTALL_PREFIX=${SW_DIR}/blaspp-2024.05.31 -cmake --build ${build_dir}/blaspp-quartz-build --target install --parallel 6 +cmake -S ${SW_DIR}/src/blaspp -B ${build_dir}/blaspp-dane-build -Duse_openmp=ON -Duse_cmake_find_blas=ON -DCMAKE_CXX_STANDARD=17 -DCMAKE_INSTALL_PREFIX=${SW_DIR}/install/blaspp-2024.10.26 +cmake --build ${build_dir}/blaspp-dane-build --target install --parallel 6 # LAPACK++ (for PSATD+RZ) -if [ -d ${HOME}/src/lapackpp ] +if [ -d ${SW_DIR}/src/lapackpp ] then - cd ${HOME}/src/lapackpp + cd ${SW_DIR}/src/lapackpp git fetch --prune - git checkout v2024.05.31 + git checkout v2024.10.26 cd - else - git clone -b v2024.05.31 https://github.com/icl-utk-edu/lapackpp.git ${HOME}/src/lapackpp + git clone -b v2024.10.26 https://github.com/icl-utk-edu/lapackpp.git ${SW_DIR}/src/lapackpp fi -CXXFLAGS="-DLAPACK_FORTRAN_ADD_" cmake -S ${HOME}/src/lapackpp -B ${build_dir}/lapackpp-quartz-build -Duse_cmake_find_lapack=ON -DCMAKE_CXX_STANDARD=17 -Dbuild_tests=OFF -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DCMAKE_INSTALL_PREFIX=${SW_DIR}/lapackpp-2024.05.31 -cmake --build ${build_dir}/lapackpp-quartz-build --target install --parallel 6 +CXXFLAGS="-DLAPACK_FORTRAN_ADD_" cmake -S ${SW_DIR}/src/lapackpp -B ${build_dir}/lapackpp-dane-build -Duse_cmake_find_lapack=ON -DCMAKE_CXX_STANDARD=17 -Dbuild_tests=OFF -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DCMAKE_INSTALL_PREFIX=${SW_DIR}/install/lapackpp-2024.10.26 +cmake --build ${build_dir}/lapackpp-dane-build --target install --parallel 6 # Python ###################################################################### # python3 -m pip install --upgrade --user virtualenv -rm -rf ${SW_DIR}/venvs/warpx-quartz -python3 -m venv ${SW_DIR}/venvs/warpx-quartz -source ${SW_DIR}/venvs/warpx-quartz/bin/activate +rm -rf ${SW_DIR}/venvs/warpx-dane +python3 -m venv ${SW_DIR}/venvs/warpx-dane +source ${SW_DIR}/venvs/warpx-dane/bin/activate python3 -m pip install --upgrade pip -python3 -m pip cache purge +#python3 -m pip cache purge python3 -m pip install --upgrade build python3 -m pip install --upgrade packaging python3 -m pip install --upgrade wheel @@ -111,7 +111,7 @@ python3 -m pip install --upgrade matplotlib python3 -m pip install --upgrade yt # install or update WarpX dependencies such as picmistandard -python3 -m pip install --upgrade -r ${HOME}/src/warpx/requirements.txt +python3 -m pip install --upgrade -r ${SW_DIR}/src/warpx/requirements.txt # ML dependencies python3 -m pip install --upgrade torch diff --git a/Tools/machines/desktop/spack-macos-openmp.yaml b/Tools/machines/desktop/spack-macos-openmp.yaml index 3ea78625b78..820cf7069fd 100644 --- a/Tools/machines/desktop/spack-macos-openmp.yaml +++ b/Tools/machines/desktop/spack-macos-openmp.yaml @@ -23,7 +23,6 @@ spack: - conduit ~fortran - fftw - hdf5 ~fortran - - heffte ~cuda +fftw - lapackpp ~cuda ~rocm ^blaspp ~cuda +openmp ~rocm - mpi - llvm-openmp diff --git a/Tools/machines/desktop/spack-ubuntu-cuda.yaml b/Tools/machines/desktop/spack-ubuntu-cuda.yaml index 19b9ae12e24..460f271a24c 100644 --- a/Tools/machines/desktop/spack-ubuntu-cuda.yaml +++ b/Tools/machines/desktop/spack-ubuntu-cuda.yaml @@ -25,7 +25,6 @@ spack: - cuda - fftw - hdf5 - - heffte - lapackpp - mpi - pkgconfig @@ -121,19 +120,6 @@ spack: modules: [] environment: {} extra_rpaths: [] - - compiler: - spec: gcc@8.3.0 - paths: - cc: /usr/bin/gcc - cxx: /usr/bin/g++ - f77: /usr/bin/gfortran - fc: /usr/bin/gfortran - flags: {} - operating_system: debian10 - target: x86_64 - modules: [] - environment: {} - extra_rpaths: [] # binary caches mirrors: diff --git a/Tools/machines/desktop/spack-ubuntu-openmp.yaml b/Tools/machines/desktop/spack-ubuntu-openmp.yaml index 1eb7d4074a7..90f8a048686 100644 --- a/Tools/machines/desktop/spack-ubuntu-openmp.yaml +++ b/Tools/machines/desktop/spack-ubuntu-openmp.yaml @@ -22,7 +22,6 @@ spack: - ecp-data-vis-sdk +adios2 +ascent +hdf5 +sensei - fftw - hdf5 - - heffte ~cuda +fftw - lapackpp ~cuda ~rocm ^blaspp ~cuda +openmp ~rocm - mpi - pkgconfig @@ -111,19 +110,6 @@ spack: modules: [] environment: {} extra_rpaths: [] - - compiler: - spec: gcc@8.3.0 - paths: - cc: /usr/bin/gcc - cxx: /usr/bin/g++ - f77: /usr/bin/gfortran - fc: /usr/bin/gfortran - flags: {} - operating_system: debian10 - target: x86_64 - modules: [] - environment: {} - extra_rpaths: [] # binary caches mirrors: diff --git a/Tools/machines/desktop/spack-ubuntu-rocm.yaml b/Tools/machines/desktop/spack-ubuntu-rocm.yaml index 7eee1baa13c..851ed04c0f9 100644 --- a/Tools/machines/desktop/spack-ubuntu-rocm.yaml +++ b/Tools/machines/desktop/spack-ubuntu-rocm.yaml @@ -21,7 +21,6 @@ spack: - cmake - ecp-data-vis-sdk +adios2 +ascent +hdf5 +sensei - hdf5 - - heffte - hip - lapackpp - llvm-amdgpu @@ -115,19 +114,6 @@ spack: modules: [] environment: {} extra_rpaths: [] - - compiler: - spec: gcc@8.3.0 - paths: - cc: /usr/bin/gcc - cxx: /usr/bin/g++ - f77: /usr/bin/gfortran - fc: /usr/bin/gfortran - flags: {} - operating_system: debian10 - target: x86_64 - modules: [] - environment: {} - extra_rpaths: [] # binary caches mirrors: diff --git a/Tools/machines/frontier-olcf/frontier_warpx.profile.example b/Tools/machines/frontier-olcf/frontier_warpx.profile.example index 5ca6e1e1622..16f28a0fca2 100644 --- a/Tools/machines/frontier-olcf/frontier_warpx.profile.example +++ b/Tools/machines/frontier-olcf/frontier_warpx.profile.example @@ -6,12 +6,15 @@ export MY_PROFILE=$(cd $(dirname $BASH_SOURCE) && pwd)"/"$(basename $BASH_SOURCE if [ -z ${proj-} ]; then echo "WARNING: The 'proj' variable is not yet set in your $MY_PROFILE file! Please edit its line 2 to continue!"; return; fi # required dependencies -module switch Core Core/24.07 module load cmake/3.27.9 module load craype-accel-amd-gfx90a -module load rocm/5.7.1 -module load cray-mpich/8.1.28 -module load cce/17.0.0 # must be loaded after rocm +module load rocm/6.2.4 +module load cray-mpich/8.1.31 +module load cce/18.0.1 # must be loaded after rocm +# https://docs.olcf.ornl.gov/systems/frontier_user_guide.html#compatible-compiler-rocm-toolchain-versions + +# Fix for OpenMP Runtime (OLCFHELP-21543) +export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${ROCM_PATH}/llvm/lib # optional: faster builds module load ccache @@ -27,11 +30,11 @@ export LD_LIBRARY_PATH=${HOME}/sw/frontier/gpu/blaspp-2024.05.31/lib64:$LD_LIBRA export LD_LIBRARY_PATH=${HOME}/sw/frontier/gpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH # optional: for QED lookup table generation support -module load boost/1.79.0 +module load boost/1.85.0 # optional: for openPMD support -module load adios2/2.8.3-mpi -module load hdf5/1.12.1-mpi +module load adios2/2.10.2-mpi +module load hdf5/1.14.3-mpi # optional: for Python bindings or libEnsemble module load cray-python/3.11.5 diff --git a/Tools/machines/frontier-olcf/install_dependencies.sh b/Tools/machines/frontier-olcf/install_dependencies.sh index fd1d28e76b5..17b4955e7c4 100755 --- a/Tools/machines/frontier-olcf/install_dependencies.sh +++ b/Tools/machines/frontier-olcf/install_dependencies.sh @@ -87,11 +87,17 @@ python3 -m pip install --upgrade build python3 -m pip install --upgrade packaging python3 -m pip install --upgrade wheel python3 -m pip install --upgrade setuptools -# cupy and h5py need an older Cython -# https://github.com/cupy/cupy/issues/4610 -# https://github.com/h5py/h5py/issues/2268 -python3 -m pip install --upgrade "cython<3.0" +python3 -m pip install --upgrade "cython>=3.0" +# cupy for ROCm +# https://docs.cupy.dev/en/stable/install.html#building-cupy-for-rocm-from-source +# https://github.com/cupy/cupy/issues/7830 +CC=cc CXX=CC \ +CUPY_INSTALL_USE_HIP=1 \ +ROCM_HOME=${ROCM_PATH} \ +HCC_AMDGPU_TARGET=${AMREX_AMD_ARCH} \ + python3 -m pip install -v git+https://github.com/cupy/cupy.git@e669b994f976565bf2da4b1f82de51e10b58fbe1 python3 -m pip install --upgrade numpy +python3 -m pip install --upgrade h5py python3 -m pip install --upgrade pandas python3 -m pip install --upgrade scipy MPICC="cc -shared" python3 -m pip install --upgrade mpi4py --no-cache-dir --no-build-isolation --no-binary mpi4py @@ -100,14 +106,6 @@ python3 -m pip install --upgrade matplotlib python3 -m pip install --upgrade yt # install or update WarpX dependencies such as picmistandard python3 -m pip install --upgrade -r $HOME/src/warpx/requirements.txt -# cupy for ROCm -# https://docs.cupy.dev/en/stable/install.html#building-cupy-for-rocm-from-source -# https://github.com/cupy/cupy/issues/7830 -CC=cc CXX=CC \ -CUPY_INSTALL_USE_HIP=1 \ -ROCM_HOME=${ROCM_PATH} \ -HCC_AMDGPU_TARGET=${AMREX_AMD_ARCH} \ - python3 -m pip install -v cupy # optional: for optimas (based on libEnsemble & ax->botorch->gpytorch->pytorch) #python3 -m pip install --upgrade torch --index-url https://download.pytorch.org/whl/rocm5.4.2 #python3 -m pip install -r $HOME/src/warpx/Tools/optimas/requirements.txt diff --git a/Tools/machines/fugaku-riken/fugaku_warpx.profile.example b/Tools/machines/fugaku-riken/fugaku_warpx.profile.example index caf85983b58..7041846ebbc 100644 --- a/Tools/machines/fugaku-riken/fugaku_warpx.profile.example +++ b/Tools/machines/fugaku-riken/fugaku_warpx.profile.example @@ -18,7 +18,7 @@ spack load boost@1.80.0%fj@4.8.1/zc5pwgc # optional: for openPMD support spack load hdf5@1.12.2%fj@4.8.1/im6lxev export CMAKE_PREFIX_PATH=${HOME}/sw/fugaku/a64fx/c-blosc-1.21.1-install:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${HOME}/sw/fugaku/a64fx/adios2-2.8.3-install:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${HOME}/sw/fugaku/a64fx/adios2-2.10.2-install:$CMAKE_PREFIX_PATH # compiler environment hints export CC=$(which mpifcc) diff --git a/Tools/machines/fugaku-riken/install_dependencies.sh b/Tools/machines/fugaku-riken/install_dependencies.sh index 3ceb45e4558..eb5098fb43f 100755 --- a/Tools/machines/fugaku-riken/install_dependencies.sh +++ b/Tools/machines/fugaku-riken/install_dependencies.sh @@ -42,12 +42,12 @@ if [ -d ${SRC_DIR}/c-blosc ] then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi rm -rf ${SRC_DIR}/adios2-fugaku-build -cmake -S ${SRC_DIR}/adios2 -B ${SRC_DIR}/adios2-fugaku-build -DBUILD_SHARED_LIBS=OFF -DADIOS2_USE_Blosc=ON -DBUILD_TESTING=OFF -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3-install +cmake -S ${SRC_DIR}/adios2 -B ${SRC_DIR}/adios2-fugaku-build -DBUILD_SHARED_LIBS=OFF -DADIOS2_USE_Blosc=ON -DBUILD_TESTING=OFF -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2-install cmake --build ${SRC_DIR}/adios2-fugaku-build --target install -j 48 rm -rf ${SRC_DIR}/adios2-fugaku-build diff --git a/Tools/machines/greatlakes-umich/greatlakes_v100_warpx.profile.example b/Tools/machines/greatlakes-umich/greatlakes_v100_warpx.profile.example index c08255e7962..140593deb55 100644 --- a/Tools/machines/greatlakes-umich/greatlakes_v100_warpx.profile.example +++ b/Tools/machines/greatlakes-umich/greatlakes_v100_warpx.profile.example @@ -21,16 +21,16 @@ module load phdf5/1.12.1 SW_DIR="${HOME}/sw/greatlakes/v100" export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc2-2.14.4:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.0:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${SW_DIR}/c-blosc2-2.14.4/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.0/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export PATH=${SW_DIR}/adios2-2.10.0/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: for Python bindings or libEnsemble module load python/3.12.1 diff --git a/Tools/machines/greatlakes-umich/install_v100_dependencies.sh b/Tools/machines/greatlakes-umich/install_v100_dependencies.sh index 30faec52421..c6925442d9f 100755 --- a/Tools/machines/greatlakes-umich/install_v100_dependencies.sh +++ b/Tools/machines/greatlakes-umich/install_v100_dependencies.sh @@ -57,10 +57,10 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.10.0 + git checkout v2.10.2 cd - else - git clone -b v2.10.0 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-v100-build cmake \ @@ -71,7 +71,7 @@ cmake \ -DADIOS2_USE_Fortran=OFF \ -DADIOS2_USE_Python=OFF \ -DADIOS2_USE_ZeroMQ=OFF \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.0 + -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build ${build_dir}/adios2-v100-build --target install -j 8 rm -rf ${build_dir}/adios2-v100-build diff --git a/Tools/machines/hpc3-uci/hpc3_gpu_warpx.profile.example b/Tools/machines/hpc3-uci/hpc3_gpu_warpx.profile.example index 970dc980347..ddb70fbf255 100644 --- a/Tools/machines/hpc3-uci/hpc3_gpu_warpx.profile.example +++ b/Tools/machines/hpc3-uci/hpc3_gpu_warpx.profile.example @@ -18,16 +18,16 @@ module load boost/1.78.0/gcc.11.2.0 module load OpenBLAS/0.3.21 module load hdf5/1.13.1/gcc.11.2.0-openmpi.4.1.2 export CMAKE_PREFIX_PATH=${HOME}/sw/hpc3/gpu/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${HOME}/sw/hpc3/gpu/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${HOME}/sw/hpc3/gpu/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${HOME}/sw/hpc3/gpu/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${HOME}/sw/hpc3/gpu/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${HOME}/sw/hpc3/gpu/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${HOME}/sw/hpc3/gpu/adios2-2.8.3/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${HOME}/sw/hpc3/gpu/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${HOME}/sw/hpc3/gpu/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${HOME}/sw/hpc3/gpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export PATH=${HOME}/sw/hpc3/gpu/adios2-2.8.3/bin:${PATH} +export PATH=${HOME}/sw/hpc3/gpu/adios2-2.10.2/bin:${PATH} # optional: CCache #module load ccache # missing diff --git a/Tools/machines/hpc3-uci/install_gpu_dependencies.sh b/Tools/machines/hpc3-uci/install_gpu_dependencies.sh index c4c31dd4066..e4b9f4caa5a 100755 --- a/Tools/machines/hpc3-uci/install_gpu_dependencies.sh +++ b/Tools/machines/hpc3-uci/install_gpu_dependencies.sh @@ -64,13 +64,13 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-pm-gpu-build -cmake -S $HOME/src/adios2 -B $HOME/src/adios2-pm-gpu-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_HDF5=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 +cmake -S $HOME/src/adios2 -B $HOME/src/adios2-pm-gpu-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_HDF5=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build $HOME/src/adios2-pm-gpu-build --target install --parallel 8 rm -rf $HOME/src/adios2-pm-gpu-build diff --git a/Tools/machines/karolina-it4i/install_dependencies.sh b/Tools/machines/karolina-it4i/install_dependencies.sh index 9cc4f1ee144..33d8462b55f 100755 --- a/Tools/machines/karolina-it4i/install_dependencies.sh +++ b/Tools/machines/karolina-it4i/install_dependencies.sh @@ -53,7 +53,7 @@ python -m pip install --user --upgrade matplotlib #python -m pip install --user --upgrade yt # install or update WarpX dependencies -python -m pip install --user --upgrade picmistandard==0.31.0 +python -m pip install --user --upgrade picmistandard==0.33.0 python -m pip install --user --upgrade lasy # optional: for optimas (based on libEnsemble & ax->botorch->gpytorch->pytorch) diff --git a/Tools/machines/karolina-it4i/spack-karolina-cuda.yaml b/Tools/machines/karolina-it4i/spack-karolina-cuda.yaml index 1cb6a4ac209..ead49f06fab 100644 --- a/Tools/machines/karolina-it4i/spack-karolina-cuda.yaml +++ b/Tools/machines/karolina-it4i/spack-karolina-cuda.yaml @@ -20,7 +20,7 @@ spack: - py-cython - py-mpi4py - py-numpy@1.24.2 - - openpmd-api@0.15.2 +python + - openpmd-api@0.16.1 +python - py-periodictable@1.5.0 - py-h5py # optional diff --git a/Tools/machines/lassen-llnl/install_v100_dependencies_toss3.sh b/Tools/machines/lassen-llnl/install_v100_dependencies_toss3.sh index 1b14159cd22..b4e80f2ddea 100644 --- a/Tools/machines/lassen-llnl/install_v100_dependencies_toss3.sh +++ b/Tools/machines/lassen-llnl/install_v100_dependencies_toss3.sh @@ -69,12 +69,12 @@ if [ -d ${SRC_DIR}/adios2 ] then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi -cmake -S ${SRC_DIR}/adios2 -B ${build_dir}/adios2-lassen-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_SST=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 +cmake -S ${SRC_DIR}/adios2 -B ${build_dir}/adios2-lassen-build -DBUILD_TESTING=OFF -DADIOS2_BUILD_EXAMPLES=OFF -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_SST=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build ${build_dir}/adios2-lassen-build --target install -j 10 # BLAS++ (for PSATD+RZ) @@ -114,7 +114,7 @@ rm -rf ${SW_DIR}/venvs/warpx-lassen-toss3 python3 -m venv ${SW_DIR}/venvs/warpx-lassen-toss3 source ${SW_DIR}/venvs/warpx-lassen-toss3/bin/activate python3 -m pip install --upgrade pip -python3 -m pip cache purge +# python3 -m pip cache purge # error: pip cache commands can not function since cache is disabled python3 -m pip install --upgrade build python3 -m pip install --upgrade packaging python3 -m pip install --upgrade wheel diff --git a/Tools/machines/lassen-llnl/lassen_v100_warpx_toss3.profile.example b/Tools/machines/lassen-llnl/lassen_v100_warpx_toss3.profile.example index 99e61a2fbf6..a2b9356104b 100644 --- a/Tools/machines/lassen-llnl/lassen_v100_warpx_toss3.profile.example +++ b/Tools/machines/lassen-llnl/lassen_v100_warpx_toss3.profile.example @@ -14,12 +14,12 @@ SRC_DIR="/usr/workspace/${USER}/lassen/src" SW_DIR="/usr/workspace/${USER}/lassen-toss3/gpu" export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/hdf5-1.14.1.2:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/hdf5-1.14.1.2/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.8.3/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export PATH=${SW_DIR}/hdf5-1.14.1.2/bin:${PATH} -export PATH=${SW_DIR}/adios2-2.8.3/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: for PSATD in RZ geometry support export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:$CMAKE_PREFIX_PATH diff --git a/Tools/machines/lawrencium-lbnl/lawrencium_warpx.profile.example b/Tools/machines/lawrencium-lbnl/lawrencium_warpx.profile.example index 62f80433233..fbbf0267e1e 100644 --- a/Tools/machines/lawrencium-lbnl/lawrencium_warpx.profile.example +++ b/Tools/machines/lawrencium-lbnl/lawrencium_warpx.profile.example @@ -14,11 +14,11 @@ module load boost/1.83.0 module load hdf5/1.14.3 export CMAKE_PREFIX_PATH=$HOME/sw/v100/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=$HOME/sw/v100/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=$HOME/sw/v100/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=$HOME/sw/v100/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=$HOME/sw/v100/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH -export PATH=$HOME/sw/v100/adios2-2.8.3/bin:$PATH +export PATH=$HOME/sw/v100/adios2-2.10.2/bin:$PATH # optional: CCache #module load ccache # missing diff --git a/Tools/machines/leonardo-cineca/install_gpu_dependencies.sh b/Tools/machines/leonardo-cineca/install_gpu_dependencies.sh index 4d89e30cd29..2df123ba0ee 100644 --- a/Tools/machines/leonardo-cineca/install_gpu_dependencies.sh +++ b/Tools/machines/leonardo-cineca/install_gpu_dependencies.sh @@ -30,15 +30,14 @@ mkdir -p ${SW_DIR} if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 - git fetch - git checkout master - git pull + git fetch --prune + git checkout v2.10.2 cd - else - git clone https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-gpu-build -cmake -S $HOME/src/adios2 -B $HOME/src/adios2-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-master +cmake -S $HOME/src/adios2 -B $HOME/src/adios2-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build $HOME/src/adios2-gpu-build --target install -j 16 rm -rf $HOME/src/adios2-gpu-build diff --git a/Tools/machines/leonardo-cineca/leonardo_gpu_warpx.profile.example b/Tools/machines/leonardo-cineca/leonardo_gpu_warpx.profile.example index dd8e79ffb37..763bb07ad17 100644 --- a/Tools/machines/leonardo-cineca/leonardo_gpu_warpx.profile.example +++ b/Tools/machines/leonardo-cineca/leonardo_gpu_warpx.profile.example @@ -15,16 +15,16 @@ module load boost/1.80.0--openmpi--4.1.4--gcc--11.3.0 # optional: for openPMD and PSATD+RZ support module load openblas/0.3.21--gcc--11.3.0 export CMAKE_PREFIX_PATH=/leonardo/prod/spack/03/install/0.19/linux-rhel8-icelake/gcc-11.3.0/c-blosc-1.21.1-aifmix6v5lwxgt7rigwoebalrgbcnv26:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=$HOME/sw/adios2-master:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=$HOME/sw/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=$HOME/sw/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=$HOME/sw/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=/leonardo/prod/spack/03/install/0.19/linux-rhel8-icelake/gcc-11.3.0/c-blosc-1.21.1-aifmix6v5lwxgt7rigwoebalrgbcnv26/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=$HOME/sw/adios2-master/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=$HOME/sw/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=$HOME/sw/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=$HOME/sw/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export PATH=$HOME/sw/adios2-master/bin:$PATH +export PATH=$HOME/sw/adios2-2.10.2/bin:$PATH # optional: for Python bindings or libEnsemble module load python/3.10.8--gcc--11.3.0 diff --git a/Tools/machines/lonestar6-tacc/install_a100_dependencies.sh b/Tools/machines/lonestar6-tacc/install_a100_dependencies.sh index cd29664a978..1ade3fe77d4 100755 --- a/Tools/machines/lonestar6-tacc/install_a100_dependencies.sh +++ b/Tools/machines/lonestar6-tacc/install_a100_dependencies.sh @@ -56,13 +56,13 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-a100-build -cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-a100-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 +cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-a100-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build ${build_dir}/adios2-a100-build --target install -j 16 rm -rf ${build_dir}/adios2-a100-build @@ -96,45 +96,6 @@ CXXFLAGS="-DLAPACK_FORTRAN_ADD_" cmake -S $HOME/src/lapackpp -B ${build_dir}/lap cmake --build ${build_dir}/lapackpp-a100-build --target install --parallel 16 rm -rf ${build_dir}/lapackpp-a100-build -# heFFTe -if [ -d $HOME/src/heffte ] -then - cd $HOME/src/heffte - git fetch --prune - git checkout v2.4.0 - cd - -else - git clone -b v2.4.0 https://github.com/icl-utk-edu/heffte.git ${HOME}/src/heffte -fi -rm -rf ${HOME}/src/heffte-a100-build -cmake \ - -S ${HOME}/src/heffte \ - -B ${build_dir}/heffte-a100-build \ - -DBUILD_SHARED_LIBS=ON \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_CXX_STANDARD=17 \ - -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/heffte-2.4.0 \ - -DHeffte_DISABLE_GPU_AWARE_MPI=OFF \ - -DHeffte_ENABLE_AVX=OFF \ - -DHeffte_ENABLE_AVX512=OFF \ - -DHeffte_ENABLE_FFTW=OFF \ - -DHeffte_ENABLE_CUDA=ON \ - -DHeffte_ENABLE_ROCM=OFF \ - -DHeffte_ENABLE_ONEAPI=OFF \ - -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_SEQUENTIAL_TESTING=OFF \ - -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_TRACING=OFF \ - -DHeffte_ENABLE_PYTHON=OFF \ - -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_SWIG=OFF \ - -DHeffte_ENABLE_MAGMA=OFF -cmake --build ${build_dir}/heffte-a100-build --target install --parallel 16 -rm -rf ${build_dir}/heffte-a100-build - - # Python ###################################################################### # python3 -m pip install --upgrade pip diff --git a/Tools/machines/lonestar6-tacc/lonestar6_warpx_a100.profile.example b/Tools/machines/lonestar6-tacc/lonestar6_warpx_a100.profile.example index 148299f281c..5b6c91b6a4d 100644 --- a/Tools/machines/lonestar6-tacc/lonestar6_warpx_a100.profile.example +++ b/Tools/machines/lonestar6-tacc/lonestar6_warpx_a100.profile.example @@ -17,18 +17,16 @@ module load phdf5/1.10.4 SW_DIR="${WORK}/sw/lonestar6/sw/lonestar6/a100" export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:${CMAKE_PREFIX_PATH} -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.8.3:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:${CMAKE_PREFIX_PATH} export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:${CMAKE_PREFIX_PATH} export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:${CMAKE_PREFIX_PATH} -export CMAKE_PREFIX_PATH=${SW_DIR}/heffte-2.4.0:${CMAKE_PREFIX_PATH} export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.8.3/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/heffte-2.4.0/lib64:$LD_LIBRARY_PATH -export PATH=${SW_DIR}/adios2-2.8.3/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: CCache #module load ccache # TODO: request from support diff --git a/Tools/machines/lumi-csc/install_dependencies.sh b/Tools/machines/lumi-csc/install_dependencies.sh index 2fd31b79bce..e149b8abd43 100755 --- a/Tools/machines/lumi-csc/install_dependencies.sh +++ b/Tools/machines/lumi-csc/install_dependencies.sh @@ -124,10 +124,10 @@ if [ -d ${SRC_DIR}/adios2 ] then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi rm -rf ${build_dir}/adios2-lu-build cmake -S ${SRC_DIR}/adios2 \ @@ -137,7 +137,7 @@ cmake -S ${SRC_DIR}/adios2 \ -DADIOS2_USE_HDF5=OFF \ -DADIOS2_USE_Python=OFF \ -DADIOS2_USE_ZeroMQ=OFF \ - -DCMAKE_INSTALL_PREFIX=${HOME}/sw/lumi/gpu/adios2-2.8.3 + -DCMAKE_INSTALL_PREFIX=${HOME}/sw/lumi/gpu/adios2-2.10.2 cmake --build ${build_dir}/adios2-lu-build --target install -j 16 rm -rf ${build_dir}/adios2-lu-build diff --git a/Tools/machines/lumi-csc/lumi_warpx.profile.example b/Tools/machines/lumi-csc/lumi_warpx.profile.example index 915f976f4ab..967638e8461 100644 --- a/Tools/machines/lumi-csc/lumi_warpx.profile.example +++ b/Tools/machines/lumi-csc/lumi_warpx.profile.example @@ -22,9 +22,9 @@ module load Boost/1.82.0-cpeCray-23.09 # optional: for openPMD support export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/hdf5-1.14.1.2:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export PATH=${SW_DIR}/hdf5-1.14.1.2/bin:${PATH} -export PATH=${SW_DIR}/adios2-2.8.3/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: for Python bindings or libEnsemble module load cray-python/3.11.7 diff --git a/Tools/machines/perlmutter-nersc/Containerfile b/Tools/machines/perlmutter-nersc/Containerfile new file mode 100644 index 00000000000..5a8553c2619 --- /dev/null +++ b/Tools/machines/perlmutter-nersc/Containerfile @@ -0,0 +1,167 @@ +# Build this container from its current directory: +# podman build --build-arg NJOBS=6 -t warpx-perlmutter-dev . +# Adjust NJOBS to the number of processes to use for parallel compilation. +# +# Run from the via WarpX source directory +# podman run -v ${PWD}:/opt/warpx -it warpx-perlmutter-dev +# then +# cd /opt/warpx +# and compile. + +# Base System and Essential Tools Installation +FROM nvidia/cuda:12.6.0-devel-ubuntu22.04 AS base + +# parallel builds +ARG NJOBS +ENV NJOBS=$NJOBS + +# Set up environment variables +ENV DEBIAN_FRONTEND=noninteractive \ + SW_DIR=/opt/software \ + FORCE_UNSAFE_CONFIGURE=1 + +# Perlmutter A100 compilation optimization +ENV AMREX_CUDA_ARCH=8.0 \ + CUDAARCHS=80 \ + CXXFLAGS="-march=znver3" \ + CFLAGS="-march=znver3" + +# Install essential system dependencies including MPI libraries +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + autoconf \ + build-essential \ + ca-certificates \ + coreutils \ + curl \ + environment-modules \ + gfortran \ + git \ + openssh-server \ + python3 \ + python3-pip \ + python3-dev \ + python3-venv \ + unzip \ + vim \ + libmpich-dev \ + cmake \ + libblas-dev \ + liblapack-dev \ + g++ \ + pkg-config \ + libbz2-dev \ + zlib1g-dev \ + libpng-dev \ + libzstd-dev \ + && rm -rf /var/lib/apt/lists/* + +# Install c-blosc from source +FROM base AS c-blosc + +RUN git clone -b v1.21.1 https://github.com/Blosc/c-blosc.git /tmp/c-blosc && \ + cmake \ + -S /tmp/c-blosc \ + -B /tmp/c-blosc-build \ + -DCMAKE_INSTALL_PREFIX=/usr .. && \ + cmake --build /tmp/c-blosc-build \ + --target install \ + -j${NJOBS} && \ + rm -rf /tmp/c-blosc* + +# Install ADIOS2 from source +FROM base AS adios2 + +# Ensure c-blosc is installed before ADIOS2 +COPY --from=c-blosc /usr /usr + +# Verify the location of Blosc library +RUN find /usr -name 'libblosc*' + +# Ensure Blosc library paths are correctly configured +ENV BLOSC_LIBRARY=/usr/lib/libblosc.so.1.21.1 +ENV BLOSC_INCLUDE_DIR=/usr/include + +# Install ADIOS2 +RUN git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git /tmp/adios2 && \ + cd /tmp/adios2 && \ + cmake -S . -B build \ + -DADIOS2_USE_Blosc=ON \ + -DBLOSC_LIBRARY=${BLOSC_LIBRARY} \ + -DBLOSC_INCLUDE_DIR=${BLOSC_INCLUDE_DIR} \ + -DADIOS2_USE_Fortran=OFF \ + -DADIOS2_USE_Python=OFF \ + -DADIOS2_USE_ZeroMQ=OFF \ + -DADIOS2_USE_BZip2=ON \ + -DADIOS2_USE_ZFP=OFF \ + -DADIOS2_USE_SZ=OFF \ + -DADIOS2_USE_MGARD=OFF \ + -DADIOS2_USE_PNG=ON \ + -DCMAKE_INSTALL_PREFIX=/usr .. && \ + cmake --build build --target install -j${NJOBS} && \ + rm -rf /tmp/adios2 + +# Install BLAS++ and LAPACK++ +FROM base AS blaspp_lapackpp + +RUN git clone -b v2024.05.31 https://github.com/icl-utk-edu/blaspp.git /tmp/blaspp && \ + cd /tmp/blaspp && \ + cmake -S . -B build \ + -Duse_openmp=OFF \ + -Dgpu_backend=cuda \ + -DCMAKE_CXX_STANDARD=17 \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DBLAS_LIBRARIES=/usr/lib/x86_64-linux-gnu/libblas.so \ + -DLAPACK_LIBRARIES=/usr/lib/x86_64-linux-gnu/liblapack.so .. && \ + cmake --build build \ + --target install \ + -j${NJOBS} && \ + rm -rf /tmp/blaspp + +RUN git clone -b v2024.05.31 https://github.com/icl-utk-edu/lapackpp.git /tmp/lapackpp && \ + cd /tmp/lapackpp && \ + cmake -S . -B build \ + -DCMAKE_CXX_STANDARD=17 \ + -Dbuild_tests=OFF \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DLAPACK_LIBRARIES=/usr/lib/x86_64-linux-gnu/liblapack.so .. && \ + cmake --build build \ + --target install -j${NJOBS} && \ + rm -rf /tmp/lapackpp + +# Final Image +FROM base AS final + +# Copy installed software from previous stages +COPY --from=c-blosc /usr /usr +COPY --from=adios2 /usr /usr +COPY --from=blaspp_lapackpp /usr /usr + +# Create and activate Python virtual environment +RUN python3 -m venv /opt/venv && \ + /opt/venv/bin/pip install --no-cache-dir \ + wheel \ + numpy \ + pandas \ + scipy \ + matplotlib \ + jupyter \ + scikit-learn \ + openpmd-api \ + yt \ + cupy-cuda12x \ + torch \ + optimas[all] \ + cython \ + packaging \ + build \ + setuptools + +# Set up the environment for the virtual environment +ENV PATH="/opt/venv/bin:${PATH}" + +# Set up entrypoint +ENTRYPOINT ["/bin/bash", "-c"] + +# Default command +CMD ["/bin/bash"] diff --git a/Tools/machines/perlmutter-nersc/install_cpu_dependencies.sh b/Tools/machines/perlmutter-nersc/install_cpu_dependencies.sh index 437300b8303..5be1ef7b9aa 100755 --- a/Tools/machines/perlmutter-nersc/install_cpu_dependencies.sh +++ b/Tools/machines/perlmutter-nersc/install_cpu_dependencies.sh @@ -31,7 +31,7 @@ fi # Remove old dependencies ##################################################### # -SW_DIR="${CFS}/${proj}/${USER}/sw/perlmutter/cpu" +SW_DIR="${PSCRATCH}/storage/sw/warpx/perlmutter/cpu" rm -rf ${SW_DIR} mkdir -p ${SW_DIR} @@ -44,9 +44,29 @@ python3 -m pip uninstall -qqq -y mpi4py 2>/dev/null || true # General extra dependencies ################################################## # +# build parallelism +PARALLEL=16 + # tmpfs build directory: avoids issues often seen with $HOME and is faster build_dir=$(mktemp -d) +# CCache +curl -Lo ccache.tar.xz https://github.com/ccache/ccache/releases/download/v4.10.2/ccache-4.10.2-linux-x86_64.tar.xz +tar -xf ccache.tar.xz +mv ccache-4.10.2-linux-x86_64 ${SW_DIR}/ccache-4.10.2 +rm -rf ccache.tar.xz + +# Boost (QED tables) +rm -rf $HOME/src/boost-temp +mkdir -p $HOME/src/boost-temp +curl -Lo $HOME/src/boost-temp/boost.tar.gz https://archives.boost.io/release/1.82.0/source/boost_1_82_0.tar.gz +tar -xzf $HOME/src/boost-temp/boost.tar.gz -C $HOME/src/boost-temp +cd $HOME/src/boost-temp/boost_1_82_0 +./bootstrap.sh --with-libraries=math --prefix=${SW_DIR}/boost-1.82.0 +./b2 cxxflags="-std=c++17" install -j ${PARALLEL} +cd - +rm -rf $HOME/src/boost-temp + # c-blosc (I/O compression) if [ -d $HOME/src/c-blosc ] then @@ -59,7 +79,7 @@ else fi rm -rf $HOME/src/c-blosc-pm-cpu-build cmake -S $HOME/src/c-blosc -B ${build_dir}/c-blosc-pm-cpu-build -DBUILD_TESTS=OFF -DBUILD_BENCHMARKS=OFF -DDEACTIVATE_AVX2=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/c-blosc-1.21.1 -cmake --build ${build_dir}/c-blosc-pm-cpu-build --target install --parallel 16 +cmake --build ${build_dir}/c-blosc-pm-cpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/c-blosc-pm-cpu-build # ADIOS2 @@ -67,14 +87,14 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-pm-cpu-build -cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-pm-cpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_CUDA=OFF -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 -cmake --build ${build_dir}/adios2-pm-cpu-build --target install -j 16 +cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-pm-cpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_CUDA=OFF -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 +cmake --build ${build_dir}/adios2-pm-cpu-build --target install -j ${PARALLEL} rm -rf ${build_dir}/adios2-pm-cpu-build # BLAS++ (for PSATD+RZ) @@ -89,7 +109,7 @@ else fi rm -rf $HOME/src/blaspp-pm-cpu-build CXX=$(which CC) cmake -S $HOME/src/blaspp -B ${build_dir}/blaspp-pm-cpu-build -Duse_openmp=ON -Dgpu_backend=OFF -DCMAKE_CXX_STANDARD=17 -DCMAKE_INSTALL_PREFIX=${SW_DIR}/blaspp-2024.05.31 -cmake --build ${build_dir}/blaspp-pm-cpu-build --target install --parallel 16 +cmake --build ${build_dir}/blaspp-pm-cpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/blaspp-pm-cpu-build # LAPACK++ (for PSATD+RZ) @@ -104,48 +124,9 @@ else fi rm -rf $HOME/src/lapackpp-pm-cpu-build CXX=$(which CC) CXXFLAGS="-DLAPACK_FORTRAN_ADD_" cmake -S $HOME/src/lapackpp -B ${build_dir}/lapackpp-pm-cpu-build -DCMAKE_CXX_STANDARD=17 -Dbuild_tests=OFF -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DCMAKE_INSTALL_PREFIX=${SW_DIR}/lapackpp-2024.05.31 -cmake --build ${build_dir}/lapackpp-pm-cpu-build --target install --parallel 16 +cmake --build ${build_dir}/lapackpp-pm-cpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/lapackpp-pm-cpu-build -# heFFTe -if [ -d $HOME/src/heffte ] -then - cd $HOME/src/heffte - git fetch --prune - git checkout v2.4.0 - cd - -else - git clone -b v2.4.0 https://github.com/icl-utk-edu/heffte.git ${HOME}/src/heffte -fi -rm -rf ${HOME}/src/heffte-pm-cpu-build -cmake \ - -S ${HOME}/src/heffte \ - -B ${build_dir}/heffte-pm-cpu-build \ - -DBUILD_SHARED_LIBS=ON \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_CXX_STANDARD=17 \ - -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/heffte-2.4.0 \ - -DHeffte_DISABLE_GPU_AWARE_MPI=ON \ - -DHeffte_ENABLE_AVX=ON \ - -DHeffte_ENABLE_AVX512=OFF \ - -DHeffte_ENABLE_FFTW=ON \ - -DHeffte_ENABLE_CUDA=OFF \ - -DHeffte_ENABLE_ROCM=OFF \ - -DHeffte_ENABLE_ONEAPI=OFF \ - -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_SEQUENTIAL_TESTING=OFF \ - -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_TRACING=OFF \ - -DHeffte_ENABLE_PYTHON=OFF \ - -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_SWIG=OFF \ - -DHeffte_ENABLE_MAGMA=OFF -cmake --build ${build_dir}/heffte-pm-cpu-build --target install --parallel 16 -rm -rf ${build_dir}/heffte-pm-cpu-build - - # Python ###################################################################### # python3 -m pip install --upgrade pip diff --git a/Tools/machines/perlmutter-nersc/install_gpu_dependencies.sh b/Tools/machines/perlmutter-nersc/install_gpu_dependencies.sh index da48d9543a0..a029b428e8a 100755 --- a/Tools/machines/perlmutter-nersc/install_gpu_dependencies.sh +++ b/Tools/machines/perlmutter-nersc/install_gpu_dependencies.sh @@ -31,7 +31,7 @@ fi # Remove old dependencies ##################################################### # -SW_DIR="${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu" +SW_DIR="${PSCRATCH}/storage/sw/warpx/perlmutter/gpu" rm -rf ${SW_DIR} mkdir -p ${SW_DIR} @@ -44,9 +44,29 @@ python3 -m pip uninstall -qqq -y mpi4py 2>/dev/null || true # General extra dependencies ################################################## # +# build parallelism +PARALLEL=16 + # tmpfs build directory: avoids issues often seen with $HOME and is faster build_dir=$(mktemp -d) +# CCache +curl -Lo ccache.tar.xz https://github.com/ccache/ccache/releases/download/v4.10.2/ccache-4.10.2-linux-x86_64.tar.xz +tar -xf ccache.tar.xz +mv ccache-4.10.2-linux-x86_64 ${SW_DIR}/ccache-4.10.2 +rm -rf ccache.tar.xz + +# Boost (QED tables) +rm -rf $HOME/src/boost-temp +mkdir -p $HOME/src/boost-temp +curl -Lo $HOME/src/boost-temp/boost.tar.gz https://archives.boost.io/release/1.82.0/source/boost_1_82_0.tar.gz +tar -xzf $HOME/src/boost-temp/boost.tar.gz -C $HOME/src/boost-temp +cd $HOME/src/boost-temp/boost_1_82_0 +./bootstrap.sh --with-libraries=math --prefix=${SW_DIR}/boost-1.82.0 +./b2 cxxflags="-std=c++17" install -j ${PARALLEL} +cd - +rm -rf $HOME/src/boost-temp + # c-blosc (I/O compression) if [ -d $HOME/src/c-blosc ] then @@ -59,7 +79,7 @@ else fi rm -rf $HOME/src/c-blosc-pm-gpu-build cmake -S $HOME/src/c-blosc -B ${build_dir}/c-blosc-pm-gpu-build -DBUILD_TESTS=OFF -DBUILD_BENCHMARKS=OFF -DDEACTIVATE_AVX2=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/c-blosc-1.21.1 -cmake --build ${build_dir}/c-blosc-pm-gpu-build --target install --parallel 16 +cmake --build ${build_dir}/c-blosc-pm-gpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/c-blosc-pm-gpu-build # ADIOS2 @@ -67,14 +87,14 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-pm-gpu-build -cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-pm-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 -cmake --build ${build_dir}/adios2-pm-gpu-build --target install -j 16 +cmake -S $HOME/src/adios2 -B ${build_dir}/adios2-pm-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 +cmake --build ${build_dir}/adios2-pm-gpu-build --target install -j ${PARALLEL} rm -rf ${build_dir}/adios2-pm-gpu-build # BLAS++ (for PSATD+RZ) @@ -89,7 +109,7 @@ else fi rm -rf $HOME/src/blaspp-pm-gpu-build CXX=$(which CC) cmake -S $HOME/src/blaspp -B ${build_dir}/blaspp-pm-gpu-build -Duse_openmp=OFF -Dgpu_backend=cuda -DCMAKE_CXX_STANDARD=17 -DCMAKE_INSTALL_PREFIX=${SW_DIR}/blaspp-2024.05.31 -cmake --build ${build_dir}/blaspp-pm-gpu-build --target install --parallel 16 +cmake --build ${build_dir}/blaspp-pm-gpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/blaspp-pm-gpu-build # LAPACK++ (for PSATD+RZ) @@ -104,52 +124,9 @@ else fi rm -rf $HOME/src/lapackpp-pm-gpu-build CXX=$(which CC) CXXFLAGS="-DLAPACK_FORTRAN_ADD_" cmake -S $HOME/src/lapackpp -B ${build_dir}/lapackpp-pm-gpu-build -DCMAKE_CXX_STANDARD=17 -Dbuild_tests=OFF -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON -DCMAKE_INSTALL_PREFIX=${SW_DIR}/lapackpp-2024.05.31 -cmake --build ${build_dir}/lapackpp-pm-gpu-build --target install --parallel 16 +cmake --build ${build_dir}/lapackpp-pm-gpu-build --target install --parallel ${PARALLEL} rm -rf ${build_dir}/lapackpp-pm-gpu-build -# heFFTe -if [ -d $HOME/src/heffte ] -then - cd $HOME/src/heffte - git fetch --prune - git checkout v2.4.0 - cd - -else - git clone -b v2.4.0 https://github.com/icl-utk-edu/heffte.git ${HOME}/src/heffte -fi -rm -rf ${HOME}/src/heffte-pm-gpu-build -cmake \ - -S ${HOME}/src/heffte \ - -B ${build_dir}/heffte-pm-gpu-build \ - -DBUILD_SHARED_LIBS=ON \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_CXX_STANDARD=17 \ - -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/heffte-2.4.0 \ - -DHeffte_DISABLE_GPU_AWARE_MPI=OFF \ - -DHeffte_ENABLE_AVX=OFF \ - -DHeffte_ENABLE_AVX512=OFF \ - -DHeffte_ENABLE_FFTW=OFF \ - -DHeffte_ENABLE_CUDA=ON \ - -DHeffte_ENABLE_ROCM=OFF \ - -DHeffte_ENABLE_ONEAPI=OFF \ - -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_SEQUENTIAL_TESTING=OFF \ - -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_TRACING=OFF \ - -DHeffte_ENABLE_PYTHON=OFF \ - -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_SWIG=OFF \ - -DHeffte_ENABLE_MAGMA=OFF -cmake --build ${build_dir}/heffte-pm-gpu-build --target install --parallel 16 -rm -rf ${build_dir}/heffte-pm-gpu-build - -# work-around for heFFTe 2.4.0 bug with NVCC -# https://github.com/icl-utk-edu/heffte/pull/54 -sed -i 's/__AVX__/NOTDEFINED_DONOTUSE/g' ${SW_DIR}/heffte-2.4.0/include/stock_fft/heffte_stock_vec_types.h - - # Python ###################################################################### # python3 -m pip install --upgrade pip @@ -177,7 +154,7 @@ python3 -m pip install --upgrade cupy-cuda12x # CUDA 12 compatible wheel # optimas (based on libEnsemble & ax->botorch->gpytorch->pytorch) python3 -m pip install --upgrade torch # CUDA 12 compatible wheel python3 -m pip install --upgrade optimas[all] - +python3 -m pip install --upgrade lasy # remove build temporary directory rm -rf ${build_dir} diff --git a/Tools/machines/perlmutter-nersc/perlmutter_cpu_warpx.profile.example b/Tools/machines/perlmutter-nersc/perlmutter_cpu_warpx.profile.example index 94d598abf5b..860c5a9915f 100644 --- a/Tools/machines/perlmutter-nersc/perlmutter_cpu_warpx.profile.example +++ b/Tools/machines/perlmutter-nersc/perlmutter_cpu_warpx.profile.example @@ -7,37 +7,39 @@ if [ -z ${proj-} ]; then echo "WARNING: The 'proj' variable is not yet set in yo # required dependencies module load cpu -module load cmake/3.24.3 +module load cmake/3.30.2 module load cray-fftw/3.3.10.6 +# missing modules installed here +export SW_DIR=${PSCRATCH}/storage/sw/warpx/perlmutter/cpu + # optional: for QED support with detailed tables -export BOOST_ROOT=/global/common/software/spackecp/perlmutter/e4s-23.05/default/spack/opt/spack/linux-sles15-zen3/gcc-11.2.0/boost-1.82.0-ow5r5qrgslcwu33grygouajmuluzuzv3 +export CMAKE_PREFIX_PATH=${SW_DIR}/boost-1.82.0:${CMAKE_PREFIX_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/boost-1.82.0/lib:${LD_LIBRARY_PATH} # optional: for openPMD and PSATD+RZ support module load cray-hdf5-parallel/1.12.2.9 -export CMAKE_PREFIX_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/adios2-2.8.3:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/blaspp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/heffte-2.4.0:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:${CMAKE_PREFIX_PATH} -export LD_LIBRARY_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/adios2-2.8.3/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/heffte-2.4.0/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.1/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:${LD_LIBRARY_PATH} -export PATH=${CFS}/${proj}/${USER}/sw/perlmutter/cpu/adios2-2.8.3/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: CCache -export PATH=/global/common/software/spackecp/perlmutter/e4s-23.08/default/spack/opt/spack/linux-sles15-zen3/gcc-11.2.0/ccache-4.8.2-cvooxdw5wgvv2g3vjxjkrpv6dopginv6/bin:$PATH +export PATH=${SW_DIR}/ccache-4.10.2:$PATH # optional: for Python bindings or libEnsemble module load cray-python/3.11.5 -if [ -d "${CFS}/${proj}/${USER}/sw/perlmutter/cpu/venvs/warpx-cpu" ] +if [ -d "${SW_DIR}/venvs/warpx-cpu" ] then - source ${CFS}/${proj}/${USER}/sw/perlmutter/cpu/venvs/warpx-cpu/bin/activate + source ${SW_DIR}/venvs/warpx-cpu/bin/activate fi # an alias to request an interactive batch node for one hour diff --git a/Tools/machines/perlmutter-nersc/perlmutter_gpu.sbatch b/Tools/machines/perlmutter-nersc/perlmutter_gpu.sbatch index 37bd5d60c54..bd47fa3bd2a 100644 --- a/Tools/machines/perlmutter-nersc/perlmutter_gpu.sbatch +++ b/Tools/machines/perlmutter-nersc/perlmutter_gpu.sbatch @@ -17,7 +17,7 @@ # A100 80GB (256 nodes) #S BATCH -C gpu&hbm80g #SBATCH --exclusive -#SBATCH --cpus-per-task=16 +#SBATCH --cpus-per-task=32 # ideally single:1, but NERSC cgroups issue #SBATCH --gpu-bind=none #SBATCH --ntasks-per-node=4 @@ -34,7 +34,7 @@ export MPICH_OFI_NIC_POLICY=GPU # threads for OpenMP and threaded compressors per MPI rank # note: 16 avoids hyperthreading (32 virtual cores, 16 physical) -export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK} +export OMP_NUM_THREADS=16 # GPU-aware MPI optimizations GPU_AWARE_MPI="amrex.use_gpu_aware_mpi=1" diff --git a/Tools/machines/perlmutter-nersc/perlmutter_gpu_warpx.profile.example b/Tools/machines/perlmutter-nersc/perlmutter_gpu_warpx.profile.example index da1d55964d1..5119c44d327 100644 --- a/Tools/machines/perlmutter-nersc/perlmutter_gpu_warpx.profile.example +++ b/Tools/machines/perlmutter-nersc/perlmutter_gpu_warpx.profile.example @@ -12,36 +12,38 @@ module load craype module load craype-x86-milan module load craype-accel-nvidia80 module load cudatoolkit -module load cmake/3.24.3 +module load cmake/3.30.2 + +# missing modules installed here +export SW_DIR=${PSCRATCH}/storage/sw/warpx/perlmutter/gpu # optional: for QED support with detailed tables -export BOOST_ROOT=/global/common/software/spackecp/perlmutter/e4s-23.05/default/spack/opt/spack/linux-sles15-zen3/gcc-11.2.0/boost-1.82.0-ow5r5qrgslcwu33grygouajmuluzuzv3 +export CMAKE_PREFIX_PATH=${SW_DIR}/boost-1.82.0:${CMAKE_PREFIX_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/boost-1.82.0/lib:${LD_LIBRARY_PATH} # optional: for openPMD and PSATD+RZ support module load cray-hdf5-parallel/1.12.2.9 -export CMAKE_PREFIX_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/adios2-2.8.3:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/blaspp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/heffte-2.4.0:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.1:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:${CMAKE_PREFIX_PATH} +export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:${CMAKE_PREFIX_PATH} -export LD_LIBRARY_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/adios2-2.8.3/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/heffte-2.4.0/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.1/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:${LD_LIBRARY_PATH} -export PATH=${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/adios2-2.8.3/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # optional: CCache -export PATH=/global/common/software/spackecp/perlmutter/e4s-23.08/default/spack/opt/spack/linux-sles15-zen3/gcc-11.2.0/ccache-4.8.2-cvooxdw5wgvv2g3vjxjkrpv6dopginv6/bin:$PATH +export PATH=${SW_DIR}/ccache-4.10.2:$PATH # optional: for Python bindings or libEnsemble module load cray-python/3.11.5 -if [ -d "${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/venvs/warpx-gpu" ] +if [ -d "${SW_DIR}/venvs/warpx-gpu" ] then - source ${CFS}/${proj%_g}/${USER}/sw/perlmutter/gpu/venvs/warpx-gpu/bin/activate + source ${SW_DIR}/venvs/warpx-gpu/bin/activate fi # an alias to request an interactive batch node for one hour diff --git a/Tools/machines/pitzer-osc/install_cpu_dependencies.sh b/Tools/machines/pitzer-osc/install_cpu_dependencies.sh index f0b6ce4b950..cc74adb1a52 100644 --- a/Tools/machines/pitzer-osc/install_cpu_dependencies.sh +++ b/Tools/machines/pitzer-osc/install_cpu_dependencies.sh @@ -107,10 +107,10 @@ rm -rf ${build_dir}/c-blosc-pitzer-build if [ -d ${SRC_DIR}/adios2 ]; then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.10.1 + git checkout v2.10.2 cd - else - git clone -b v2.10.1 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi rm -rf ${build_dir}/adios2-pitzer-build cmake -S ${SRC_DIR}/adios2 \ @@ -122,7 +122,7 @@ cmake -S ${SRC_DIR}/adios2 \ -DADIOS2_USE_Python=OFF \ -DADIOS2_USE_SST=OFF \ -DADIOS2_USE_ZeroMQ=OFF \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.1 + -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build ${build_dir}/adios2-pitzer-build --target install -j 16 rm -rf ${build_dir}/adios2-pitzer-build diff --git a/Tools/machines/pitzer-osc/install_v100_dependencies.sh b/Tools/machines/pitzer-osc/install_v100_dependencies.sh index 5601b4d76c9..eae1a01e39e 100644 --- a/Tools/machines/pitzer-osc/install_v100_dependencies.sh +++ b/Tools/machines/pitzer-osc/install_v100_dependencies.sh @@ -107,10 +107,10 @@ rm -rf ${build_dir}/c-blosc-pitzer-build if [ -d ${SRC_DIR}/adios2 ]; then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.10.1 + git checkout v2.10.2 cd - else - git clone -b v2.10.1 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi rm -rf ${build_dir}/adios2-pitzer-build cmake -S ${SRC_DIR}/adios2 \ @@ -122,7 +122,7 @@ cmake -S ${SRC_DIR}/adios2 \ -DADIOS2_USE_Python=OFF \ -DADIOS2_USE_SST=OFF \ -DADIOS2_USE_ZeroMQ=OFF \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.1 + -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build ${build_dir}/adios2-pitzer-build --target install -j 16 rm -rf ${build_dir}/adios2-pitzer-build diff --git a/Tools/machines/pitzer-osc/pitzer_cpu_warpx.profile.example b/Tools/machines/pitzer-osc/pitzer_cpu_warpx.profile.example index d99c16b6cb6..233bbde63d6 100644 --- a/Tools/machines/pitzer-osc/pitzer_cpu_warpx.profile.example +++ b/Tools/machines/pitzer-osc/pitzer_cpu_warpx.profile.example @@ -43,10 +43,10 @@ export LD_LIBRARY_PATH=${SW_DIR}/boost-1.82.0/lib:$LD_LIBRARY_PATH # optional: for openPMD support (hdf5 and adios2) module load hdf5/1.12.2 export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.6:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.1:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.6/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.1/lib64:$LD_LIBRARY_PATH -export PATH=${SW_DIR}/adios2-2.10.1/bin:${PATH} +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # compiler environment hints export CC=$(which gcc) diff --git a/Tools/machines/pitzer-osc/pitzer_v100_warpx.profile.example b/Tools/machines/pitzer-osc/pitzer_v100_warpx.profile.example index 061794f5f68..06c117160bf 100644 --- a/Tools/machines/pitzer-osc/pitzer_v100_warpx.profile.example +++ b/Tools/machines/pitzer-osc/pitzer_v100_warpx.profile.example @@ -47,10 +47,10 @@ export LD_LIBRARY_PATH=${SW_DIR}/boost-1.82.0/lib:$LD_LIBRARY_PATH module load hdf5/1.12.0 export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-1.21.6:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.1:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-1.21.6/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.1/lib64:$LD_LIBRARY_PATH -export PATH=${SW_DIR}/adios2-2.10.1/bin:${PATH} +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # avoid relocation truncation error which result from large executable size export CUDAFLAGS="--host-linker-script=use-lcs" # https://github.com/ECP-WarpX/WarpX/pull/3673 diff --git a/Tools/machines/polaris-alcf/install_gpu_dependencies.sh b/Tools/machines/polaris-alcf/install_gpu_dependencies.sh index 18f94e6fd3b..48744741a21 100755 --- a/Tools/machines/polaris-alcf/install_gpu_dependencies.sh +++ b/Tools/machines/polaris-alcf/install_gpu_dependencies.sh @@ -50,13 +50,13 @@ if [ -d $HOME/src/adios2 ] then cd $HOME/src/adios2 git fetch --prune - git checkout v2.8.3 + git checkout v2.10.2 cd - else - git clone -b v2.8.3 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git $HOME/src/adios2 fi rm -rf $HOME/src/adios2-pm-gpu-build -cmake -S $HOME/src/adios2 -B $HOME/src/adios2-pm-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.8.3 +cmake -S $HOME/src/adios2 -B $HOME/src/adios2-pm-gpu-build -DADIOS2_USE_Blosc=ON -DADIOS2_USE_Fortran=OFF -DADIOS2_USE_Python=OFF -DADIOS2_USE_ZeroMQ=OFF -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake --build $HOME/src/adios2-pm-gpu-build --target install -j 16 rm -rf $HOME/src/adios2-pm-gpu-build diff --git a/Tools/machines/polaris-alcf/polaris_gpu_warpx.profile.example b/Tools/machines/polaris-alcf/polaris_gpu_warpx.profile.example index e1bd4e0fdd3..5cdda701bc7 100644 --- a/Tools/machines/polaris-alcf/polaris_gpu_warpx.profile.example +++ b/Tools/machines/polaris-alcf/polaris_gpu_warpx.profile.example @@ -22,16 +22,16 @@ module load boost # optional: for openPMD and PSATD+RZ support module load hdf5/1.14.3 export CMAKE_PREFIX_PATH=/home/${USER}/sw/polaris/gpu/c-blosc-1.21.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=/home/${USER}/sw/polaris/gpu/adios2-2.8.3:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=/home/${USER}/sw/polaris/gpu/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=/home/${USER}/sw/polaris/gpu/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=/home/${USER}/sw/polaris/gpu/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=/home/${USER}/sw/polaris/gpu/c-blosc-1.21.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=/home/${USER}/sw/polaris/gpu/adios2-2.8.3/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=/home/${USER}/sw/polaris/gpu/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=/home/${USER}/sw/polaris/gpu/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=/home/${USER}/sw/polaris/gpu/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export PATH=/home/${USER}/sw/polaris/gpu/adios2-2.8.3/bin:${PATH} +export PATH=/home/${USER}/sw/polaris/gpu/adios2-2.10.2/bin:${PATH} # optional: for Python bindings or libEnsemble module load python/3.10.9 diff --git a/Tools/machines/tioga-llnl/install_mi300a_dependencies.sh b/Tools/machines/tioga-llnl/install_mi300a_dependencies.sh index 7e002838e4a..d3ade42fca9 100644 --- a/Tools/machines/tioga-llnl/install_mi300a_dependencies.sh +++ b/Tools/machines/tioga-llnl/install_mi300a_dependencies.sh @@ -73,10 +73,10 @@ if [ -d ${SRC_DIR}/adios2 ] then cd ${SRC_DIR}/adios2 git fetch --prune - git checkout v2.10.1 + git checkout v2.10.2 cd - else - git clone -b v2.10.1 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 + git clone -b v2.10.2 https://github.com/ornladios/ADIOS2.git ${SRC_DIR}/adios2 fi cmake \ --fresh \ @@ -87,7 +87,7 @@ cmake \ -DADIOS2_USE_Fortran=OFF \ -DADIOS2_USE_Python=OFF \ -DADIOS2_USE_ZeroMQ=OFF \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.1 + -DCMAKE_INSTALL_PREFIX=${SW_DIR}/adios2-2.10.2 cmake \ --build ${build_dir}/adios2-build \ --target install \ @@ -143,48 +143,6 @@ cmake \ --parallel ${build_procs} rm -rf ${build_dir}/lapackpp-tioga-mi300a-build -# heFFTe -if [ -d ${SRC_DIR}/heffte ] -then - cd ${SRC_DIR}/heffte - git fetch --prune - git checkout v2.4.0 - cd - -else - git clone -b v2.4.0 https://github.com/icl-utk-edu/heffte.git ${SRC_DIR}/heffte -fi -cmake \ - --fresh \ - -S ${SRC_DIR}/heffte \ - -B ${build_dir}/heffte-build \ - -DBUILD_SHARED_LIBS=ON \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_CXX_STANDARD=17 \ - -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON \ - -DCMAKE_INSTALL_PREFIX=${SW_DIR}/heffte-2.4.0 \ - -DHeffte_DISABLE_GPU_AWARE_MPI=OFF \ - -DHeffte_ENABLE_AVX=OFF \ - -DHeffte_ENABLE_AVX512=OFF \ - -DHeffte_ENABLE_FFTW=OFF \ - -DHeffte_ENABLE_CUDA=OFF \ - -DHeffte_ENABLE_ROCM=ON \ - -DHeffte_ENABLE_ONEAPI=OFF \ - -DHeffte_ENABLE_MKL=OFF \ - -DHeffte_ENABLE_DOXYGEN=OFF \ - -DHeffte_SEQUENTIAL_TESTING=OFF \ - -DHeffte_ENABLE_TESTING=OFF \ - -DHeffte_ENABLE_TRACING=OFF \ - -DHeffte_ENABLE_PYTHON=OFF \ - -DHeffte_ENABLE_FORTRAN=OFF \ - -DHeffte_ENABLE_SWIG=OFF \ - -DHeffte_ENABLE_MAGMA=OFF -cmake \ - --build ${build_dir}/heffte-build \ - --target install \ - --parallel ${build_procs} -rm -rf ${build_dir}/heffte-build - - # Python ###################################################################### # # sometimes, the Lassen PIP Index is down diff --git a/Tools/machines/tioga-llnl/tioga_mi300a_warpx.profile.example b/Tools/machines/tioga-llnl/tioga_mi300a_warpx.profile.example index e3da37c5522..db6aa2e5b8c 100644 --- a/Tools/machines/tioga-llnl/tioga_mi300a_warpx.profile.example +++ b/Tools/machines/tioga-llnl/tioga_mi300a_warpx.profile.example @@ -28,18 +28,16 @@ module load ninja/1.10.2 SW_DIR="/p/lustre1/${USER}/tioga/warpx/mi300a" module load cray-hdf5-parallel/1.12.2.11 export CMAKE_PREFIX_PATH=${SW_DIR}/c-blosc-2.15.1:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.1:$CMAKE_PREFIX_PATH +export CMAKE_PREFIX_PATH=${SW_DIR}/adios2-2.10.2:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/blaspp-2024.05.31:$CMAKE_PREFIX_PATH export CMAKE_PREFIX_PATH=${SW_DIR}/lapackpp-2024.05.31:$CMAKE_PREFIX_PATH -export CMAKE_PREFIX_PATH=${SW_DIR}/heffte-2.4.0:$CMAKE_PREFIX_PATH export LD_LIBRARY_PATH=${SW_DIR}/c-blosc-2.15.1/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.1/lib64:$LD_LIBRARY_PATH +export LD_LIBRARY_PATH=${SW_DIR}/adios2-2.10.2/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/blaspp-2024.05.31/lib64:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=${SW_DIR}/lapackpp-2024.05.31/lib64:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH=${SW_DIR}/heffte-2.4.0/lib64:$LD_LIBRARY_PATH -export PATH=${SW_DIR}/adios2-2.10.1/bin:${PATH} +export PATH=${SW_DIR}/adios2-2.10.2/bin:${PATH} # python module load cray-python/3.11.7 diff --git a/cmake/WarpXFunctions.cmake b/cmake/WarpXFunctions.cmake index 43efd89efc5..543d0cd0ce4 100644 --- a/cmake/WarpXFunctions.cmake +++ b/cmake/WarpXFunctions.cmake @@ -313,10 +313,6 @@ function(set_warpx_binary_name D) set_property(TARGET ${tgt} APPEND_STRING PROPERTY OUTPUT_NAME ".FFT") endif() - if(WarpX_HEFFTE) - set_property(TARGET ${tgt} APPEND_STRING PROPERTY OUTPUT_NAME ".HEFFTE") - endif() - if(WarpX_EB) set_property(TARGET ${tgt} APPEND_STRING PROPERTY OUTPUT_NAME ".EB") endif() @@ -462,7 +458,6 @@ function(warpx_print_summary) message(" PARTICLE PRECISION: ${WarpX_PARTICLE_PRECISION}") message(" PRECISION: ${WarpX_PRECISION}") message(" FFT Solvers: ${WarpX_FFT}") - message(" heFFTe: ${WarpX_HEFFTE}") message(" PYTHON: ${WarpX_PYTHON}") if(WarpX_PYTHON) message(" PYTHON IPO: ${WarpX_PYTHON_IPO}") diff --git a/cmake/dependencies/AMReX.cmake b/cmake/dependencies/AMReX.cmake index 9854cbb0800..3c389a0a01b 100644 --- a/cmake/dependencies/AMReX.cmake +++ b/cmake/dependencies/AMReX.cmake @@ -51,6 +51,12 @@ macro(find_amrex) set(AMReX_OMP OFF CACHE INTERNAL "") endif() + if(WarpX_FFT OR ABLASTR_FFT) + set(AMReX_FFT ON CACHE INTERNAL "") + else() + set(AMReX_FFT OFF CACHE INTERNAL "") + endif() + if(WarpX_EB) set(AMReX_EB ON CACHE INTERNAL "") else() @@ -93,7 +99,7 @@ macro(find_amrex) set(AMReX_PROBINIT OFF CACHE INTERNAL "") set(AMReX_TINY_PROFILE ON CACHE BOOL "") set(AMReX_LINEAR_SOLVERS_EM ON CACHE INTERNAL "") - set(AMReX_LINEAR_SOLVERS_INCFLO OFF CACHE INTERNAL "") + set(AMReX_LINEAR_SOLVERS_INCFLO ON CACHE INTERNAL "") if(WarpX_ASCENT OR WarpX_SENSEI) set(AMReX_GPU_RDC ON CACHE BOOL "") @@ -243,6 +249,11 @@ macro(find_amrex) foreach(D IN LISTS WarpX_amrex_dim) set(COMPONENT_DIMS ${COMPONENT_DIMS} ${D}D) endforeach() + if(WarpX_FFT) + set(COMPONENT_FFT FFT) + else() + set(COMPONENT_FFT) + endif() if(WarpX_EB) set(COMPONENT_EB EB) else() @@ -260,7 +271,7 @@ macro(find_amrex) endif() set(COMPONENT_PRECISION ${WarpX_PRECISION} P${WarpX_PARTICLE_PRECISION}) - find_package(AMReX 24.10 CONFIG REQUIRED COMPONENTS ${COMPONENT_ASCENT} ${COMPONENT_CATALYST} ${COMPONENT_DIMS} ${COMPONENT_EB} PARTICLES ${COMPONENT_PIC} ${COMPONENT_PRECISION} ${COMPONENT_SENSEI} LSOLVERS) + find_package(AMReX 25.02 CONFIG REQUIRED COMPONENTS ${COMPONENT_ASCENT} ${COMPONENT_CATALYST} ${COMPONENT_DIMS} ${COMPONENT_EB} ${COMPONENT_FFT} PARTICLES ${COMPONENT_PIC} ${COMPONENT_PRECISION} ${COMPONENT_SENSEI} LSOLVERS) # note: TINYP skipped because user-configured and optional # AMReX CMake helper scripts @@ -283,7 +294,7 @@ set(WarpX_amrex_src "" set(WarpX_amrex_repo "https://github.com/AMReX-Codes/amrex.git" CACHE STRING "Repository URI to pull and build AMReX from if(WarpX_amrex_internal)") -set(WarpX_amrex_branch "92679babfc2cc66ca06ee591a80001db57c89878" +set(WarpX_amrex_branch "044d52f7d309e340939d7cae449fd83209da317f" CACHE STRING "Repository branch for WarpX_amrex_repo if(WarpX_amrex_internal)") diff --git a/cmake/dependencies/PICSAR.cmake b/cmake/dependencies/PICSAR.cmake index 9eb9162238a..d5249b61641 100644 --- a/cmake/dependencies/PICSAR.cmake +++ b/cmake/dependencies/PICSAR.cmake @@ -88,7 +88,7 @@ function(find_picsar) #message(STATUS "PICSAR: Using version '${PICSAR_VERSION}'") else() # not supported by PICSAR (yet) - #find_package(PICSAR 24.09 CONFIG REQUIRED QED) + #find_package(PICSAR 25.01 CONFIG REQUIRED QED) #message(STATUS "PICSAR: Found version '${PICSAR_VERSION}'") message(FATAL_ERROR "PICSAR: Cannot be used as externally installed " "library yet. " @@ -109,7 +109,7 @@ if(WarpX_QED) set(WarpX_picsar_repo "https://github.com/ECP-WarpX/picsar.git" CACHE STRING "Repository URI to pull and build PICSAR from if(WarpX_picsar_internal)") - set(WarpX_picsar_branch "24.09" + set(WarpX_picsar_branch "25.01" CACHE STRING "Repository branch for WarpX_picsar_repo if(WarpX_picsar_internal)") diff --git a/cmake/dependencies/openPMD.cmake b/cmake/dependencies/openPMD.cmake index ce6ec4d0967..a5a80f25790 100644 --- a/cmake/dependencies/openPMD.cmake +++ b/cmake/dependencies/openPMD.cmake @@ -13,7 +13,7 @@ function(find_openpmd) if(WarpX_openpmd_internal OR WarpX_openpmd_src) set(CMAKE_POLICY_DEFAULT_CMP0077 NEW) - # see https://openpmd-api.readthedocs.io/en/0.15.2/dev/buildoptions.html + # see https://openpmd-api.readthedocs.io/en/0.16.1/dev/buildoptions.html set(openPMD_USE_ADIOS1 OFF CACHE INTERNAL "") set(openPMD_USE_MPI ${WarpX_MPI} CACHE INTERNAL "") set(openPMD_USE_PYTHON OFF CACHE INTERNAL "") @@ -71,7 +71,7 @@ function(find_openpmd) else() set(COMPONENT_WMPI NOMPI) endif() - find_package(openPMD 0.15.1 CONFIG REQUIRED COMPONENTS ${COMPONENT_WMPI}) + find_package(openPMD 0.16.1 CONFIG REQUIRED COMPONENTS ${COMPONENT_WMPI}) message(STATUS "openPMD-api: Found version '${openPMD_VERSION}'") endif() endfunction() @@ -87,7 +87,7 @@ if(WarpX_OPENPMD) set(WarpX_openpmd_repo "https://github.com/openPMD/openPMD-api.git" CACHE STRING "Repository URI to pull and build openPMD-api from if(WarpX_openpmd_internal)") - set(WarpX_openpmd_branch "0.15.2" + set(WarpX_openpmd_branch "0.16.1" CACHE STRING "Repository branch for WarpX_openpmd_repo if(WarpX_openpmd_internal)") diff --git a/cmake/dependencies/pyAMReX.cmake b/cmake/dependencies/pyAMReX.cmake index 3236851d392..be7c64acd69 100644 --- a/cmake/dependencies/pyAMReX.cmake +++ b/cmake/dependencies/pyAMReX.cmake @@ -59,7 +59,7 @@ function(find_pyamrex) endif() elseif(NOT WarpX_pyamrex_internal) # TODO: MPI control - find_package(pyAMReX 24.10 CONFIG REQUIRED) + find_package(pyAMReX 25.02 CONFIG REQUIRED) message(STATUS "pyAMReX: Found version '${pyAMReX_VERSION}'") endif() endfunction() @@ -74,7 +74,7 @@ option(WarpX_pyamrex_internal "Download & build pyAMReX" ON) set(WarpX_pyamrex_repo "https://github.com/AMReX-Codes/pyamrex.git" CACHE STRING "Repository URI to pull and build pyamrex from if(WarpX_pyamrex_internal)") -set(WarpX_pyamrex_branch "1aa1db34a0d1bdc084bd6069a4fd97b26266af5c" +set(WarpX_pyamrex_branch "3088ea12a1a6287246bf027c4235f10e92472450" CACHE STRING "Repository branch for WarpX_pyamrex_repo if(WarpX_pyamrex_internal)") diff --git a/cmake/dependencies/pybind11.cmake b/cmake/dependencies/pybind11.cmake index 50b00013f7a..e90b56b2d38 100644 --- a/cmake/dependencies/pybind11.cmake +++ b/cmake/dependencies/pybind11.cmake @@ -37,7 +37,7 @@ function(find_pybind11) mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_FETCHEDpybind11) endif() else() - find_package(pybind11 2.12.0 CONFIG REQUIRED) + find_package(pybind11 2.13.0 CONFIG REQUIRED) message(STATUS "pybind11: Found version '${pybind11_VERSION}'") endif() endfunction() @@ -52,7 +52,7 @@ option(WarpX_pybind11_internal "Download & build pybind11" ON) set(WarpX_pybind11_repo "https://github.com/pybind/pybind11.git" CACHE STRING "Repository URI to pull and build pybind11 from if(WarpX_pybind11_internal)") -set(WarpX_pybind11_branch "v2.12.0" +set(WarpX_pybind11_branch "v2.13.6" CACHE STRING "Repository branch for WarpX_pybind11_repo if(WarpX_pybind11_internal)") diff --git a/requirements.txt b/requirements.txt index 2c8b749abe0..e44273328de 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,7 +4,7 @@ periodictable~=1.5 # PICMI # note: don't forget to update the version in Docs/requirements.txt, too -picmistandard==0.31.0 +picmistandard==0.33.0 # for development against an unreleased PICMI version, use: #picmistandard @ git+https://github.com/picmi-standard/picmi.git#subdirectory=PICMI_Python diff --git a/setup.py b/setup.py index f2bc72ff386..fae11aa0654 100644 --- a/setup.py +++ b/setup.py @@ -105,7 +105,6 @@ def build_extension(self, ext): "-DWarpX_PRECISION=" + WARPX_PRECISION, "-DWarpX_PARTICLE_PRECISION=" + WARPX_PARTICLE_PRECISION, "-DWarpX_FFT:BOOL=" + WARPX_FFT, - "-DWarpX_HEFFTE:BOOL=" + WARPX_HEFFTE, "-DWarpX_PYTHON:BOOL=ON", "-DWarpX_PYTHON_IPO:BOOL=" + WARPX_PYTHON_IPO, "-DWarpX_QED:BOOL=" + WARPX_QED, @@ -208,7 +207,6 @@ def build_extension(self, ext): WARPX_PRECISION = env.pop("WARPX_PRECISION", "DOUBLE") WARPX_PARTICLE_PRECISION = env.pop("WARPX_PARTICLE_PRECISION", WARPX_PRECISION) WARPX_FFT = env.pop("WARPX_FFT", "OFF") -WARPX_HEFFTE = env.pop("WARPX_HEFFTE", "OFF") WARPX_QED = env.pop("WARPX_QED", "ON") WARPX_QED_TABLE_GEN = env.pop("WARPX_QED_TABLE_GEN", "OFF") WARPX_DIMS = env.pop("WARPX_DIMS", "1;2;RZ;3") @@ -282,7 +280,7 @@ def build_extension(self, ext): setup( name="pywarpx", # note PEP-440 syntax: x.y.zaN but x.y.z.devN - version="24.10", + version="25.02", packages=["pywarpx"], package_dir={"pywarpx": "Python/pywarpx"}, author="Jean-Luc Vay, David P. Grote, Maxence Thévenet, Rémi Lehe, Andrew Myers, Weiqun Zhang, Axel Huebl, et al.", @@ -309,7 +307,7 @@ def build_extension(self, ext): cmdclass=cmdclass, # scripts=['warpx_1d', 'warpx_2d', 'warpx_rz', 'warpx_3d'], zip_safe=False, - python_requires=">=3.8", + python_requires=">=3.8", # left for CI, truly ">=3.9" # tests_require=['pytest'], install_requires=install_requires, # see: src/bindings/python/cli @@ -320,7 +318,7 @@ def build_extension(self, ext): # }, extras_require={ "all": [ - "openPMD-api~=0.15.1", + "openPMD-api>=0.16.1", "openPMD-viewer~=1.1", "yt>=4.1.0", "matplotlib", @@ -338,12 +336,13 @@ def build_extension(self, ext): "Topic :: Scientific/Engineering :: Physics", "Programming Language :: C++", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", ( - "License :: OSI Approved :: " "BSD License" + "License :: OSI Approved :: BSD License" ), # TODO: use real SPDX: BSD-3-Clause-LBNL ], # new PEP 639 format