diff --git a/.coveragerc b/.coveragerc
index 0fa6bd98c4..922ba7b57a 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -9,5 +9,3 @@ omit =
*/proteus/WaveTools.py
*/proteus/BoundaryConditions.py
*/proteus/SpatialTools.py
- */proteus/mprans/BoundaryConditions.py
- */proteus/mprans/SpatialTools.py
diff --git a/.github/coverage/cython_traced.py b/.github/coverage/cython_traced.py
index 9ab5221e36..4bd63eca6b 100644
--- a/.github/coverage/cython_traced.py
+++ b/.github/coverage/cython_traced.py
@@ -21,7 +21,7 @@
from Cython.Coverage import Plugin as _CythonPlugin
# relative to the package directory, '/'-separated
-TRACED_MODULES = ('BoundaryConditions.py', 'mprans/BoundaryConditions.py', 'WaveTools.py')
+TRACED_MODULES = ('BoundaryConditions.py', 'WaveTools.py')
class Plugin(_CythonPlugin):
diff --git a/.github/coverage/floors.json b/.github/coverage/floors.json
index c2c254c9ca..65f2ef4a3c 100644
--- a/.github/coverage/floors.json
+++ b/.github/coverage/floors.json
@@ -1,12 +1,11 @@
{
- "proteus/ADR.py": 90.6,
"proteus/ADRProblem.py": 93.1,
"proteus/AnalysisTools.py": 0.0,
"proteus/AnalyticalSolutions.py": 89.3,
"proteus/ArchiveFields.py": 98.3,
"proteus/Archiver.py": 70.5,
"proteus/AuxiliaryVariables.py": 16.5,
- "proteus/BoundaryConditions.py": 96.6,
+ "proteus/BoundaryConditions.py": 70.7,
"proteus/Comm.py": 97.0,
"proteus/Context.py": 92.5,
"proteus/DiagUtils.py": 11.4,
@@ -22,10 +21,11 @@
"proteus/LatexReport.py": 7.3,
"proteus/LinearAlgebraTools.py": 85.3,
"proteus/LinearSolvers.py": 76.9,
- "proteus/MeshAdaptPUMI/AdaptHelper.py": 83.8,
+ "proteus/MeshAdaptPUMI/AdaptHelper.py": 83.1,
"proteus/MeshAdaptPUMI/Checkpoint.py": 14.1,
"proteus/MeshAdaptPUMI/__init__.py": 100.0,
"proteus/MeshTools.py": 65.9,
+ "proteus/MoveMeshMonitor.py": 65.9,
"proteus/NonlinearSolvers.py": 46.4,
"proteus/Norms.py": 18.5,
"proteus/NumericalFlux.py": 55.3,
@@ -40,7 +40,7 @@
"proteus/SWFlow/utils/SWEs_so.py": 0.0,
"proteus/ShockCapturing.py": 36.1,
"proteus/SimTools.py": 11.9,
- "proteus/SpatialTools.py": 62.9,
+ "proteus/SpatialTools.py": 56.0,
"proteus/SplitOperator.py": 46.1,
"proteus/StepControl.py": 36.0,
"proteus/SubgridError.py": 19.6,
@@ -100,47 +100,41 @@
"proteus/default_so.py": 91.3,
"proteus/defaults.py": 88.8,
"proteus/deim_utils.py": 60.4,
- "proteus/elastoplastic/ElastoPlastic.py": 82.0,
- "proteus/elastoplastic/__init__.py": 100.0,
"proteus/iproteus.py": 76.9,
- "proteus/m_comp_co2/__init__.py": "test pending (deck from Arnob; not legacy, #1282)",
- "proteus/m_comp_co2/m_comp_co2.py": "test pending (deck from Arnob; not legacy, #1282)",
- "proteus/mprans/AddedMass.py": 76.2,
- "proteus/mprans/ArchiveBeams.py": 7.8,
- "proteus/mprans/BodyDynamics.py": 52.2,
- "proteus/mprans/BoundaryConditions.py": 70.1,
- "proteus/mprans/CLSVOF.py": 79.5,
- "proteus/mprans/Dissipation.py": 56.5,
- "proteus/mprans/EntropyViscosity.py": 100.0,
- "proteus/mprans/GN_SW2DCV.py": 77.3,
- "proteus/mprans/Kappa.py": 56.2,
- "proteus/mprans/MCorr.py": 64.5,
- "proteus/mprans/MCorr3P.py": 50.4,
- "proteus/mprans/MoveMesh.py": 86.4,
- "proteus/mprans/MoveMeshMonitor.py": 65.9,
- "proteus/mprans/NCLS.py": 75.4,
- "proteus/mprans/NCLS3P.py": 75.6,
- "proteus/mprans/Pres.py": 76.1,
- "proteus/mprans/PresInc.py": 76.2,
- "proteus/mprans/PresInit.py": 23.2,
- "proteus/mprans/PressureNormalization.py": 97.5,
- "proteus/mprans/RANS2P.py": 87.1,
- "proteus/mprans/RANS2P_IB.py": 2.4,
- "proteus/mprans/RANS3PF.py": 88.0,
- "proteus/mprans/RANS3PSed.py": 4.7,
- "proteus/mprans/RDLS.py": 67.0,
- "proteus/mprans/SW2D.py": 6.1,
- "proteus/mprans/SW2DCV.py": 85.8,
- "proteus/mprans/SpatialTools.py": 52.1,
- "proteus/mprans/TADR.py": 88.4,
- "proteus/mprans/VOF.py": 87.4,
- "proteus/mprans/VOF3P.py": 83.5,
- "proteus/mprans/VOS3P.py": 82.4,
- "proteus/mprans/__init__.py": 100.0,
- "proteus/mprans/beamFEM.py": 9.2,
+ "proteus/kernels/ADR.py": 90.6,
+ "proteus/kernels/AddedMass.py": 76.2,
+ "proteus/kernels/ArchiveBeams.py": 7.8,
+ "proteus/kernels/CLSVOF.py": 79.5,
+ "proteus/kernels/Dissipation.py": 56.5,
+ "proteus/kernels/ElastoPlastic.py": 82.0,
+ "proteus/kernels/EntropyViscosity.py": 100.0,
+ "proteus/kernels/GN_SW2DCV.py": 77.3,
+ "proteus/kernels/Kappa.py": 56.2,
+ "proteus/kernels/MCorr.py": 64.5,
+ "proteus/kernels/MCorr3P.py": 50.4,
+ "proteus/kernels/MoveMesh.py": 86.4,
+ "proteus/kernels/NCLS.py": 75.4,
+ "proteus/kernels/NCLS3P.py": 75.6,
+ "proteus/kernels/Pres.py": 76.1,
+ "proteus/kernels/PresInc.py": 76.2,
+ "proteus/kernels/PresInit.py": 23.2,
+ "proteus/kernels/PressureNormalization.py": 97.5,
+ "proteus/kernels/RANS2P.py": 87.1,
+ "proteus/kernels/RANS2P_IB.py": 2.4,
+ "proteus/kernels/RANS3PF.py": 88.0,
+ "proteus/kernels/RANS3PSed.py": 4.7,
+ "proteus/kernels/RDLS.py": 67.0,
+ "proteus/kernels/Richards.py": 78.9,
+ "proteus/kernels/SW2D.py": 6.1,
+ "proteus/kernels/SW2DCV.py": 85.8,
+ "proteus/kernels/TADR.py": 88.4,
+ "proteus/kernels/VOF.py": 87.4,
+ "proteus/kernels/VOF3P.py": 83.5,
+ "proteus/kernels/VOS3P.py": 82.4,
+ "proteus/kernels/__init__.py": 100.0,
+ "proteus/kernels/beamFEM.py": 9.2,
+ "proteus/kernels/m_comp_co2.py": "test pending (deck from Arnob; not legacy, #1282)",
+ "proteus/mbd/BodyDynamics.py": 52.2,
"proteus/petsc_optional.py": 91.6,
- "proteus/richards/ADR.py": 0.0,
- "proteus/richards/Richards.py": 78.9,
- "proteus/richards/__init__.py": 100.0,
"proteus/runtime.py": 100.0
}
diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 5dc5502829..d782776a2a 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -230,7 +230,7 @@ jobs:
# installs it with default build isolation, through pip run from this env, which finds the bundle.
python -m build --sdist --no-isolation
- # The coverage leg builds BoundaryConditions, mprans.BoundaryConditions and WaveTools (compiled by Cython from
+ # The coverage leg builds BoundaryConditions and WaveTools (compiled by Cython from
# .py files, so coverage.py saw their lines never run: 0%) with line tracing; setup.py reads this variable.
# Every other leg builds as before: tracing slows those modules down and nothing else needs it.
- name: Install sdist with default build isolation
@@ -241,7 +241,7 @@ jobs:
# The Cython.Coverage plugin finds a traced module's executable lines in the C++ file Cython generated, which it
# looks for next to the installed .so. pip builds in a temporary directory and keeps no generated source, so make
- # the three files again here (the lines they map are the same ones) and put them there; the coverage job reads
+ # the two files again here (the lines they map are the same ones) and put them there; the coverage job reads
# the same files from the artifact below.
- name: Generate the Cython sources the coverage plugin reads (coverage leg)
if: matrix.leg.coverage == 'yes'
@@ -249,12 +249,12 @@ jobs:
run: |
PKG="$(cd "$(mktemp -d)" && python -c 'import os, proteus; print(os.path.dirname(proteus.__file__))')"
echo "installed package: $PKG; cython $(cython --version 2>&1)"
- for mod in BoundaryConditions mprans/BoundaryConditions WaveTools; do
+ for mod in BoundaryConditions WaveTools; do
cython --cplus -3 -X linetrace=True -I . "proteus/$mod.py" -o "proteus/$mod.cpp"
cp "proteus/$mod.cpp" "$PKG/$mod.cpp"
done
- ls "$PKG"/BoundaryConditions.* "$PKG"/mprans/BoundaryConditions.* "$PKG"/WaveTools.*
- tar czf linetrace-sources.tgz proteus/BoundaryConditions.cpp proteus/mprans/BoundaryConditions.cpp proteus/WaveTools.cpp
+ ls "$PKG"/BoundaryConditions.* "$PKG"/WaveTools.*
+ tar czf linetrace-sources.tgz proteus/BoundaryConditions.cpp proteus/WaveTools.cpp
- name: Smoke test
shell: bash -l {0}
@@ -580,7 +580,7 @@ jobs:
- name: Combine and check against the floors
shell: bash
run: |
- # Cython: the plugin that reads the line-traced modules' data (BoundaryConditions, mprans.BoundaryConditions,
+ # Cython: the plugin that reads the line-traced modules' data (BoundaryConditions,
# WaveTools) has to be there to combine and report them
pip install -q "coverage>=7.10" "cython>=3.0,<4"
# the plugin looks for each module's generated C++ next to its .py
diff --git a/.gitignore b/.gitignore
index 7a41eda028..b60bcf7668 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,21 +66,20 @@ proteus/fenton/Fenton.cpp
proteus/flcbdfWrappers.cpp
proteus/mbd/CouplingFSI.cpp
proteus/MeshAdaptPUMI/Adapter.cpp
-proteus/mprans/BoundaryConditions.cpp
-proteus/mprans/MeshSmoothing.cpp
-proteus/mprans/cAddedMass.cpp
-proteus/mprans/cCLSVOF.cpp
-proteus/mprans/cGN_SW2DCV.cpp
-proteus/mprans/cMCorr3P.cpp
-proteus/mprans/cMoveMeshMonitor.cpp
-proteus/mprans/cNCLS3P.cpp
-proteus/mprans/cPres.cpp
-proteus/mprans/cPresInc.cpp
-proteus/mprans/cPresInit.cpp
-proteus/mprans/cRANS3PF.cpp
-proteus/mprans/cRANS3PSed.cpp
-proteus/mprans/cVOF3P.cpp
-proteus/mprans/cVOS3P.cpp
+proteus/MeshSmoothing.cpp
+proteus/kernels/cAddedMass.cpp
+proteus/kernels/cCLSVOF.cpp
+proteus/kernels/cGN_SW2DCV.cpp
+proteus/kernels/cMCorr3P.cpp
+proteus/cMoveMeshMonitor.cpp
+proteus/kernels/cNCLS3P.cpp
+proteus/kernels/cPres.cpp
+proteus/kernels/cPresInc.cpp
+proteus/kernels/cPresInit.cpp
+proteus/kernels/cRANS3PF.cpp
+proteus/kernels/cRANS3PSed.cpp
+proteus/kernels/cVOF3P.cpp
+proteus/kernels/cVOS3P.cpp
proteus/superluWrappers.c
proteus/MeshAdaptPUMI/MeshAdapt.cpp
proteus/tests/ci/meshNoVessel.edge
diff --git a/CLAUDE.md b/CLAUDE.md
index 42bb31abc1..56578a4654 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -36,7 +36,7 @@ Verified on `main` at b9d98f5 (2026-11-17): 4 cores, 15 GB RAM, running as root.
file.
4. **Check it:**
```bash
- python -c "import proteus, proteus.superluWrappers, proteus.mprans.cRANS2P, proteus.MeshAdaptPUMI.MeshAdapt, proteus.mbd.CouplingFSI"
+ python -c "import proteus, proteus.superluWrappers, proteus.kernels.cRANS2P, proteus.MeshAdaptPUMI.MeshAdapt, proteus.mbd.CouplingFSI"
```
## Making the tests pass
diff --git a/Makefile b/Makefile
index 6efecd4719..b5b377158e 100644
--- a/Makefile
+++ b/Makefile
@@ -110,6 +110,7 @@ else
-rm -rf ${PROTEUS_PREFIX}
endif
-rm -rf build proteus/*.pyc proteus/*.so proteus/*.a proteus/MeshAdaptPUMI/*.so
+ -rm -rf build proteus/kernels/*.pyc proteus/kernels/*.so proteus/kernels/*.a
-rm -rf build proteus/mprans/*.pyc proteus/mprans/*.so proteus/mprans/*.a
-rm -rf build proteus/richards/*.pyc proteus/richards/*.so proteus/richards/*.a
-rm -rf build proteus/elastoplastic/*.pyc proteus/elastoplastic/*.so proteus/elastoplastic/*.a
diff --git a/README.md b/README.md
index f57a2dc4c3..d83b036104 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,10 @@
+
+
+
+
+
+
+
# Proteus: Computational Methods and Simulation Toolkit [](https://github.com/proteustoolkit/proteus/actions/workflows/sdist.yml) [](https://zenodo.org/badge/latestdoi/2212385)
diff --git a/docs/Doxyfile b/docs/Doxyfile
index 7b89d2a364..3053cd58b8 100644
--- a/docs/Doxyfile
+++ b/docs/Doxyfile
@@ -38,7 +38,7 @@ PROJECT_NAME = proteus
# could be handy for archiving the generated documentation or if some version
# control system is used.
-PROJECT_NUMBER = 2.0.0rc1
+PROJECT_NUMBER = 2.0.0rc2
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
@@ -51,7 +51,7 @@ PROJECT_BRIEF = "C/C++/Fortran libraries"
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
# the logo to the output directory.
-#PROJECT_LOGO = ./source/_static/corps_logo_cross_24.svg
+#PROJECT_LOGO = ./source/_static/logo/primary/png/proteus-favicon-64.png
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
diff --git a/docs/source/_static/logo/Montserrat-OFL.txt b/docs/source/_static/logo/Montserrat-OFL.txt
new file mode 100644
index 0000000000..a176d90de9
--- /dev/null
+++ b/docs/source/_static/logo/Montserrat-OFL.txt
@@ -0,0 +1,93 @@
+Copyright (c) 2011--2016, The Montserrat Project Authors (julieta.ulanovsky@gmail.com)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/docs/source/_static/logo/README.md b/docs/source/_static/logo/README.md
new file mode 100644
index 0000000000..6d9e56e7cb
--- /dev/null
+++ b/docs/source/_static/logo/README.md
@@ -0,0 +1,48 @@
+# Proteus logo
+
+Hand-written SVG (every file has a `viewBox`, no embedded rasters, no font references: the wordmark is outlined).
+The trident was designed by cekees's daughter; the rest is built around it.
+
+## primary/ (the logos to use)
+
+Grey trident with no container; organization-agnostic.
+
+- `proteus-mark.svg`: trident `#898b8e`; works on light and dark backgrounds (3.4:1 on white, 4-5:1 on dark).
+- `proteus-mark-light-background.svg`: trident `#5f6164`, for white backgrounds where more contrast is wanted (6.2:1).
+- `proteus-mark-auto.svg`: `#5f6164` in light mode and `#898b8e` in dark mode (`prefers-color-scheme`; works through `
`).
+- `proteus-lockup-{h,v}-{light-background,dark-background,auto}.svg`: trident + PROTEUS, horizontal and stacked
+ (stacked: the stem sits over the T). The suffix names the background the file is meant for.
+- `proteus-favicon.svg`, `proteus-favicon.ico` (16/32/48): square, trident alone, transparent; heavier than the mark (3-unit round stroke, `#767a7e`, fills the square) so it stays legible at 16 px in a browser tab.
+- `png/`: transparent PNG renders (mark 512/1024, lockups 1200 and 800 wide, favicon 16 to 512).
+
+## lsu/ (secondary: LSU-affiliated uses)
+
+Purple `#592c82` chamfered-corner badge with a gold `#ffc72a` edge and the grey trident: `proteus-badge.svg`,
+a square `proteus-favicon.svg`, lockups, `.ico`, `png/`.
+
+## Where each is used
+
+| Use | File |
+| --- | --- |
+| Sphinx sidebar (`html_logo`, `docs/source/conf.py`) | `primary/proteus-lockup-v-light-background.svg` |
+| Sphinx favicon (`html_favicon`) | `primary/proteus-favicon.ico` |
+| Top-level `README.md` | `primary/proteus-lockup-h-{light,dark}-background.svg` via `` |
+| Commented-out Doxygen and LaTeX logos | `primary/png/proteus-favicon-64.png`, `primary/png/proteus-lockup-v-light-background-800.png` |
+
+## Colours and sources
+
+- The grey, purple and gold follow the swatches in the LSU CCT logo files: LSU Logo Grey 50% / PANTONE Cool Gray 8 C,
+ LSU Purple CMYK Coated 82/98/0/12 / PANTONE 268 C, LSU Gold CMYK Coated 0/19/89/0 / PANTONE 123 C.
+ The sRGB values are LAB-to-sRGB conversions of those swatches, not values published by LSU; check them against the
+ official LSU brand assets before print or formal use.
+- `#5f6164` is a derived darker grey, not an LSU colour.
+- Wordmark: Montserrat SemiBold (SIL Open Font License, see `Montserrat-OFL.txt`), outlined, letter-spaced, not kerned.
+- The badge's polygonal outline echoes the angular LSU cap lettering without reproducing it. LSU marks belong to LSU:
+ confirm the badge is acceptable to LSU before using it outside this project.
+- No CMYK, EPS or PDF exports exist yet.
+
+## Previous logo
+
+The old Army Corps castle-style logo (`../corps_logo_cross2.svg`) and the old icons (`../triton*.ico`, `../proteus*.png`,
+`../proteusSimple.ico`, `../proteus.pdf`) are kept for the applications that need them; nothing in the docs build
+references them any more.
diff --git a/docs/source/_static/logo/lsu/png/proteus-badge-1024.png b/docs/source/_static/logo/lsu/png/proteus-badge-1024.png
new file mode 100644
index 0000000000..4502f43599
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-badge-1024.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-badge-512.png b/docs/source/_static/logo/lsu/png/proteus-badge-512.png
new file mode 100644
index 0000000000..db5c11a1e9
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-badge-512.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-16.png b/docs/source/_static/logo/lsu/png/proteus-favicon-16.png
new file mode 100644
index 0000000000..4f40244734
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-16.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-180.png b/docs/source/_static/logo/lsu/png/proteus-favicon-180.png
new file mode 100644
index 0000000000..bc58e77781
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-180.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-192.png b/docs/source/_static/logo/lsu/png/proteus-favicon-192.png
new file mode 100644
index 0000000000..0d1207df4a
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-192.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-32.png b/docs/source/_static/logo/lsu/png/proteus-favicon-32.png
new file mode 100644
index 0000000000..06541322d3
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-32.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-48.png b/docs/source/_static/logo/lsu/png/proteus-favicon-48.png
new file mode 100644
index 0000000000..d87a8706e9
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-48.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-512.png b/docs/source/_static/logo/lsu/png/proteus-favicon-512.png
new file mode 100644
index 0000000000..ab59f38b34
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-512.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-favicon-64.png b/docs/source/_static/logo/lsu/png/proteus-favicon-64.png
new file mode 100644
index 0000000000..f3014cdc09
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-favicon-64.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-lockup-h-dark-background-1200.png b/docs/source/_static/logo/lsu/png/proteus-lockup-h-dark-background-1200.png
new file mode 100644
index 0000000000..d793567861
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-lockup-h-dark-background-1200.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-lockup-h-light-background-1200.png b/docs/source/_static/logo/lsu/png/proteus-lockup-h-light-background-1200.png
new file mode 100644
index 0000000000..9a50adfd1b
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-lockup-h-light-background-1200.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-lockup-v-dark-background-800.png b/docs/source/_static/logo/lsu/png/proteus-lockup-v-dark-background-800.png
new file mode 100644
index 0000000000..7f15bef1f0
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-lockup-v-dark-background-800.png differ
diff --git a/docs/source/_static/logo/lsu/png/proteus-lockup-v-light-background-800.png b/docs/source/_static/logo/lsu/png/proteus-lockup-v-light-background-800.png
new file mode 100644
index 0000000000..1e33e87910
Binary files /dev/null and b/docs/source/_static/logo/lsu/png/proteus-lockup-v-light-background-800.png differ
diff --git a/docs/source/_static/logo/lsu/proteus-badge.svg b/docs/source/_static/logo/lsu/proteus-badge.svg
new file mode 100644
index 0000000000..930faa00d1
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-badge.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/lsu/proteus-favicon.ico b/docs/source/_static/logo/lsu/proteus-favicon.ico
new file mode 100644
index 0000000000..02cd16b128
Binary files /dev/null and b/docs/source/_static/logo/lsu/proteus-favicon.ico differ
diff --git a/docs/source/_static/logo/lsu/proteus-favicon.svg b/docs/source/_static/logo/lsu/proteus-favicon.svg
new file mode 100644
index 0000000000..de059372f5
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-favicon.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/lsu/proteus-lockup-h-dark-background.svg b/docs/source/_static/logo/lsu/proteus-lockup-h-dark-background.svg
new file mode 100644
index 0000000000..cf98d2ce98
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-lockup-h-dark-background.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/lsu/proteus-lockup-h-light-background.svg b/docs/source/_static/logo/lsu/proteus-lockup-h-light-background.svg
new file mode 100644
index 0000000000..7c5ee11a0b
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-lockup-h-light-background.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/lsu/proteus-lockup-v-dark-background.svg b/docs/source/_static/logo/lsu/proteus-lockup-v-dark-background.svg
new file mode 100644
index 0000000000..c8215f23cf
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-lockup-v-dark-background.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/lsu/proteus-lockup-v-light-background.svg b/docs/source/_static/logo/lsu/proteus-lockup-v-light-background.svg
new file mode 100644
index 0000000000..f02f453701
--- /dev/null
+++ b/docs/source/_static/logo/lsu/proteus-lockup-v-light-background.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-16.png b/docs/source/_static/logo/primary/png/proteus-favicon-16.png
new file mode 100644
index 0000000000..b984e12e67
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-16.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-180.png b/docs/source/_static/logo/primary/png/proteus-favicon-180.png
new file mode 100644
index 0000000000..ded1afcf73
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-180.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-192.png b/docs/source/_static/logo/primary/png/proteus-favicon-192.png
new file mode 100644
index 0000000000..8aefc0d0ab
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-192.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-32.png b/docs/source/_static/logo/primary/png/proteus-favicon-32.png
new file mode 100644
index 0000000000..b9b9223f5e
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-32.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-48.png b/docs/source/_static/logo/primary/png/proteus-favicon-48.png
new file mode 100644
index 0000000000..b41dde899d
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-48.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-512.png b/docs/source/_static/logo/primary/png/proteus-favicon-512.png
new file mode 100644
index 0000000000..3b7c95de5c
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-512.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-favicon-64.png b/docs/source/_static/logo/primary/png/proteus-favicon-64.png
new file mode 100644
index 0000000000..f5b2661a6f
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-favicon-64.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-lockup-h-dark-background-1200.png b/docs/source/_static/logo/primary/png/proteus-lockup-h-dark-background-1200.png
new file mode 100644
index 0000000000..d0951b2420
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-lockup-h-dark-background-1200.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-lockup-h-light-background-1200.png b/docs/source/_static/logo/primary/png/proteus-lockup-h-light-background-1200.png
new file mode 100644
index 0000000000..27b8a222f6
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-lockup-h-light-background-1200.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-lockup-v-dark-background-800.png b/docs/source/_static/logo/primary/png/proteus-lockup-v-dark-background-800.png
new file mode 100644
index 0000000000..73c78ec1a0
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-lockup-v-dark-background-800.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-lockup-v-light-background-800.png b/docs/source/_static/logo/primary/png/proteus-lockup-v-light-background-800.png
new file mode 100644
index 0000000000..edae4a9f14
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-lockup-v-light-background-800.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-mark-1024.png b/docs/source/_static/logo/primary/png/proteus-mark-1024.png
new file mode 100644
index 0000000000..96cb9c34c6
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-mark-1024.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-mark-512.png b/docs/source/_static/logo/primary/png/proteus-mark-512.png
new file mode 100644
index 0000000000..3d12c909b4
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-mark-512.png differ
diff --git a/docs/source/_static/logo/primary/png/proteus-mark-light-background-1024.png b/docs/source/_static/logo/primary/png/proteus-mark-light-background-1024.png
new file mode 100644
index 0000000000..8785bc22b9
Binary files /dev/null and b/docs/source/_static/logo/primary/png/proteus-mark-light-background-1024.png differ
diff --git a/docs/source/_static/logo/primary/proteus-favicon.ico b/docs/source/_static/logo/primary/proteus-favicon.ico
new file mode 100644
index 0000000000..52e3f59127
Binary files /dev/null and b/docs/source/_static/logo/primary/proteus-favicon.ico differ
diff --git a/docs/source/_static/logo/primary/proteus-favicon.svg b/docs/source/_static/logo/primary/proteus-favicon.svg
new file mode 100644
index 0000000000..cad934bddc
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-favicon.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-h-auto.svg b/docs/source/_static/logo/primary/proteus-lockup-h-auto.svg
new file mode 100644
index 0000000000..5572ea50f2
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-h-auto.svg
@@ -0,0 +1,6 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-h-dark-background.svg b/docs/source/_static/logo/primary/proteus-lockup-h-dark-background.svg
new file mode 100644
index 0000000000..597ed8e8df
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-h-dark-background.svg
@@ -0,0 +1,5 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-h-light-background.svg b/docs/source/_static/logo/primary/proteus-lockup-h-light-background.svg
new file mode 100644
index 0000000000..e44cf05653
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-h-light-background.svg
@@ -0,0 +1,5 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-v-auto.svg b/docs/source/_static/logo/primary/proteus-lockup-v-auto.svg
new file mode 100644
index 0000000000..8afa45a56e
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-v-auto.svg
@@ -0,0 +1,6 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-v-dark-background.svg b/docs/source/_static/logo/primary/proteus-lockup-v-dark-background.svg
new file mode 100644
index 0000000000..804c546983
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-v-dark-background.svg
@@ -0,0 +1,5 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-lockup-v-light-background.svg b/docs/source/_static/logo/primary/proteus-lockup-v-light-background.svg
new file mode 100644
index 0000000000..bd9e046c11
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-lockup-v-light-background.svg
@@ -0,0 +1,5 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-mark-auto.svg b/docs/source/_static/logo/primary/proteus-mark-auto.svg
new file mode 100644
index 0000000000..623b57eb32
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-mark-auto.svg
@@ -0,0 +1,5 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-mark-light-background.svg b/docs/source/_static/logo/primary/proteus-mark-light-background.svg
new file mode 100644
index 0000000000..742f8ab308
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-mark-light-background.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/_static/logo/primary/proteus-mark.svg b/docs/source/_static/logo/primary/proteus-mark.svg
new file mode 100644
index 0000000000..6a8b6e1c6d
--- /dev/null
+++ b/docs/source/_static/logo/primary/proteus-mark.svg
@@ -0,0 +1,4 @@
+
diff --git a/docs/source/conf.py b/docs/source/conf.py
index afc9b1f807..daef118cfb 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -197,12 +197,12 @@ def linkcode_resolve(domain, info):
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
-html_logo = "_static/corps_logo_cross2.svg"
+html_logo = "_static/logo/primary/proteus-lockup-v-light-background.svg"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
-html_favicon = "_static/tritonBorder.ico"
+html_favicon = "_static/logo/primary/proteus-favicon.ico"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
@@ -284,7 +284,7 @@ def linkcode_resolve(domain, info):
# The name of an image file (relative to this directory) to place at the top of
# the title page.
-#latex_logo = '_static/tritonCorps.png'
+#latex_logo = '_static/logo/primary/png/proteus-lockup-v-light-background-800.png'
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
diff --git a/docs/source/models/SWFlow.rst b/docs/source/models/SWFlow.rst
index 0b33b51a14..68c5f5b8db 100644
--- a/docs/source/models/SWFlow.rst
+++ b/docs/source/models/SWFlow.rst
@@ -20,7 +20,7 @@ the action of gravity under the assumption that the deformations of the free sur
are small compared to the water height.
The implementation of the SWEs with source documentation is
-available here: :py:mod:`proteus.mprans.SW2DCV`.
+available here: :py:mod:`proteus.kernels.SW2DCV`.
@@ -32,7 +32,7 @@ Green-Naghdi equations, where h is the mesh size. The Green-Naghdi equations
are used to describe dispersive water waves.
The implementation of the mGN equations with source documentation is
-available here: :py:mod:`proteus.mprans.GN_SW2DCV`.
+available here: :py:mod:`proteus.kernels.GN_SW2DCV`.
Running the tests
diff --git a/docs/source/models/adr.rst b/docs/source/models/adr.rst
index 36c16ec91b..5a6a0225e2 100644
--- a/docs/source/models/adr.rst
+++ b/docs/source/models/adr.rst
@@ -7,7 +7,7 @@ Advection-Diffusion-Reaction with Unfitted Interfaces
Description
===========
-The ADR model (:py:mod:`proteus.ADR`) solves linear advection-diffusion-reaction equations
+The ADR model (:py:mod:`proteus.kernels.ADR`) solves linear advection-diffusion-reaction equations
.. math::
@@ -37,7 +37,7 @@ the optimal orders for :math:`p=1,2` and coefficient contrasts up to 1000: :math
:math:`L^2` and :math:`p` in the broken :math:`H^1` seminorm. The :math:`L^\infty` error also
decreases at order :math:`p+1` on average, with fluctuating rates at the highest contrast.
-All options are arguments of :py:class:`proteus.ADR.Coefficients`; its documentation lists
+All options are arguments of :py:class:`proteus.kernels.ADR.Coefficients`; its documentation lists
them with the values used in the paper below.
diff --git a/docs/source/models/body_dynamics.rst b/docs/source/models/body_dynamics.rst
index a46dc8b11b..d0bb184f69 100644
--- a/docs/source/models/body_dynamics.rst
+++ b/docs/source/models/body_dynamics.rst
@@ -146,7 +146,7 @@ cable is desired, such as a catenary shape.
ProtChAddedMass
---------------
-A class to deal with the added mass model from proteus.mprans.AddedMass. This
+A class to deal with the added mass model from proteus.kernels.AddedMass. This
class should not be instantiated manually and will be automatically
instantiating as a variable of `ProtChSystem` (accessible as
`my_system.ProtChAddedMass`). It is used to build the added mass matrix for the
diff --git a/docs/source/models/free_surface.rst b/docs/source/models/free_surface.rst
index 29916b416a..d2bdf6bbd0 100644
--- a/docs/source/models/free_surface.rst
+++ b/docs/source/models/free_surface.rst
@@ -10,14 +10,14 @@ VOF - NCLS
In this implementation, the following 4 models must be solved in order:
-* Volume of Fluid (VOF): :py:mod:`proteus.mprans.VOF`
-* Non-conservative level set (NCLS): :py:mod:`proteus.mprans.NCLS`
-* Redistancing: :py:mod:`proteus.mprans.RDLS`
-* Mass correction: :py:mod:`proteus.mprans.MCorr`
+* Volume of Fluid (VOF): :py:mod:`proteus.kernels.VOF`
+* Non-conservative level set (NCLS): :py:mod:`proteus.kernels.NCLS`
+* Redistancing: :py:mod:`proteus.kernels.RDLS`
+* Mass correction: :py:mod:`proteus.kernels.MCorr`
CLSVOF
======
In this implementation, a conservative level set is used and only the following
-model must be solved: :py:mod:`proteus.mprans.CLSVOF`.
+model must be solved: :py:mod:`proteus.kernels.CLSVOF`.
diff --git a/docs/source/models/navier_stokes.rst b/docs/source/models/navier_stokes.rst
index bdb705525a..8f92a00c2b 100644
--- a/docs/source/models/navier_stokes.rst
+++ b/docs/source/models/navier_stokes.rst
@@ -17,14 +17,14 @@ Two-Phase
=========
The two-phase implementation of Navier-Stokes, with source documentation
-available here: :py:mod:`proteus.mprans.RANS2P`.
+available here: :py:mod:`proteus.kernels.RANS2P`.
Three-Phase
===========
The three-phase implementation of Navier-Stokes, with source documentation
-available here: :py:mod:`proteus.mprans.RANS3P`.
+available here: :py:mod:`proteus.kernels.RANS3P`.
Dealing with Moving Domains
@@ -39,7 +39,7 @@ Moving (ALE) Mesh
-----------------
In the current implementation, if a model for moving the mesh is used such as
-:py:mod:`proteus.mprans.MoveMesh`, it should be the first model to be solved,
+:py:mod:`proteus.kernels.MoveMesh`, it should be the first model to be solved,
as the mesh velocity is calculated from the previous time step.
@@ -47,5 +47,5 @@ Immersed Boundaries
-------------------
The two-phase implementation of Navier-Stokes with immersed solid boundaries, with
-source documentation available here: :py:mod:`proteus.mprans.RANS2P_IB`. This is a different
+source documentation available here: :py:mod:`proteus.kernels.RANS2P_IB`. This is a different
method from the immersed finite elements of the ADR model (:ref:`adr`).
diff --git a/docs/source/tools/spatial_tools.rst b/docs/source/tools/spatial_tools.rst
index a4079f4a09..0045ad111e 100644
--- a/docs/source/tools/spatial_tools.rst
+++ b/docs/source/tools/spatial_tools.rst
@@ -3,8 +3,7 @@
SpatialTools
************
-source: :py:mod:`proteus.SpatialTools` and
-:py:mod:`proteus.mprans.SpatialTools`
+source: :py:mod:`proteus.SpatialTools`
Usage
=====
@@ -13,8 +12,8 @@ Using spatial tools
#. Create a domain from :py:mod:`proteus.Domain`.
#. Create geometries that will be part of this domain from
- :py:mod:`proteus.SpatialTools` or :py:mod:`proteus.mprans.SpatialTools`.
-#. Assemble domain with :py:meth:`proteus.SpatialTools.assembleDomain` or :py:meth:`proteus.mprans.SpatialTools.assembleDomain`.
+ :py:mod:`proteus.SpatialTools`.
+#. Assemble domain with :py:meth:`proteus.SpatialTools.assembleDomain` (two-phase flow boundary conditions when any shape is a ``ShapeRANS``).
Import
------
@@ -25,12 +24,12 @@ The base `SpatialTools` module can be imported as follows:
from proteus import SpatialTools as st
-The `mprans` version of `SpatialTools`, adding functionality specific to
+The two-phase flow part of `SpatialTools` (formerly `proteus.kernels.SpatialTools`, merged into `proteus.SpatialTools`; the old import path still works and warns), adding functionality specific to
multi-phase flows, can be imported as follows:
.. code-block:: python
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
Choosing the domain
-------------------
@@ -68,8 +67,8 @@ BoundaryConditions with SpatialTools
Usage
^^^^^
-The mprans version of SpatialTools also associate geometry boundaries with
-`BoundaryCondition` instances from mprans.BoundaryConditions. These
+SpatialTools also associates geometry boundaries with
+`BoundaryCondition` instances from BoundaryConditions. These
`BoundaryCondition` instances are easily accessible through a dictionary with
predefined names, e.g. for a `Rectangle` shape instance named `my_rectangle`,
``my_rectangle.BC['x-']`` is for accessing the boundary conditions of the left
@@ -124,7 +123,7 @@ Complete Examples
.. code-block:: python
from proteus import Domain
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
domain = Domain.PlanarStraightLineGraphDomain()
@@ -159,7 +158,7 @@ Complete Examples
.. code-block:: python
from proteus import Domain
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
domain = Domain.PiecewiseLinearComplexDomain()
@@ -200,7 +199,7 @@ Complete Examples
#See complete case in https://github.com/erdc/air-water-vv/tree/master/3d/STLShape
from proteus import Domain
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
from proteus.Profiling import logEvent as log
domain = Domain.PiecewiseLinearComplexDomain()
@@ -225,7 +224,7 @@ Complete Examples
#See complete case in https://github.com/erdc/air-water-vv/tree/master/3d/STLShape_Zones
from proteus import Domain
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
from proteus.Profiling import logEvent as log
domain = Domain.PiecewiseLinearComplexDomain()
@@ -295,7 +294,7 @@ Base classes
------------
The following classes are accessible with an import from `proteus.SpatialTools`
-and/or `proteus.mprans.SpatialTools`. Importing them from the mprans module
+(the former `proteus.kernels.SpatialTools` is the same module). Importing it makes every shape a two-phase flow shape, which
adds functionality such as the possibility to set multi-phase flow boundary
conditions and relaxation zones.
@@ -455,7 +454,7 @@ mprans specific
---------------
The following classes are for use with multi-phase flow and can only be
-imported from `proteus.mprans.SpatialTools`.
+imported from `proteus.SpatialTools`.
Tank2D
diff --git a/experimental/adrh/vof_capture.py b/experimental/adrh/vof_capture.py
index bdfd40f514..609f0a9fbd 100644
--- a/experimental/adrh/vof_capture.py
+++ b/experimental/adrh/vof_capture.py
@@ -107,7 +107,7 @@ def main(argv):
from proteus import Comm
Comm.init()
- from proteus.mprans import cArgumentsDict
+ from proteus import cArgumentsDict
base = cArgumentsDict.ArgumentsDict
diff --git a/proteus/ArchiveFields.py b/proteus/ArchiveFields.py
index e91c382839..12e9e2faf5 100644
--- a/proteus/ArchiveFields.py
+++ b/proteus/ArchiveFields.py
@@ -45,7 +45,7 @@
.. code-block:: python
- # in proteus/mprans/SW2DCV.py, class Coefficients
+ # in proteus/kernels/SW2DCV.py, class Coefficients
def archiveFields(self, lm):
yield ArchiveField("bathymetry", self.b.dof)
yield ArchiveField("eta", self.b.dof + lm.u[0].dof)
diff --git a/proteus/mprans/ArgumentsDict.cpp b/proteus/ArgumentsDict.cpp
similarity index 100%
rename from proteus/mprans/ArgumentsDict.cpp
rename to proteus/ArgumentsDict.cpp
diff --git a/proteus/mprans/ArgumentsDict.h b/proteus/ArgumentsDict.h
similarity index 100%
rename from proteus/mprans/ArgumentsDict.h
rename to proteus/ArgumentsDict.h
diff --git a/proteus/BoundaryConditions.pxd b/proteus/BoundaryConditions.pxd
index d191b2b97e..9dcb2d6b8b 100644
--- a/proteus/BoundaryConditions.pxd
+++ b/proteus/BoundaryConditions.pxd
@@ -22,3 +22,198 @@ cdef class BoundaryCondition:
cpdef void resetBC(self)
# cpdef void setConstantBC(self, double value)
# cpdef void setLinearBC(self, double a0, double a1, int i)
+
+from libcpp cimport bool
+
+ctypedef double[:,:,:] double_memview3
+ctypedef double[:,:] double_memview2
+ctypedef double[:] double_memview1
+ctypedef int[:] int_memview1
+
+# ctypedef double (*cpp_uOfXT) (BC_RANS, double[:], double)
+
+cdef class BC_RANS(BC_Base):
+ cdef double[:] zero_array
+ cdef double f
+ cdef __cppClass_WavesCharacteristics waves
+ cdef object body
+ cdef double[:] wind_speed
+ cdef double[:, :] body_python_rot_matrix
+ cdef double[:] body_python_last_pos
+ cdef double[:] body_python_h
+ cdef public:
+ # dirichlet
+ cdef BoundaryCondition p_dirichlet
+ cdef BoundaryCondition u_dirichlet
+ cdef BoundaryCondition v_dirichlet
+ cdef BoundaryCondition w_dirichlet
+ cdef BoundaryCondition phi_dirichlet
+ cdef BoundaryCondition vof_dirichlet
+ cdef BoundaryCondition k_dirichlet
+ cdef BoundaryCondition dissipation_dirichlet
+ cdef BoundaryCondition pAddedMass_dirichlet
+ # advective
+ cdef BoundaryCondition p_advective
+ cdef BoundaryCondition u_advective
+ cdef BoundaryCondition v_advective
+ cdef BoundaryCondition w_advective
+ cdef BoundaryCondition vof_advective
+ cdef BoundaryCondition k_advective
+ cdef BoundaryCondition dissipation_advective
+ #diffusive
+ cdef BoundaryCondition u_diffusive
+ cdef BoundaryCondition v_diffusive
+ cdef BoundaryCondition w_diffusive
+ cdef BoundaryCondition k_diffusive
+ cdef BoundaryCondition dissipation_diffusive
+ # mesh
+ cdef BoundaryCondition hx_dirichlet
+ cdef BoundaryCondition hy_dirichlet
+ cdef BoundaryCondition hz_dirichlet
+ cdef BoundaryCondition u_stress
+ cdef BoundaryCondition v_stress
+ cdef BoundaryCondition w_stress
+ # sediment solver
+ cdef BoundaryCondition us_dirichlet
+ cdef BoundaryCondition vs_dirichlet
+ cdef BoundaryCondition ws_dirichlet
+ cdef BoundaryCondition vos_dirichlet
+ cdef BoundaryCondition us_advective
+ cdef BoundaryCondition vs_advective
+ cdef BoundaryCondition ws_advective
+ cdef BoundaryCondition vos_advective
+ cdef BoundaryCondition us_diffusive
+ cdef BoundaryCondition vs_diffusive
+ cdef BoundaryCondition ws_diffusive
+ # projection scheme
+ cdef BoundaryCondition pInit_dirichlet
+ cdef BoundaryCondition pInc_dirichlet
+ cdef BoundaryCondition pInit_advective
+ cdef BoundaryCondition pInc_advective
+ cdef BoundaryCondition pInit_diffusive
+ cdef BoundaryCondition pInc_diffusive
+ # clsvof
+ cdef BoundaryCondition clsvof_dirichlet
+ cdef BoundaryCondition clsvof_advective
+ cdef BoundaryCondition clsvof_diffusive
+
+
+ # functions
+ # cpdef void reset(self)
+ # cpdef void setNonMaterial(self)
+ # cpdef void setTank(self)
+ # cpdef void setFixedNodes(self)
+ # cpdef void setNoSlip(self)
+ # cpdef void setFreeSlip(self)
+ # cpdef void setAtmosphere(self, double[:] orientation=*, double vof_air=*)
+ # cpdef void setMoveMesh(self, double[:] last_pos, double[:] h=*, double[:,:] rot_matrix=*)
+ @cython.locals(hx=np.ndarray)
+ cpdef double[:] __cpp_MoveMesh_h(self, double[:] x, double t)
+ cpdef double __cpp_MoveMesh_hx(self, double[:] x, double t)
+ cpdef double __cpp_MoveMesh_hy(self, double[:] x, double t)
+ cpdef double __cpp_MoveMesh_hz(self, double[:] x, double t)
+# @cython.locals(waveHeight=double, wavePhi=double,
+# water_speed=double_memview1, x_max=double_memview1,
+# u=cython.p_double, H=double)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(self, double[:] x, double t)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(self, double[:] x, double t)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(self, double[:] x, double t)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(self, double[:] x, double t)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(self, double[:] x, double t)
+ cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(self, double[:] x, double t)
+
+ctypedef double[:] (*cfvel) (double[3], double) # pointer to velocity function
+ctypedef double (*cfeta) (double[3], double) # pointer to eta function
+ctypedef double[:] (*cfvelrel) (RelaxationZone, double[3], double) # pointer to velocity function of RelaxationZone class
+ctypedef double (*cfphirel) (RelaxationZone, double[3]) # pointer to phi function of RelaxationZone class
+ctypedef double (*cfphiwave) (RelaxationZone, double[3]) # pointer to phi function of RelaxationZone class
+ctypedef np.float64_t float64_t
+ctypedef np.int64_t int64_t
+
+cdef class RelaxationZone:
+ cdef double[:] wind_speed
+ cdef double[:] u_calc # calculated velocity
+ # wave characteristics (if any)
+ cdef cfvelrel uu
+ cdef cfphirel phi
+ cdef double mwl
+ cdef cfeta eta
+ cdef double waveHeight
+ cdef double wavePhi
+ cdef double waterSpeed
+ cdef int nd
+ cdef double[:] zero_vel
+ cdef __cppClass_WavesCharacteristics waves
+ cdef public:
+ object Shape
+ str zone_type
+ double dragAlpha
+ double dragBeta
+ double porosity
+ double epsFact_solid
+ double epsFact_porous
+ double vert_axis
+ double[:] center
+ double[:] orientation
+ cpdef void calculate_init(self)
+ cdef double[:] calculate_vel(self, cython.p_double x, double t)
+ @cython.locals(xx=double_memview1, waveHeight=double, wavePhi=double,
+ waterSpeed=double_memview1, x_max=double_memview1, H=double,
+ u=cython.double[3], o1=double, o2=double, o3=double)
+ cdef double[:] __cpp_calculate_vel_wave(self, double* x, double t)
+ cdef double[:] __cpp_calculate_vel_zero(self, double* x, double t)
+ cdef double calculate_phi(self, double* x)
+ @cython.locals(d1=double, d2=double, d3=double, phi=double,
+ o1=double, o2=double, o3=double)
+ cdef double __cpp_calculate_phi_porous(self, double[3] x)
+ cdef double __cpp_calculate_phi_porous_sponge(self, double[3] x)
+
+cdef class RelaxationZoneWaveGenerator:
+ cdef int nd # dimension
+ cdef int max_flag # maximum region flag of relaxation zones (initialised in calculate_init)
+ cdef np.ndarray zones_array # zones array for fast access
+ cdef public:
+ dict zones # zones dictionary
+ object model # model attached to zone
+ object ar #
+ # cpdef RelaxationZoneWaveGenerator attachModel(self, dict, int) # needed
+ # cpdef void attachAuxiliaryVariables(self, dict) # needed
+ @cython.locals(zones=np.ndarray)
+ cpdef void calculate_init(self)
+ cpdef void calculate(self)
+ @cython.locals(m=object, zone=RelaxationZone, mType=int, nE=int, nk=int,
+ qx=double_memview3, x=cython.double[3], t=double, nl=int,
+ q_phi_porous=double_memview2, phi=double,
+ q_velocity_solid=double_memview3, u=double_memview1, mTypes=int_memview1)
+ cdef void __cpp_iterate(self) # main iteration loop
+
+
+cdef class __cppClass_WavesCharacteristics:
+ cdef int vert_axis # vertical axis
+ # relaxation zone info (if any)
+ cdef double[:] center # center of zone
+ cdef double[:] orientation # orientation of zone
+ # zero array
+ cdef double[:] zero_vel
+ cdef double[:] _b_or
+ cdef double[:] wind_speed
+ cdef double vof_air
+ cdef double vof_water
+ cdef double smoothing
+ cdef public:
+ # wave class from WaveTools
+ object WT
+ @cython.locals(phi=double, waterSpeed=double_memview1,
+ H=double)
+ cdef double[:] __cpp_calculate_velocity(self, double* x, double t)
+ @cython.locals(ux=double_memview1, b0=double, b1=double, b2=double, u0=double,
+ u1=double, u2=double)
+ cdef double __cpp_calculate_pressure(self, double* x, double t)
+ @cython.locals(level=double)
+ cdef double __cpp_calculate_phi(self, double* x, double t)
+ @cython.locals(phi=double, H=double)
+ cdef double __cpp_calculate_vof(self, double* x, double t)
+ @cython.locals(H=double)
+ cdef double __cpp_calculate_smoothing_H(self, double phi)
+
+cdef double* __x_to_cpp(double[:])
diff --git a/proteus/BoundaryConditions.py b/proteus/BoundaryConditions.py
index 7e0231653e..947ae3dfb1 100644
--- a/proteus/BoundaryConditions.py
+++ b/proteus/BoundaryConditions.py
@@ -6,16 +6,33 @@
# cython: initializedcheck=False
# cython: language_level=3
import cython
+import os, sys
import numpy as np
"""
-Module for creating boundary conditions. Imported in SpatialTools.py
+Module for creating boundary conditions: the generic classes (BC_Base, BoundaryCondition) and the two-phase
+flow ones (BC_RANS, RelaxationZone, RelaxationZoneWaveGenerator, WallFunctions, kWall; formerly
+proteus.kernels.BoundaryConditions, merged here by C49 R1). Imported in SpatialTools.py
.. inheritance-diagram:: proteus.BoundaryConditions
:parts: 1
"""
+from proteus import AuxiliaryVariables, Comm
+from proteus.ctransportCoefficients import (smoothedHeaviside,
+ smoothedHeaviside_integral)
+from proteus import WaveTools as wt
+from proteus.Profiling import logEvent
+from math import cos, sin, sqrt, atan2, acos, asin
+from mpi4py import MPI
+from scipy import spatial
__all__ = ['BC_Base',
- 'BoundaryCondition']
+ 'BoundaryCondition',
+ 'BC_RANS',
+ 'RelaxationZone',
+ 'RelaxationZoneWaveGenerator',
+ '_cppClass_WavesCharacteristics',
+ 'WallFunctions',
+ 'kWall']
class BC_Base:
"""
@@ -123,4 +140,1639 @@ def setLinearRamp(self,t1,value):
value: float
Variable value
"""
- self.uOfXT = lambda x, t, n=np.zeros(3,): min( t/t1, 1)*value
\ No newline at end of file
+ self.uOfXT = lambda x, t, n=np.zeros(3,): min( t/t1, 1)*value
+
+
+class BC_RANS(BC_Base):
+ """
+ Class regrouping boundary conditions for two-phase flows
+ """
+
+ def __init__(self, shape=None, name=None, b_or=None, b_i=0., nd=None):
+ super(BC_RANS, self).__init__(shape=shape, name=name, b_or=b_or, b_i=b_i, nd=nd)
+ # _dirichlet
+ self.p_dirichlet = BoundaryCondition() # pressure
+ self.u_dirichlet = BoundaryCondition() # velocity u
+ self.v_dirichlet = BoundaryCondition() # velocity v
+ self.w_dirichlet = BoundaryCondition() # velocity w
+ self.phi_dirichlet = BoundaryCondition() # phi
+ self.vof_dirichlet = BoundaryCondition() # VOF
+ self.k_dirichlet = BoundaryCondition() # kappa
+ self.dissipation_dirichlet = BoundaryCondition() # dissipation
+ self.pAddedMass_dirichlet = BoundaryCondition()
+ # _advective
+ self.p_advective = BoundaryCondition()
+ self.u_advective = BoundaryCondition()
+ self.v_advective = BoundaryCondition()
+ self.w_advective = BoundaryCondition()
+ self.vof_advective = BoundaryCondition()
+ self.k_advective = BoundaryCondition()
+ self.dissipation_advective = BoundaryCondition()
+ # _diffusive
+ self.u_diffusive = BoundaryCondition()
+ self.v_diffusive = BoundaryCondition()
+ self.w_diffusive = BoundaryCondition()
+ self.k_diffusive = BoundaryCondition()
+ self.dissipation_diffusive = BoundaryCondition()
+ # moveMesh boundary conditions
+ self.hx_dirichlet = BoundaryCondition()
+ self.hy_dirichlet = BoundaryCondition()
+ self.hz_dirichlet = BoundaryCondition()
+ self.u_stress = BoundaryCondition()
+ self.v_stress = BoundaryCondition()
+ self.w_stress = BoundaryCondition()
+ self.u_stress.uOfXT = 0.
+ self.v_stress.uOfXT = 0.
+ self.w_stress.uOfXT = 0.
+ # sediment solver
+ self.us_dirichlet = BoundaryCondition() # sediment velocity u
+ self.vs_dirichlet = BoundaryCondition() # sediment velocity v
+ self.ws_dirichlet = BoundaryCondition() # sediment velocity w
+ self.vos_dirichlet = BoundaryCondition() # VOS
+ self.us_advective = BoundaryCondition()
+ self.vs_advective = BoundaryCondition()
+ self.ws_advective = BoundaryCondition()
+ self.vos_advective = BoundaryCondition()
+ self.us_diffusive = BoundaryCondition()
+ self.vs_diffusive = BoundaryCondition()
+ self.ws_diffusive = BoundaryCondition()
+ # projection scheme
+ self.pInit_dirichlet = BoundaryCondition() # initial pressure
+ self.pInc_dirichlet = BoundaryCondition() # pressure increment
+ self.pInit_advective = BoundaryCondition()
+ self.pInc_advective = BoundaryCondition()
+ self.pInit_diffusive = BoundaryCondition()
+ self.pInc_diffusive = BoundaryCondition()
+ # clsvof
+ self.clsvof_dirichlet = BoundaryCondition()
+ self.clsvof_advective = BoundaryCondition()
+ self.clsvof_diffusive = BoundaryCondition()
+
+ def reset(self):
+ """
+ Resets all BoundaryCondtion functions to None, apart from the BCs
+ affecting: moving mesh
+ """
+ # self.BC_type = 'None'
+ self.p_dirichlet.resetBC()
+ self.pInit_dirichlet.resetBC()
+ self.pInc_dirichlet.resetBC()
+ self.u_dirichlet.resetBC()
+ self.v_dirichlet.resetBC()
+ self.w_dirichlet.resetBC()
+ self.phi_dirichlet.resetBC()
+ self.vof_dirichlet.resetBC()
+ self.k_dirichlet.resetBC()
+ self.dissipation_dirichlet.resetBC()
+ self.us_dirichlet.resetBC()
+ self.vs_dirichlet.resetBC()
+ self.ws_dirichlet.resetBC()
+ self.vos_dirichlet.resetBC()
+ self.p_advective.resetBC()
+ self.pInit_advective.resetBC()
+ self.pInc_advective.resetBC()
+ self.u_advective.resetBC()
+ self.v_advective.resetBC()
+ self.w_advective.resetBC()
+ self.vof_advective.resetBC()
+ self.k_advective.resetBC()
+ self.dissipation_advective.resetBC()
+ self.us_advective.resetBC()
+ self.vs_advective.resetBC()
+ self.ws_advective.resetBC()
+ self.vos_advective.resetBC()
+ self.pInit_diffusive.resetBC()
+ self.pInc_diffusive.resetBC()
+ self.u_diffusive.resetBC()
+ self.v_diffusive.resetBC()
+ self.w_diffusive.resetBC()
+ self.k_diffusive.resetBC()
+ self.dissipation_diffusive.resetBC()
+ self.us_diffusive.resetBC()
+ self.vs_diffusive.resetBC()
+ self.ws_diffusive.resetBC()
+ self.clsvof_dirichlet.resetBC()
+ self.clsvof_advective.resetBC()
+ self.clsvof_diffusive.resetBC()
+
+ def setNonMaterial(self):
+ """
+ Sets non-material boundary conditions (diffusive flux and advective vof
+ to 0.).
+ """
+ self.reset()
+ self.BC_type = 'NonMaterial'
+ self.vof_advective.setConstantBC(0.)
+ self.vos_advective.setConstantBC(0.)
+ self.p_advective.setConstantBC(0.)
+ self.u_advective.setConstantBC(0.)
+ self.v_advective.setConstantBC(0.)
+ self.w_advective.setConstantBC(0.)
+ self.u_diffusive.setConstantBC(0.)
+ self.v_diffusive.setConstantBC(0.)
+ self.w_diffusive.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+ self.ws_diffusive.setConstantBC(0.)
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+ self.pInc_diffusive.setConstantBC(0.)
+
+ def setTank(self, b_or=None):
+ if b_or is None:
+ assert self._b_or is not None, 'Boundary orientation must be defined!'
+ b_or = self._b_or
+ self.u_stress.uOfXT = 0.
+ self.v_stress.uOfXT = 0.
+ self.w_stress.uOfXT = 0.
+ self.hx_dirichlet.resetBC()
+ self.hy_dirichlet.resetBC()
+ self.hz_dirichlet.resetBC()
+ if b_or[0] == 1 or b_or[0] == -1:
+ self.hx_dirichlet.setConstantBC(0.)
+ self.u_stress.uOfXT = None
+ elif b_or[1] == 1 or b_or[1] == -1:
+ self.hy_dirichlet.setConstantBC(0.)
+ self.v_stress.uOfXT = None
+ elif len(b_or) > 2 and (b_or[2] == 1 or b_or[2] == -1):
+ self.hz_dirichlet.setConstantBC(0.)
+ self.w_stress.uOfXT = None
+
+ def setFixedNodes(self):
+ """
+ For moving domains: fixes nodes/boundary
+ """
+ self.hx_dirichlet.setConstantBC(0.)
+ self.hy_dirichlet.setConstantBC(0.)
+ self.hz_dirichlet.setConstantBC(0.)
+ self.u_stress.uOfXT = 0.
+ self.v_stress.uOfXT = 0.
+ self.w_stress.uOfXT = 0.
+
+ def setNoSlip(self):
+ """
+ Sets no slip conditions at the boundary
+ """
+ self.reset()
+ self.BC_type = 'NoSlip'
+ # dirichlet
+ self.u_dirichlet.setConstantBC(0.)
+ self.v_dirichlet.setConstantBC(0.)
+ self.w_dirichlet.setConstantBC(0.)
+ self.us_dirichlet.setConstantBC(0.)
+ self.vs_dirichlet.setConstantBC(0.)
+ self.ws_dirichlet.setConstantBC(0.)
+ self.k_dirichlet.setConstantBC(1e-20)
+ self.dissipation_dirichlet.setConstantBC(1e-10)
+ # advective
+ self.p_advective.setConstantBC(0.)
+ self.pInit_advective.setConstantBC(0.)
+ self.pInc_advective.setConstantBC(0.)
+ self.vof_advective.setConstantBC(0.)
+ self.vos_advective.setConstantBC(0.)
+ # diffusive
+ self.pInc_diffusive.setConstantBC(0.)
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+
+ def setFreeSlip(self):
+ """
+ Sets free slip conditions at the boundary
+ """
+ self.reset()
+ self.BC_type = 'FreeSlip'
+ # dirichlet
+ self.k_dirichlet.setConstantBC(1e-20)
+ self.dissipation_dirichlet.setConstantBC(1e-10)
+ # advective
+ self.p_advective.setConstantBC(0.)
+ self.pInit_advective.setConstantBC(0.)
+ self.pInc_advective.setConstantBC(0.)
+ self.u_advective.setConstantBC(0.)
+ self.v_advective.setConstantBC(0.)
+ self.w_advective.setConstantBC(0.)
+ self.us_advective.setConstantBC(0.)
+ self.vs_advective.setConstantBC(0.)
+ self.ws_advective.setConstantBC(0.)
+ self.vof_advective.setConstantBC(0.)
+ self.vos_advective.setConstantBC(0.)
+ # diffusive
+ self.u_diffusive.setConstantBC(0.)
+ self.v_diffusive.setConstantBC(0.)
+ self.w_diffusive.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+ self.ws_diffusive.setConstantBC(0.)
+ self.pInc_diffusive.setConstantBC(0.)
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+
+ def setConstantInletVelocity(self, U, ramp, kk, dd , b_or):
+ """
+ Sets constant velocity in each inlet face with ramping up and turbulence properties
+ """
+ self.reset()
+ self.BC_type = 'constantInletVelocity'
+ Uin = np.dot(U,b_or)
+ uu = U[0]
+ vv = U[1]
+ ww = U[2]
+
+ # dirichlet
+ self.u_dirichlet.setLinearRamp(ramp, uu)
+ self.v_dirichlet.setLinearRamp(ramp ,vv)
+ self.w_dirichlet.setLinearRamp(ramp ,ww)
+ self.us_dirichlet.setConstantBC(0.)
+ self.vs_dirichlet.setConstantBC(0.)
+ self.ws_dirichlet.setConstantBC(0.)
+ self.k_dirichlet.setConstantBC(kk)
+ self.dissipation_dirichlet.setConstantBC(dd)
+ #advective
+ self.p_advective.setLinearRamp(ramp, Uin)
+ self.pInit_advective.setConstantBC(0.)
+ self.pInc_advective.setLinearRamp(ramp,Uin)
+ # diffusive
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+ self.ws_diffusive.setConstantBC(0.)
+ def setConstantOutletPressure(self, p, rho, g ,kk, dd, b_or):
+ """
+ Sets constant pressure in each outlet face for single phase flows
+ """
+ self.reset()
+ self.BC_type = 'constantOutletPressure'
+ # dirichlet
+ a1 = rho*g
+ self.u_dirichlet.setConstantBC(0.)
+ self.v_dirichlet.setConstantBC(0.)
+ self.w_dirichlet.setConstantBC(0.)
+ self.us_dirichlet.setConstantBC(0.)
+ self.vs_dirichlet.setConstantBC(0.)
+ self.ws_dirichlet.setConstantBC(0.)
+
+ self.p_dirichlet.setLinearBC(p,a1)
+ self.pInit_dirichlet.setLinearBC(p, a1)
+ self.pInc_dirichlet.setConstantBC(0.)
+ self.k_dirichlet.setConstantBC(kk)
+ self.dissipation_dirichlet.setConstantBC(dd)
+
+ # diffusive
+ if b_or[0] == 1. or b_or[0] == -1.:
+ self.u_diffusive.setConstantBC(0.)
+ if b_or[1] == 1. or b_or[1] == -1.:
+ self.v_diffusive.setConstantBC(0.)
+ if b_or[2] == 1. or b_or[2] == -1.:
+ self.w_diffusive.setConstantBC(0.)
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+ self.ws_diffusive.setConstantBC(0.)
+
+ def setAtmosphere(self, orientation=None, vof_air=1.,kInflow=None,dInflow=None):
+ """
+ Sets atmosphere boundary conditions (water can come out)
+ (!) pressure dirichlet set to 0 for this BC
+
+ Parameters
+ ----------
+ orientation: Optional[array_like]
+ orientation of the boundary. Optional if orientation was already
+ passed when creating the BC_RANS class instance.
+ vof_air: Optional[float]
+ VOF value of air (default is 1.)
+ """
+ self.BC_type = 'Atmosphere'
+ if orientation is None and self._b_or is not None:
+ orientation = self._b_or
+ assert orientation is not None, 'oritentation must be set for BC'
+ self.reset()
+ self.p_dirichlet.setConstantBC(0.)
+ self.pInc_dirichlet.setConstantBC(0.)
+ self.pInit_dirichlet.setConstantBC(0.)
+ self.vof_dirichlet.setConstantBC(vof_air) # air
+ self.vos_dirichlet.setConstantBC(0.)
+ self.u_dirichlet.setConstantBC(0.)
+ self.v_dirichlet.setConstantBC(0.)
+ self.w_dirichlet.setConstantBC(0.)
+ self.us_dirichlet.setConstantBC(0.)
+ self.vs_dirichlet.setConstantBC(0.)
+ self.ws_dirichlet.setConstantBC(0.)
+ self.k_dirichlet.setConstantBC(1e-20)
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_dirichlet.setConstantBC(1e-10)
+ self.dissipation_diffusive.setConstantBC(0.)
+
+ if orientation[0] == 1. or orientation[0] == -1.:
+ self.u_diffusive.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ if orientation[1] == 1. or orientation[1] == -1.:
+ self.v_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+ if orientation[2] == 1. or orientation[2] == -1.:
+ self.w_diffusive.setConstantBC(0.)
+ self.ws_diffusive.setConstantBC(0.)
+
+ if kInflow is not None:
+ self.k_dirichlet.setConstantBC(kInflow)
+ else:
+ logEvent("WARNING: Dirichlet condition for k in "+str(self.BC_type)+" has not been set. Ignore if RANS is not used")
+ if dInflow is not None:
+ self.dissipation_dirichlet.setConstantBC(dInflow)
+ else:
+ logEvent("WARNING: Dirichlet condition for dissipation in "+str(self.BC_type)+" has not been set. Ignore if RANS is not used")
+ def setRigidBodyMoveMesh(self, body):
+ """
+ Sets boundary conditions for moving the mesh with a rigid body
+
+ Parameters
+ ----------
+ last_pos: array_like
+ last position of rigig body
+ h: array_like
+ displacement of the body
+ rot_matrix:
+ rotation matrix describing displament due to rotation between last
+ position and new position (3x3 array)
+
+ (!) if set manually, the input arrays should be updated externally
+ without loosing their memory address
+ """
+ def get_DBC_h(i):
+ def DBC_h(x, t, n=None):
+ x_0 = x - body.last_position
+ new_x_0 = np.dot(x_0, body.rotation_matrix)
+ hx = new_x_0 - x_0 + body.h
+ return hx[i]
+ return DBC_h
+ self.hx_dirichlet.uOfXT = get_DBC_h(0)
+ self.hy_dirichlet.uOfXT = get_DBC_h(1)
+ if body.nd > 2:
+ self.hz_dirichlet.uOfXT = get_DBC_h(2)
+
+ def setChMoveMesh(self, body):
+ self.hx_dirichlet.uOfXT = lambda x, t, n=None: body.hx(x, t)
+ self.hy_dirichlet.uOfXT = lambda x, t, n=None: body.hy(x, t)
+ self.hz_dirichlet.uOfXT = lambda x, t, n=None: body.hz(x, t)
+
+ def setTurbulentDirichlet(self, kVal, dissipationVal):
+ """
+ Sets only dirichlet conditions for turbulence at the boundary.
+ It's a rough approximation for evalueting the near wall turbulence
+ based on empirical assumptions.
+ More sophisticated wall functions are recommended to be used.
+
+ Parameters
+ ----------
+ kVal: float.
+ constant value applied on k.
+ dissipationVal: float.
+ constant value applied on dissipation.
+ """
+ # turbulent boundary conditions
+ self.k_dirichlet.setConstantBC(kVal)
+ self.dissipation_dirichlet.setConstantBC(dissipationVal)
+ self.k_advective.resetBC()
+ self.dissipation_advective.resetBC()
+ self.k_diffusive.resetBC()
+ self.dissipation_diffusive.resetBC()
+
+ def setTurbulentZeroGradient(self):
+ """
+ Sets only zero-gradient conditions for turbulence at the boundary.
+ More sophisticated wall functions are recommended to be used.
+ """
+ # turbulent boundary conditions
+ self.k_dirichlet.setConstantBC(0.)
+ self.dissipation_dirichlet.setConstantBC(0.)
+ self.k_advective.resetBC()
+ self.dissipation_advective.resetBC()
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+
+ def setWallFunction(self, wall, shearStress=False):
+ """
+ Sets turbulent boundaries for wall treatment.
+ Calculation made on nodes outside the viscous sublayer and based
+ on assumption on the velocity profile close to the wall in order to
+ impose the wall shear stress.
+
+ Parameters
+ ----------
+ wall: wall object.
+ BoundaryConditions class to be attached for setting up
+ all the turbulent parameters.
+ shearStress: True/False.
+ At the moment version with shearStress=False is the only one that
+ returns good results.
+ Keep it False at the moment!
+
+ - When True, the wall function prescribes diffusive boundaries
+ for velocity and kappa. It's like imposing the shear stress.
+ - If False, the wall function prescribes dirichlet conditions.
+ """
+ wf = wall
+ self.reset()
+ self.setNoSlip()
+ self.BC_type = "Wall function"
+ self.dissipation_diffusive.resetBC()
+ self.k_dirichlet.uOfXT = lambda x, t, n=None: wf.get_k_dirichlet(x, t, n)
+ self.dissipation_dirichlet.uOfXT = lambda x, t, n=None: wf.get_dissipation_dirichlet(x, t ,n)
+ self.u_dirichlet.uOfXT = lambda x, t, n=None: wf.get_u_dirichlet(x, t ,n)
+ self.v_dirichlet.uOfXT = lambda x, t, n=None: wf.get_v_dirichlet(x, t ,n)
+ self.w_dirichlet.uOfXT = lambda x, t, n=None: wf.get_w_dirichlet(x, t ,n)
+ """
+ self.dissipation_dirichlet.uOfXT = lambda x, t: wf.get_dissipation_dirichlet(x, t)
+ self.vof_advective.setConstantBC(0.)
+ self.p_advective.setConstantBC(0.)
+ if shearStress:
+ #self.k_dirichlet.uOfXT = lambda x, t: wf.get_k_dirichlet(x, t)
+ self.k_advective.setConstantBC(0.)
+ self.u_diffusive.uOfXT = lambda x, t: wf.get_u_diffusive(x, t)
+ self.v_diffusive.uOfXT = lambda x, t: wf.get_v_diffusive(x, t)
+ self.w_diffusive.uOfXT = lambda x, t: wf.get_w_diffusive(x, t)
+ self.k_diffusive.setConstantBC(0.)
+ else:
+ self.u_dirichlet.uOfXT = lambda x, t: wf.get_u_dirichlet(x, t)
+ self.v_dirichlet.uOfXT = lambda x, t: wf.get_v_dirichlet(x, t)
+ self.w_dirichlet.uOfXT = lambda x, t: wf.get_w_dirichlet(x, t)
+ self.k_dirichlet.uOfXT = lambda x, t: wf.get_k_dirichlet(x, t)
+ """
+ def setMoveMesh(self, last_pos, h=(0., 0., 0.), rot_matrix=None):
+ """
+ Sets boundary conditions for moving the mesh with a rigid body
+
+ Parameters
+ ----------
+ last_pos: array_like
+ last position of rigig body
+ h: array_like
+ displacement of the body
+ rot_matrix:
+ rotation matrix describing displament due to rotation between last
+ position and new position (3x3 array)
+
+ (!) if set manually, the input arrays should be updated externally
+ without loosing their memory address
+ """
+ if rot_matrix is None:
+ rot_matrix = np.array([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]])
+ self.body_python_rot_matrix = rot_matrix
+ self.body_python_last_pos = last_pos
+ self.body_python_h = h
+ self.hx_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hx(x, t)
+ self.hy_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hy(x, t)
+ self.hz_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hz(x, t)
+
+ def __cpp_MoveMesh_h(self, x, t):
+ cython.declare(x_0=cython.double[3])
+ cython.declare(new_x_0=cython.double[3])
+ hx = np.zeros(3)
+ x_0[0] = x[0] - self.body_python_last_pos[0]
+ x_0[1] = x[1] - self.body_python_last_pos[1]
+ x_0[2] = x[2] - self.body_python_last_pos[2]
+ new_x_0 = np.dot(x_0, self.body_python_rot_matrix)
+ hx[0] = new_x_0[0] - x_0[0] + self.body_python_h[0]
+ hx[1] = new_x_0[1] - x_0[1] + self.body_python_h[1]
+ hx[2] = new_x_0[2] - x_0[2] + self.body_python_h[2]
+ return hx
+
+ def __cpp_MoveMesh_hx(self, x, t):
+ return self.__cpp_MoveMesh_h(x, t)[0]
+
+ def __cpp_MoveMesh_hy(self, x, t):
+ return self.__cpp_MoveMesh_h(x, t)[1]
+
+ def __cpp_MoveMesh_hz(self, x, t):
+ return self.__cpp_MoveMesh_h(x, t)[2]
+
+ def setUnsteadyTwoPhaseVelocityInlet(self, wave, smoothing, vert_axis=None,orientation=None,
+ wind_speed=None, vof_air=1., vof_water=0.,kInflow=1e-30, dInflow = 1e-10):
+ """
+ Imposes a velocity profile on the fluid with input wave and wind
+ conditions.
+
+ Parameters
+ ----------
+ wave: proteus.WaveTools
+ class describing a wave (from proteus.WaveTools)
+ smoothing: float
+ smoothing distance (typically 3.*he)
+ vert_axis: Optional[int]
+ index of vertical position vector (x:0, y:1, z:2), must always be
+ aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
+ wind_speed: Optional[array_like]
+ speed of air phase
+ vof_air: Optional[float]
+ VOF value of air (default is 1.)
+ vof_water: Optional[float]
+ VOF value of water (default is 0.)
+
+ Below the sea water level: fluid velocity to wave speed.
+ Above the sea water level: fluid velocity set to wind speed
+ (with smoothing).
+ """
+ self.reset()
+ if vert_axis is None:
+ vert_axis = self.nd - 1
+ if wind_speed is None:
+ wind_speed = np.zeros(3)
+ if orientation is not None:
+ b_or = orientation
+ else:
+ b_or=self._b_or
+ assert b_or is not None, "ERROR: Boundary orientation for Unsteady flow inlet is not defined"
+ self.waves = __cppClass_WavesCharacteristics(waves=wave, vert_axis=vert_axis, b_or=b_or,
+ wind_speed=wind_speed, smoothing=smoothing, vof_water=vof_water, vof_air=vof_air)
+
+ self.u_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(x, t)
+ self.v_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(x, t)
+ self.w_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(x, t)
+ self.phi_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(x, t)
+ self.vof_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(x, t)
+ self.p_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)
+ self.pInc_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)
+
+ self.pInc_diffusive.setConstantBC(0.0)
+ self.pInit_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)#setConstantBC(0.0)
+ self.vos_dirichlet.setConstantBC(0.0)
+ self.us_dirichlet.setConstantBC(0.0)
+ self.vs_dirichlet.setConstantBC(0.0)
+ self.ws_dirichlet.setConstantBC(0.0)
+ self.k_dirichlet.setConstantBC(kInflow)
+ self.dissipation_dirichlet.setConstantBC(dInflow)
+ self.dissipation_diffusive.setConstantBC(0.)
+ self.k_diffusive.setConstantBC(0.0)
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_velocity(xx, t)[0]
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_velocity(xx, t)[1]
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_velocity(xx, t)[2]
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_pressure(xx, t)
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_phi(xx, t)
+
+ def __cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return self.waves.__cpp_calculate_vof(xx, t)
+
+ def setTwoPhaseVelocityInlet(self, U, waterLevel, smoothing, Uwind=None,
+ vert_axis=None, air=1., water=0.,
+ kInflow=None, dissipationInflow=None,
+ kInflowAir=None, dissipationInflowAir=None):
+ """
+ Imposes a velocity profile lower than the sea level and an open
+ boundary for higher than the sealevel.
+
+ Parameters
+ ----------
+ U: list.
+ Velocity vector at the global system.
+ Uwind: list.
+ Air velocity vector at the global system.
+ waterLevel: float.
+ water level at global coordinate system.
+ smoothing: float.
+ range within smoothing function is valid.
+ [3.0 times mesh element size can be a good value]
+ vert_axis: optional.
+ index of vertical in position vector, must always be
+ aligned with gravity, by default set to 1].
+ air: optional.
+ Volume fraction for air (1.0 by default).
+ water: optional.
+ Volume fraction for water (0.0 by default).
+ kInflow: float (optional).
+ K inflow value for turbulent model imposed at the boundary.
+ dissipationInflow: float (optional).
+ Dissipation inflow value for turbulent model imposed at the boundary.
+ kInflowAir: float (optional).
+ Air K inflow value for turbulent model imposed at the boundary.
+ dissipationInflowAir: float (optional).
+ Air dissipation inflow value for turbulent model imposed at the boundary.
+
+ Notes
+ -----
+ Below the seawater level, the condition returns the _dirichlet and
+ p_advective condition according to the inflow velocity.
+ Above the sea water level, the condition returns the gravity as zero,
+ and sets _dirichlet condition to zero, only if there is a zero inflow
+ velocity component.
+ (!) This condition is best used for boundaries and gravity aligned with
+ one of the main axes.
+ """
+ self.reset()
+ self.BC_type = 'TwoPhaseVelocityInlet'
+
+ if vert_axis is None:
+ vert_axis = self.nd - 1
+ if Uwind is None:
+ Uwind = np.zeros(3)
+
+ U = np.array(U)
+ Uwind = np.array(Uwind)
+
+ def get_inlet_ux_dirichlet(i):
+ def ux_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - waterLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ u = H * Uwind[i] + (1 - H) * U[i]
+ return u
+ return ux_dirichlet
+
+ def inlet_phi_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - waterLevel
+ return phi
+
+ def inlet_vof_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - waterLevel
+ if phi >= smoothing:
+ H = 1.
+ elif smoothing > 0 and -smoothing < phi < smoothing:
+ H = smoothedHeaviside(smoothing, phi)
+ elif phi <= -smoothing:
+ H = 0.
+ vof = H * air + (1 - H) * water
+ return vof
+
+ def inlet_p_advective(x, t, n=None):
+ b_or = self._b_or
+ phi = x[vert_axis] - waterLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ u = H * Uwind + (1 - H) * U
+ # This is the normal velocity, based on the inwards boundary
+ # orientation -b_or
+ u_p = np.sum(u * np.abs(b_or))
+ return -u_p
+
+ def inlet_k_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - waterLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ return H * kInflowAir + (1 - H) * kInflow
+
+ def inlet_dissipation_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - waterLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ return H * dissipationInflowAir + (1 - H) * dissipationInflow
+
+ self.u_dirichlet.uOfXT = get_inlet_ux_dirichlet(0)
+ self.v_dirichlet.uOfXT = get_inlet_ux_dirichlet(1)
+ self.w_dirichlet.uOfXT = get_inlet_ux_dirichlet(2)
+ self.phi_dirichlet.uOfXT = inlet_phi_dirichlet
+ self.vof_dirichlet.uOfXT = inlet_vof_dirichlet
+ self.p_advective.uOfXT = inlet_p_advective
+ if kInflow is not None:
+ self.k_dirichlet.uOfXT = inlet_k_dirichlet
+ self.k_advective.resetBC()
+ self.k_diffusive.resetBC()
+ if dissipationInflow is not None:
+ self.dissipation_dirichlet.uOfXT = inlet_dissipation_dirichlet
+ self.dissipation_advective.resetBC()
+ self.dissipation_diffusive.resetBC()
+
+ def setHydrostaticPressureOutletWithDepth(self, seaLevel, rhoUp, rhoDown, g,
+ refLevel, smoothing, orientation=None,U=None, Uwind=None,
+ pRef=0.0, vert_axis=None,
+ air=1.0, water=0.0,
+ kInflow=None, dissipationInflow=None,
+ kInflowAir=None, dissipationInflowAir=None):
+ """
+ Returns the pressure and vof profile based on the known depth.
+ If the boundary is aligned with one of the main axes, sets the tangential
+ velocity components to zero as well.
+ (!) This condition is best used for boundaries and gravity aligned with
+ one of the main axes.
+
+ Parameters
+ ----------
+ rhoUp: Phase density of the upper part.
+ rhoDown: Phase density of the lower part.
+ g: Gravitational acceleration vector.
+ refLevel: Level at which pressure = pRef.
+ pRef: Reference value for the pressure at x[vert_axis]=refLevel, by default set to 0.
+ vert_axis: index of vertical in position vector, must always be aligned with gravity, by default set to 1.
+ """
+ self.reset()
+
+ if vert_axis is None:
+ vert_axis = self.nd - 1
+
+ def hydrostaticPressureOutletWithDepth_p_dirichlet(x, t , n=None):
+ p_top = pRef
+ phi_top = refLevel - seaLevel
+ phi = x[vert_axis] - seaLevel
+ return p_top - g[vert_axis] * (rhoDown * (phi_top - phi) +
+ (rhoUp - rhoDown) *
+ (smoothedHeaviside_integral(smoothing, phi_top)
+ -
+ smoothedHeaviside_integral(smoothing, phi)))
+
+ def hydrostaticPressureOutletWithDepth_phi_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - seaLevel
+ return phi
+
+ def hydrostaticPressureOutletWithDepth_vof_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - seaLevel
+ if phi >= smoothing:
+ H = 1.
+ elif smoothing > 0 and -smoothing < phi < smoothing:
+ H = smoothedHeaviside(smoothing, phi)
+ elif phi <= -smoothing:
+ H = 0.
+ return H * air + (1 - H) * water
+
+ def inlet_k_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - seaLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ return H * kInflowAir + (1 - H) * kInflow
+
+ def inlet_dissipation_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - seaLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ return H * dissipationInflowAir + (1 - H) * dissipationInflow
+
+ if orientation is not None:
+ b_or = orientation
+ else:
+ b_or=self._b_or
+ assert b_or is not None, "ERROR: Boundary orientation for Hydrostatic flow outlet is not defined"
+ if b_or[0] == 1. or b_or[0] == -1.:
+ self.v_dirichlet.setConstantBC(0.)
+ self.w_dirichlet.setConstantBC(0.)
+ self.u_diffusive.setConstantBC(0.)
+ if b_or[1] == 1. or b_or[1] == -1.:
+ self.u_dirichlet.setConstantBC(0.)
+ self.w_dirichlet.setConstantBC(0.)
+ self.v_diffusive.setConstantBC(0.)
+ if b_or[2] == 1. or b_or[2] == -1.:
+ self.u_dirichlet.setConstantBC(0.)
+ self.v_dirichlet.setConstantBC(0.)
+ self.w_diffusive.setConstantBC(0.)
+#sediment
+ self.us_advective.setConstantBC(0.)
+ self.vs_advective.setConstantBC(0.)
+ self.ws_advective.setConstantBC(0.)
+ self.vos_advective.setConstantBC(0.)
+ self.us_diffusive.setConstantBC(0.)
+ self.vs_diffusive.setConstantBC(0.)
+#end sediment
+ self.p_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_p_dirichlet
+ self.pInit_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_p_dirichlet
+ self.pInc_dirichlet.setConstantBC(0.)
+ self.phi_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_phi_dirichlet
+ self.vof_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_vof_dirichlet
+ self.k_diffusive.setConstantBC(0.)
+ self.dissipation_diffusive.setConstantBC(0.)
+ if U is not None:
+ def get_inlet_ux_dirichlet(i):
+ def ux_dirichlet(x, t, n=None):
+ phi = x[vert_axis] - seaLevel
+ if phi <= 0.:
+ H = 0.0
+ elif 0 < phi <= smoothing:
+ H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
+ else:
+ H = 1.0
+ return H * Uwind[i] + (1 - H) * U[i]
+ return ux_dirichlet
+
+ if Uwind is None:
+ Uwind = np.zeros(3)
+ U = np.array(U)
+ Uwind = np.array(Uwind)
+ self.u_dirichlet.uOfXT = get_inlet_ux_dirichlet(0)
+ self.v_dirichlet.uOfXT = get_inlet_ux_dirichlet(1)
+ self.w_dirichlet.uOfXT = get_inlet_ux_dirichlet(2)
+ self.u_diffusive.resetBC()
+
+ if kInflow is not None:
+ self.k_dirichlet.uOfXT = inlet_k_dirichlet
+ self.k_advective.resetBC()
+ self.k_diffusive.resetBC()
+ if dissipationInflow is not None:
+ self.dissipation_dirichlet.uOfXT = inlet_dissipation_dirichlet
+ self.dissipation_advective.resetBC()
+ self.dissipation_diffusive.resetBC()
+
+# for regions
+
+class RelaxationZone:
+ """
+ Holds information about a relaxation zone (wave generation/absorption
+ or porous zone)
+
+ Parameters
+ ----------
+ zone_type: string
+ type of zone, can be set to 'absorption', 'generation', or 'porous'
+ center: array_like
+ coordinates of center of the zone
+ orientation: array_like
+ orientation for absorption/generation zones: from boundary to tank
+ epsFact_porous: float
+ half the zone length
+ waves: Optional[proteus.WaveTools]
+ class instance of a wave from proteus.WaveTools (must be set for
+ generation zone)
+ shape: Optional[proteus.SpatialTools.Shape]
+ shape class instance containing region
+ dragAlpha: Optional[float]
+ parameter for porous zones (default: 0.5/1.005e-6)
+ dragBeta: Optional[float]
+ parameter for porous zones (default: 0.)
+ porosity: Optional[float]
+ parameter for porous zone (default: 1.)
+ vert_axis: Optional[int]
+ index of vertical position vector (x:0, y:1, z:2), must always be
+ aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
+ smoothing: Optional[float]
+ smoothing distance from the free surface (usually 3*he)
+ vof_water: Optional[int]
+ VOF value of water (default: 0)
+ vof_air: Optional[int]
+ VOF value of air (default: 1)
+ """
+
+ def __cinit__(self, zone_type, center, orientation, epsFact_porous,
+ waves=None, shape=None, wind_speed=np.array([0., 0., 0.]),
+ dragAlpha=0.5/1.005e-6, dragBeta=0., porosity=1., vert_axis=None, smoothing=0.,
+ vof_water=0., vof_air=1.):
+ self.Shape = shape
+ self.nd = self.Shape.Domain.nd
+ self.zone_type = zone_type
+ self.center = center
+ self.orientation = orientation
+ if vert_axis is None:
+ vert_axis = self.Shape.Domain.nd - 1
+ self.vert_axis = vert_axis
+ if waves is not None:
+ self.waves = __cppClass_WavesCharacteristics(waves=waves, wind_speed=wind_speed, vert_axis=vert_axis,
+ smoothing=smoothing, vof_water=vof_water, vof_air=vof_air)
+ self.epsFact_porous = epsFact_porous
+ self.dragAlpha = dragAlpha
+ self.dragBeta = dragBeta
+ self.porosity = porosity
+ self.zero_vel = np.zeros(3)
+
+ def calculate_init(self):
+ if self.zone_type == 'generation':
+ # self.u = &self.waves.u
+ # self.eta = &self.waves.eta
+ self.uu = self.__cpp_calculate_vel_wave
+ self.phi = self.__cpp_calculate_phi_porous_sponge
+ elif self.zone_type == 'absorption':
+ self.uu = self.__cpp_calculate_vel_zero
+ self.phi = self.__cpp_calculate_phi_porous_sponge
+ elif self.zone_type == 'porous':
+ self.uu = self.__cpp_calculate_vel_zero
+ self.phi = self.__cpp_calculate_phi_porous
+
+ def calculate_phi(self, x):
+ return self.phi(self, x)
+
+ def __cpp_calculate_phi_porous_sponge(self, x):
+ """
+ Used for RelaxationZone only
+ """
+ cython.declare(d=cython.double[3], o=cython.double[3])
+ d[0] = self.center[0] - x[0]
+ d[1] = self.center[1] - x[1]
+ o[0] = self.orientation[0]
+ o[1] = self.orientation[1]
+ if self.nd > 2:
+ d[2] = self.center[2] - x[2]
+ o[2] = self.orientation[2]
+ else:
+ d[2] = 0
+ o[2] = 0
+ phi = o[0] * d[0] + o[1] * d[1] + o[2] * d[2]
+ return phi
+
+ def __cpp_calculate_phi_porous(self, x):
+ IN_POROUS_ZONE=-10000.0
+ return IN_POROUS_ZONE
+
+ def calculate_vel(self, x, t):
+ cython.declare(d=cython.double[3], o=cython.double[3])
+ d[0] = x[0]
+ d[1] = x[1]
+ d[2] = x[2]
+ return self.uu(self, d, t)
+
+ def calculate_phi_python(self, x):
+ cython.declare(xx=cython.double[3], tt=cython.double)
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ ph = self.phi(self, xx)
+ return ph
+
+ def calculate_vel_python(self, x, t, n=None):
+ cython.declare(xx=cython.double[3], tt=cython.double)
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ tt = t
+ return self.uu(self, xx, tt)
+
+ def __cpp_calculate_vel_zero(self, x, t):
+ return self.zero_vel
+
+ def __cpp_calculate_vel_wave(self, x, t):
+ return self.waves.__cpp_calculate_velocity(x, t)
+
+
+class RelaxationZoneWaveGenerator:
+ """
+ Prescribe a velocity penalty scaling in a material zone via a
+ Darcy-Forchheimer penalty
+
+ Parameters
+ ----------
+ zones: dict
+ dictionary with key as the region flag and values as a RelaxationZone
+ class
+ nd: int
+ number of dimensions of domain
+ """
+
+ def __init__(self, zones, nd):
+ self.zones = zones
+ self.nd = nd
+
+ def attachModel(self, model, ar):
+ self.model = model
+ self.ar = ar
+ return self
+
+ def attachAuxiliaryVariables(self, avDict):
+ pass
+
+ def calculate_init(self):
+ max_key = 0
+ for key, zone in list(self.zones.items()):
+ zone.calculate_init()
+ if key > max_key:
+ max_key = key
+ self.max_flag = max_key
+ self.zones_array = np.empty(self.max_flag + 1, dtype=RelaxationZone)
+ for key, zone in list(self.zones.items()):
+ self.zones_array[key] = zone
+
+ def calculate(self):
+ self.__cpp_iterate()
+
+ def __cpp_iterate(self):
+ nl = len(self.model.levelModelList)
+ for l in range(nl): # usually only 1
+ # initialisation of variables before costly loop
+ m = self.model.levelModelList[l]
+ nE = m.coefficients.q_phi.shape[0]
+ nk = m.coefficients.q_phi.shape[1]
+ t = m.timeIntegration.t
+ qx = m.q['x']
+ q_phi_porous = m.coefficients.q_phi_porous
+ q_velocity_porous = m.coefficients.q_velocity_porous
+ mTypes = m.mesh.elementMaterialTypes
+ # costly loop
+ for eN in range(nE):
+ mType = mTypes[eN]
+ if mType <= self.max_flag:
+ zone = self.zones_array[mType]
+ if zone is not None:
+ for k in range(nk):
+ x[0] = qx[eN, k, 0]
+ x[1] = qx[eN, k, 1]
+ x[2] = qx[eN, k, 2]
+ phi = zone.calculate_phi(x)
+ q_phi_porous[eN, k] = phi
+ u = zone.calculate_vel(x, t)
+ q_velocity_porous[eN, k, 0] = u[0]
+ q_velocity_porous[eN, k, 1] = u[1]
+ if self.nd > 2:
+ q_velocity_porous[eN, k, 2] = u[2]
+ m.q['phi_porous'] = q_phi_porous
+ m.q['velocity_porous'] = q_velocity_porous
+
+
+class __cppClass_WavesCharacteristics:
+ """
+ Class holding information from WaveTools waves and cnvering it to
+ boundary conditions to use for relaxation zones and wave inlet.
+ This class is created automatically when passing WaveTools class
+ instances to a relaxation zone or wave inlet BC.
+
+ Parameters
+ ----------
+ wave: proteus.WaveTools
+ class describing a wave (from proteus.WaveTools)
+ vert_axis: int
+ index of vertical position vector (x:0, y:1, z:2), must always be
+ aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
+ wind_speed: Optional[array_like]
+ speed of air phase
+ b_or: Optional[array_like]
+ boundary orientation. Necessary for pressure calculations. Used
+ for boundary conditions but not in relaxation zones.
+ smoothing: Optional[float]
+ smoothing distance from the free surface (usually 3*he)
+ vof_water: Optional[float]
+ VOF value of water (default: 0)
+ vof_air: Optional[float]
+ VOF value of air (default: 1)
+ """
+
+ def __init__(self, waves, vert_axis, wind_speed=None, b_or=None,
+ smoothing=0., vof_water=0., vof_air=1.):
+ self.WT = waves # wavetools wave
+ self.vert_axis = vert_axis
+ self.zero_vel = np.zeros(3)
+ self._b_or = b_or
+ self.smoothing = smoothing
+ self.vof_air = vof_air
+ self.vof_water = vof_water
+ if wind_speed is None:
+ self.wind_speed = self.zero_vel
+ else:
+ self.wind_speed = wind_speed
+
+ def __cpp_calculate_velocity(self, x, t):
+ # u is returned as a memoryview (pxd: cdef double[:]); a C array declared here lives on this
+ # function's stack and the view dangles once it returns. Unnoticed until the module was built
+ # with line tracing, which reuses that stack: the caller then read 0.0.
+ u = np.empty(3)
+ cython.declare(xx=cython.double[3])
+ cython.declare(x_max=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ phi = self.__cpp_calculate_phi(x, t)
+ if phi <= 0.:
+ # no smoothing below mwl, or wave peak could get chopped off
+ H = 0
+ waterSpeed = self.WT.u(xx, t)
+ elif 0 < phi <= self.smoothing:
+ # smoothing on half the range of VOF (above wave crest)
+ H = smoothedHeaviside(self.smoothing/2., phi - self.smoothing/2.)
+ # use max velocity of wave for water
+ x_max[0] = x[0]
+ x_max[1] = x[1]
+ x_max[2] = x[2]
+ x_max[self.vert_axis] = x[self.vert_axis] - phi
+ waterSpeed = self.WT.u(x_max, t)
+ else:
+ H = 1.
+ waterSpeed = self.zero_vel
+ u[0] = H * self.wind_speed[0] + (1 - H) * waterSpeed[0]
+ u[1] = H * self.wind_speed[1] + (1 - H) * waterSpeed[1]
+ u[2] = H * self.wind_speed[2] + (1 - H) * waterSpeed[2]
+ return u
+
+ def __cpp_calculate_pressure(self, x, t):
+ # This is the normal velocity, based on the outwards boundary
+ # orientation b_or
+ # needs to be equal to -ux_dirichlet
+ ux = self.__cpp_calculate_velocity(x, t)
+ b0, b1, b2 = self._b_or[0], self._b_or[1], self._b_or[2]
+ u0, u1, u2 = ux[0], ux[1], ux[2]
+ return b0 * u0 + b1 * u1 + b2 * u2
+
+ def __cpp_calculate_phi(self, x, t):
+ cython.declare(xx=cython.double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ level = self.WT.mwl + self.WT.eta(xx, t)
+ return x[self.vert_axis] - level
+
+ def __cpp_calculate_vof(self, x, t):
+ phi = self.__cpp_calculate_phi(x, t)
+ H = self.__cpp_calculate_smoothing_H(phi)
+ return H
+
+ def __cpp_calculate_smoothing_H(self, phi):
+ if phi >= self.smoothing:
+ H = 1.
+ elif self.smoothing > 0 and -self.smoothing < phi < self.smoothing:
+ H = smoothedHeaviside(self.smoothing, phi)
+ elif phi <= -self.smoothing:
+ H = 0.
+ return H
+
+
+def __x_to_cpp(x):
+ cython.declare(xx=double[3])
+ xx[0] = x[0]
+ xx[1] = x[1]
+ xx[2] = x[2]
+ return xx
+
+
+class WallFunctions(AuxiliaryVariables.AV_base):
+ """
+ Auxiliary variable used to calculate attributes of an associated shape
+ class instance acting as a wall.
+ """
+
+ def __init__(self, turbModel, kWall, Y, Yplus, U0, nu=1.004e-6, Cmu=0.09, K=0.41, B=5.57):
+ """
+ Sets turbulent boundaries for wall treatment.
+ Calculation made on nodes outside the viscous sublayer and based
+ on assumption on the velocity profile close to the wall in order to
+ impose the wall shear stress.
+
+ - k is assumed to be constant in the fully turbulent region close to the wall,
+ in this way kv = kp.
+ - dissipation is calculated.
+
+ Parameters
+ ----------
+ turbModel: string.
+ 'ke' or 'kw', for switching between k-epsilon or k-omega models.
+ kWall: object.
+ Class kWall object for extracting kappa from the model.
+ Y: float.
+ size of the nearest element to the boundary.
+ Yplus: float.
+ size of the nearest element to the boundary in terms of wall unit.
+ U0: array_like.
+ stream velocity.
+ nu: float.
+ fluid viscosity.
+ Cmu: float.
+ turbulent viscosity constant.
+ K: float.
+ von Karman coefficient.
+ B: float.
+ roughness coefficient for walls.
+ """
+ self.turbModel = turbModel
+ self.Y = Y
+ self.Yplus = Yplus
+ self.U0 = U0
+ self.nu = nu
+ self.Cmu = Cmu
+ self.K = K
+ self.B = B
+ # initialise variables
+ self.Ubound = np.zeros(3)
+ self.kappa = 1e-10
+ self.tau_rho = 0.
+ self.utAbs = 1e-10
+ self.ut = np.zeros(3)
+ self.x = np.zeros(3)
+ self.t = 0.
+ self.model = None
+ self.xi, self.element, self.rank = None, None, None
+ self.kWall = kWall
+
+ def attachModel(self, model, ar):
+ """
+ Attaches model to auxiliary variable
+ """
+ self.model = model
+ self.ar = ar
+ self.nd = model.levelModelList[0].nSpace_global
+ self.Closure_0_model = model.levelModelList[0].coefficients.Closure_0_model
+ self.Closure_1_model = model.levelModelList[0].coefficients.Closure_1_model
+ return self
+
+ def attachAuxiliaryVariables(self, avDict):
+ pass
+
+ def calculate_init(self):
+ pass
+
+ def calculate(self):
+ pass
+
+ def getLocalNearestNode(self, coords, kdtree):
+ """
+ Finds nearest node to coordinates (local)
+ Parameters
+ ----------
+ coords: array_like
+ coordinates from which to find nearest node
+ kdtree: scipy.spatial.cKDTree
+ instance of scipy kdtree
+ Returns
+ -------
+ node: int
+ nearest node index
+ distance: float
+ distance to nearest node
+ """
+ # determine local nearest node distance
+ distance, node = kdtree.query(coords)
+ return node, distance
+
+ def getLocalElement(self, femSpace, coords, node):
+ """
+ Given coordinates and its nearest node, determine if it is on a
+ local element.
+ Parameters
+ ----------
+ femSpace: object
+ finite element space
+ coords: array_like
+ coordinates from which to element
+ node: int
+ nearest node index
+ Returns
+ -------
+ eN: int or None
+ local index of element (None if not found)
+ """
+ patchBoundaryNodes = set()
+ checkedElements = []
+ # nodeElementOffsets give the indices to get the elements sharing the node
+ statem1 = node + 1 < len(femSpace.mesh.nodeElementOffsets)
+ for eOffset in range(femSpace.mesh.nodeElementOffsets[node], femSpace.mesh.nodeElementOffsets[node + 1]):
+ eN = femSpace.mesh.nodeElementsArray[eOffset]
+ checkedElements.append(eN)
+ # union of set
+ patchBoundaryNodes |= set(femSpace.mesh.elementNodesArray[eN])
+ # evaluate the inverse map for element eN (global to local)
+ xi = femSpace.elementMaps.getInverseValue(eN, coords)
+ #J = femSpace.elementMaps.getJacobianValues(eN, )
+ # query whether xi lies within the reference element
+ if femSpace.elementMaps.referenceElement.onElement(xi):
+ return eN
+ # extra loop if case coords is in neighbour element
+ for node in patchBoundaryNodes:
+ for eOffset in range(femSpace.mesh.nodeElementOffsets[node], femSpace.mesh.nodeElementOffsets[node + 1]):
+ eN = femSpace.mesh.nodeElementsArray[eOffset]
+ if eN not in checkedElements:
+ checkedElements.append(eN)
+ # evaluate the inverse map for element eN
+ xi = femSpace.elementMaps.getInverseValue(eN, coords)
+ # query whether xi lies within the reference element
+ if femSpace.elementMaps.referenceElement.onElement(xi):
+ return eN
+ # no elements found
+ return None
+
+ def findElementContainingCoords(self, coords):
+ """
+ Given global coordinates of a point, returns
+ local coordinates and the owner of the point.
+
+ Parameters
+ ----------
+ coords: array_like
+ global coordinates to look for
+ Returns
+ -------
+ xi:
+ local coordinates
+ eN: int
+ (local) element number
+ rank: int
+ processor rank containing element
+ """
+ comm = Comm.get().comm.tompi4py()
+ xi = owning_proc = element = rank = None # initialised as None
+ self.xi, self.element, self.rank = xi, element, rank
+ # get nearest node on each processor
+ # comm.barrier()
+ self.u = self.model.levelModelList[0].u
+ self.femSpace_velocity = self.u[1].femSpace
+ nodes_kdtree = spatial.cKDTree(self.model.levelModelList[0].mesh.nodeArray)
+ nearest_node, nearest_node_distance = self.getLocalNearestNode(coords, nodes_kdtree)
+ # look for element containing coords on each processor (if it exists)
+ local_element = self.getLocalElement(self.femSpace_velocity, coords, nearest_node)
+ if local_element:
+ xi = self.femSpace_velocity.elementMaps.getInverseValue(local_element, coords)
+ rank = comm.rank
+ else:
+ xi = None
+ rank = None
+ #rank = comm.allreduce(rank, op=MPI.MAX)
+ return xi, local_element, rank
+
+ def getFluidVelocityLocalCoords(self, xi, element, rank):
+ """
+ Given local details, returns velocity field at those coordinates.
+
+ Parameters
+ ----------
+ xi:
+ local coords in element
+ element: int
+ element number (local to processor 'rank')
+ rank: int
+ rank of processor owning the element
+ """
+ comm = Comm.get().comm.tompi4py()
+ if comm.rank == rank:
+ u = self.u[1].getValue(element, xi)
+ v = self.u[2].getValue(element, xi)
+ if self.nd > 2:
+ w = self.u[3].getValue(element, xi)
+ if self.nd <= 2:
+ w = 0.
+ else:
+ u = v = w = None
+ return u, v, w
+
+ def setYplusNormalDirection(self, x, t,n, relax=1.0):
+ """
+ Return the point at y+ distance in normal
+ direction from the boundary.
+ """
+ # near wall point
+ if len(n) < 3:
+ nP = (relax * self.Y * (-n[:2])) + x[:2]
+ else:
+ nP = (relax * self.Y * (-n)) + x
+ return nP
+
+ def extractVelocity(self, x, t, n):
+ """
+ Extraction of the velocity at y+ distance from the boundary.
+ """
+ coords = self.setYplusNormalDirection(x, t, n)
+ xi, element, rank = self.findElementContainingCoords(coords)
+ if rank is not None:
+ u, v, w = self.getFluidVelocityLocalCoords(xi, element, rank)
+ else:
+ relax = 0.5
+ while rank is None:
+ coords_relax = self.setYplusNormalDirection(x, t, n ,relax)
+ xi, element, rank = self.findElementContainingCoords(coords_relax)
+ relax *= 0.5
+ # just use the element containing the boundary quadrature point to interpolate to the y+ point
+ u, v, w = self.getFluidVelocityLocalCoords(self.femSpace_velocity.elementMaps.getInverseValue(element, coords),
+ element,
+ rank)
+ self.xi, self.element, self.rank = xi, element, rank
+ return u, v, w
+
+ def tangentialVelocity(self, x, t, n, uInit=None):
+ """
+ Given the velocity, calculates its
+ tangential component to the wall.
+
+ Parameters
+ ----------
+ uInit: True/False.
+ Switch for initializing the module.
+ True only during the first time step.
+ """
+ n=np.pad(n,(0,3-n.shape[0]),mode='constant',constant_values=0.0)
+ if uInit is True or self.model is None:
+ u0, u1, u2 = self.U0
+ else:
+ u0, u1, u2 = self.extractVelocity(x, t, n)
+ self.meanV = np.array([u0, u1, u2])
+ # projection of u vector over an ortoganal plane to n
+ self.tanU = self.meanV - self.meanV * (n**2)
+ # tangential unit vector
+ self.tV = self.tanU/np.sqrt(np.sum(self.tanU**2))
+
+ def getVariables(self, x, t):
+ """
+ Calculates velocity, gradient of the velocity and
+ kappa according with wall functions theory (see
+ S. B. Pope pg 442-443).
+ """
+ comm = Comm.get().comm.tompi4py()
+ # Extraction of kappa
+ self.kappa = self.kWall.getKappa(x, t, self.xi, self.element, self.rank)
+ # Calculation of nominal friction velocity based on kappa
+ self.utStar = (self.kappa**0.5) * (self.Cmu**0.25)
+ self.Ystar = self.Y * self.utStar / self.nu
+ # Absolute value of the extracted velocity at y+ location.
+ Up = np.sqrt(np.sum(self.tanU**2))
+ # viscous layer
+ if self.Ystar < 11.225:
+ self.Ustar = self.Ystar
+ self.uDir = (self.utStar*self.Ystar) * self.tV
+ self.gradU = ( (self.utStar**2)/self.nu ) * self.tV
+ # log-law layer
+ else:
+ # Wall function theory from S.B. Pope, page 442-443
+ E = np.exp(self.B * self.K)
+ self.Ustar = self.utStar * np.log(E * self.Ystar) / self.K
+ self.utAbs = self.utStar * np.sqrt(Up/self.Ustar)
+ # Velocity vector and velocity gradient multiplied by the tangential vector unit
+ self.gradU = (self.utAbs/(self.K*self.Y)) * self.tV
+ # Linear approximation for velocity at the wall (using the gradU of the logLaw)
+ self.uDir = self.tanU - (self.gradU * self.Y)
+
+ def get_u_dirichlet(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ return self.uDir[0]
+
+ def get_v_dirichlet(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ return self.uDir[1]
+
+ def get_w_dirichlet(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ return self.uDir[2]
+
+ def get_k_dirichlet(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t,n, uInit)
+ self.getVariables(x, t)
+ return self.kappa
+
+ def get_dissipation_dirichlet(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ d = 0.
+ if self.turbModel == 'ke':
+ d = (self.utStar**3)/(self.K*self.Y)
+ elif self.turbModel == 'kw' and self.kappa > 0.:
+ d = np.sqrt(self.kappa)/(self.K*self.Y*(self.Cmu**0.25))
+ return d
+
+ def get_u_diffusive(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ gradU = self.gradU[0]
+ return gradU
+
+ def get_v_diffusive(self, x, t, n ):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ gradU = self.gradU[1]
+ return gradU
+
+ def get_w_diffusive(self, x, t, n):
+ if t > 0.:
+ uInit = False
+ else:
+ uInit = True
+ self.tangentialVelocity(x, t, n, uInit)
+ self.getVariables(x, t)
+ gradU = self.gradU[2]
+ return gradU
+
+
+class kWall(AuxiliaryVariables.AV_base):
+ """
+ Auxiliary variable used to calculate attributes of an associated shape
+ class instance acting as a wall for the k variable.
+ """
+
+ def __init__(self, Y, Yplus, nu=1.004e-6, Cmu=0.09):
+ """
+ Sets turbulent boundaries for wall treatment.
+ """
+ self.kappa = 1e-10
+ self.Y = Y
+ self.Yplus = Yplus
+ self.nu = nu
+ self.model = None
+ self.Cmu = Cmu
+
+ def attachModel(self, model, ar):
+ """
+ Attaches model to auxiliary variable
+ """
+ self.model = model
+ self.ar = ar
+ self.nd = model.levelModelList[0].nSpace_global
+ return self
+
+ def attachAuxiliaryVariables(self, avDict):
+ pass
+
+ def calculate_init(self):
+ pass
+
+ def calculate(self):
+ pass
+
+ def getFluidKappaLocalCoords(self, xi, element, rank):
+ """
+
+ Parameters
+ ----------
+ xi:
+ local coords in element
+ element: int
+ element number (local to processor 'rank')
+ rank: int
+ rank of processor owning the element
+ """
+ comm = Comm.get().comm.tompi4py()
+ # solution of the selected model
+ self.u = self.model.levelModelList[0].u
+ #self.femSpace_kappa = self.u[0].femSpace
+ if comm.rank == rank:
+ kappa = self.u[0].getValue(element, xi)
+ else:
+ kappa = None
+ return kappa
+
+ def kappaNearWall(self, xi, element, rank, kInit=None):
+ if kInit is True or self.model is None:
+ self.ut = self.Yplus * self.nu / self.Y
+ self.kappa = (self.ut**2)/np.sqrt(self.Cmu)
+ else:
+ self.kappa = self.getFluidKappaLocalCoords(xi, element, rank)
+
+ def getKappa(self, x, t, xi, element, rank):
+ if t > 0.:
+ kInit = False
+ else:
+ kInit = True
+ self.kappaNearWall(xi, element, rank, kInit)
+ return abs(self.kappa)
\ No newline at end of file
diff --git a/proteus/DispatchRun.py b/proteus/DispatchRun.py
index 327d4553d0..b7df3d3d51 100644
--- a/proteus/DispatchRun.py
+++ b/proteus/DispatchRun.py
@@ -362,7 +362,7 @@ def _surface_tension(doc, spec, found):
raise RealizeError("the surface tension %s must be a number (value: ...) for the realizer" % name)
sigma = float(value)
if sigma != 0.0:
- flow = [m for m in found if m.module == "proteus.mprans.RANS2P"] \
+ flow = [m for m in found if m.module == "proteus.kernels.RANS2P"] \
if found is not None else []
if flow:
raise RealizeError("the model states surface tension %s = %r, and %s computes none (only RANS3PF's "
@@ -515,7 +515,7 @@ def _tank(split, he, name, outdir, comm):
"""The SpatialTools tank of the domain's box (Tank2D meshed by triangle, Tank3D by TetGen), its sides' BC_RANS set by
:func:`tank_sides`, at element size ``he`` (Proteus's convention, ADRProblem.mesh_constraint), or its stored mesh."""
from proteus import Domain
- from proteus.mprans import SpatialTools as st
+ from proteus import SpatialTools as st
from proteus.ADRProblem import mesh_constraint
sides = tank_sides(split)
lower, upper = _box(split)
diff --git a/proteus/DispatchTable.py b/proteus/DispatchTable.py
index 378c58ff06..23e37756de 100644
--- a/proteus/DispatchTable.py
+++ b/proteus/DispatchTable.py
@@ -82,7 +82,7 @@ def _rans2p(cell, form, flag):
"cell": cell,
"family": "two_phase_level_set",
"role": "velocity_pressure",
- "module": "proteus.mprans.RANS2P",
+ "module": "proteus.kernels.RANS2P",
"name": "rans2p",
"formulation": form,
"spaces": {"velocity": {"options": [("CG", 1)], "default": ("CG", 1)},
@@ -162,7 +162,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "rans3pf_projection",
"family": "two_phase_level_set",
"role": "velocity",
- "module": "proteus.mprans.RANS3PF",
+ "module": "proteus.kernels.RANS3PF",
"name": "rans3p",
"formulation": "nonconservative_inertia",
"spaces": {"velocity": {"options": [("CG", 2)], "default": ("CG", 2)}},
@@ -205,7 +205,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "presinc",
"family": "two_phase_level_set",
"role": "pressure_increment",
- "module": "proteus.mprans.PresInc",
+ "module": "proteus.kernels.PresInc",
"name": "pressureIncrement",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -225,7 +225,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "pres",
"family": "two_phase_level_set",
"role": "pressure",
- "module": "proteus.mprans.Pres",
+ "module": "proteus.kernels.Pres",
"name": "pressure",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -244,7 +244,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "presinit",
"family": "two_phase_level_set",
"role": "pressure_spin_up",
- "module": "proteus.mprans.PresInit",
+ "module": "proteus.kernels.PresInit",
"name": "pressureInitial",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -260,15 +260,15 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"hints": [],
},
# ---- two-phase level-set flow: the interface -------------------------------------------------------------
- _scalar_transport("vof", "volume_fraction", "proteus.mprans.VOF", "vof",
+ _scalar_transport("vof", "volume_fraction", "proteus.kernels.VOF", "vof",
{"useMetrics": 1.0}, _SUPG),
- _scalar_transport("ncls", "level_set", "proteus.mprans.NCLS", "ncls",
+ _scalar_transport("ncls", "level_set", "proteus.kernels.NCLS", "ncls",
{"useMetrics": 1.0, "checkMass": False}, _SUPG, extra_hints=["checkMass"]),
{
"cell": "rdls",
"family": "two_phase_level_set",
"role": "redistancing",
- "module": "proteus.mprans.RDLS",
+ "module": "proteus.kernels.RDLS",
"name": "rdls",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -301,7 +301,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "mcorr",
"family": "two_phase_level_set",
"role": "mass_correction",
- "module": "proteus.mprans.MCorr",
+ "module": "proteus.kernels.MCorr",
"name": "mcorr",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -332,7 +332,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "clsvof",
"family": "two_phase_level_set",
"role": "level_set_redistanced",
- "module": "proteus.mprans.CLSVOF",
+ "module": "proteus.kernels.CLSVOF",
"name": "clsvof",
"formulation": AS_WRITTEN,
"spaces": {"fields": {"options": [("CG", 1)], "default": ("CG", 1)}},
@@ -365,7 +365,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "sw2dcv",
"family": "shallow_water",
"role": "shallow_water",
- "module": "proteus.mprans.SW2DCV",
+ "module": "proteus.kernels.SW2DCV",
"name": "sw",
"formulation": AS_WRITTEN,
"scheme": {"options": ["graph_viscosity_convex_limiting"], "default": "graph_viscosity_convex_limiting"},
@@ -402,7 +402,7 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
"cell": "gn_sw2dcv",
"family": "dispersive_shallow_water",
"role": "shallow_water",
- "module": "proteus.mprans.GN_SW2DCV",
+ "module": "proteus.kernels.GN_SW2DCV",
"name": "GN_sw",
"formulation": AS_WRITTEN,
"scheme": {"options": ["graph_viscosity_convex_limiting"], "default": "graph_viscosity_convex_limiting"},
@@ -453,16 +453,16 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
#: TwoPhaseFlow's Parameters class for each module: the deck machinery builds each model's p and n from it
TWO_PHASE_PARAMETERS = {
- "proteus.mprans.RANS2P": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRANS2P",
- "proteus.mprans.RANS3PF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRANS3PF",
- "proteus.mprans.PresInc": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressureIncrement",
- "proteus.mprans.Pres": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressure",
- "proteus.mprans.PresInit": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressureInitial",
- "proteus.mprans.VOF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelVOF",
- "proteus.mprans.NCLS": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelNCLS",
- "proteus.mprans.RDLS": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRDLS",
- "proteus.mprans.MCorr": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelMCorr",
- "proteus.mprans.CLSVOF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelCLSVOF",
+ "proteus.kernels.RANS2P": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRANS2P",
+ "proteus.kernels.RANS3PF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRANS3PF",
+ "proteus.kernels.PresInc": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressureIncrement",
+ "proteus.kernels.Pres": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressure",
+ "proteus.kernels.PresInit": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelPressureInitial",
+ "proteus.kernels.VOF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelVOF",
+ "proteus.kernels.NCLS": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelNCLS",
+ "proteus.kernels.RDLS": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelRDLS",
+ "proteus.kernels.MCorr": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelMCorr",
+ "proteus.kernels.CLSVOF": "proteus.TwoPhaseFlow.utils.Parameters.ParametersModelCLSVOF",
}
#: a dispatched numerics attribute -> where TwoPhaseFlow's Parameters takes it before it builds the n module.
@@ -527,9 +527,9 @@ def _scalar_transport(cell, role, module, name, coefficients, stabilization, ext
#: SWFlow's p and n modules for each module (proteus/SWFlow/models, read through Context's mySWFlowProblem, as
#: parun --SWEs loads them) and its sw_model switch
SHALLOW_WATER_MODELS = {
- "proteus.mprans.SW2DCV": {"sw_model": 0, "p": "sw_p", "n": "sw_n"},
+ "proteus.kernels.SW2DCV": {"sw_model": 0, "p": "sw_p", "n": "sw_n"},
# the dispersive model by hyperbolic relaxation: six unknowns, h, hu, hv and the auxiliaries h eta, h w, h beta
- "proteus.mprans.GN_SW2DCV": {"sw_model": 1, "p": "GN_sw_p", "n": "GN_sw_n"},
+ "proteus.kernels.GN_SW2DCV": {"sw_model": 1, "p": "GN_sw_p", "n": "GN_sw_n"},
}
#: the dispersive family's auxiliary unknowns, by the role ymf gives them (ymf.dispersion.AUXILIARY_ROLES), in the
diff --git a/proteus/FemTools.py b/proteus/FemTools.py
index d616f74cd6..f863c1a14c 100644
--- a/proteus/FemTools.py
+++ b/proteus/FemTools.py
@@ -7576,6 +7576,10 @@ def impose(g):
return g
if strongFacesOnly:
getPeriodicBoundaryConditions = None
+ #kept for adoptDOF: a dof this rank sees but whose condition came from a face of another rank
+ self._getPointwiseBoundaryConditions = getPointwiseBoundaryConditions
+ self._impose = impose
+ self._exactConversion = exactConversion
if (getPointwiseBoundaryConditions is not None and femSpace.strongDirichletConditions and
(not weakDirichletConditions or strongFacesOnly)):
for eN in range(femSpace.elementMaps.mesh.nElements_global):
@@ -7763,6 +7767,32 @@ def impose(g):
self.global2freeGlobal_free_dofs[i] = self.global2freeGlobal[dofN]#map each of the unknown DOF's to the free unknown number
+ def adoptDOF(self,dofN,x,materialFlag):
+ """Hold the strong condition that another rank's face (or node) flag gives this dof.
+
+ A dof on the rank cut is in a rank's dictionary only if one of that rank's own elements has the
+ face or node that selects it; ``LinearAlgebraTools.strongDirichletNonAuthorityDofs`` hands the
+ authority's point and flag to the other ranks that see the dof, so that every copy loads the
+ same value into ``u`` and zeroes the same column. The setter is called exactly as the
+ constructor does. Returns whether the dof was adopted (not for exact-conversion spaces, whose
+ condition is a combination of data at several points, and not where the setter gives nothing).
+ """
+ if self._getPointwiseBoundaryConditions is None or self._exactConversion or dofN in self.DOFBoundaryConditionsDict:
+ return False
+ gReturn = self._getPointwiseBoundaryConditions(x,materialFlag)
+ try:
+ g = gReturn[0]
+ except TypeError:
+ g = gReturn
+ g = self._impose(g)
+ if not g:
+ return False
+ self.DOFBoundaryConditionsDict[dofN] = g
+ self.DOFBoundaryPointDict[dofN] = x
+ self.DOFBoundaryMaterialFlag[dofN] = materialFlag
+ self.freeDOFSet.discard(dofN)
+ return True
+
@staticmethod
def exactConversionCondition(femSpace,eN,i,g,materialFlag,getPointwiseBoundaryConditions,impose=lambda g: g):
"""
diff --git a/proteus/Gauges.py b/proteus/Gauges.py
index 522ddad100..5b3e7aa526 100644
--- a/proteus/Gauges.py
+++ b/proteus/Gauges.py
@@ -1472,7 +1472,9 @@ def gauges_from_ymf(spec, fields=None, tags=None):
def _flow_model_with_boundary_integrals(p):
- return type(p.coefficients).__module__ in ("proteus.mprans.RANS2P", "proteus.mprans.RANS3PF")
+ # the module a class reports is its package and its file (proteus.kernels.RANS2P)
+ package, _, name = type(p.coefficients).__module__.rpartition(".")
+ return package == "proteus.kernels" and name in ("RANS2P", "RANS3PF")
def _variable_names(p):
diff --git a/proteus/LinearAlgebraTools.py b/proteus/LinearAlgebraTools.py
index c2f7f2085a..6554f039e9 100644
--- a/proteus/LinearAlgebraTools.py
+++ b/proteus/LinearAlgebraTools.py
@@ -2425,7 +2425,7 @@ def matvec(self,x,y):
ParMat_petsc4py = ParMat_mpi4py
-def strongDirichletNonAuthorityDofs(model, par_r):
+def strongDirichletNonAuthorityDofs(model, par_r, adopt=None):
"""The local dofs whose strong-Dirichlet row this rank must not contribute.
With ``forceStrongConditions`` every rank replaces the rows of the dofs in its own
@@ -2442,6 +2442,21 @@ def strongDirichletNonAuthorityDofs(model, par_r):
and one ``u - g`` whatever the partition. No Dirichlet value is exchanged, so
values that depend on x or t work. Collective, once per level model.
+ The copies that are not held are not left alone: ``u - g`` is the authority's row,
+ but every other rank that sees the dof still assembles the PDE rows of its own
+ equations with its copy of ``u``, and zeroes the column of the dof only if it
+ holds it. If the owner is not the authority (the cut puts the face that selects
+ the dof on another rank than the owner's elements) the owner's copy was never
+ loaded with g and the owner's rows kept the column of an unknown that is not one:
+ the corner (0, 1) of the unit square (node flag 3, the top face, selected by the
+ left face of an element on another rank) stayed at 0 instead of 1 and the solution
+ followed (s = -146.306 against -140.990 serial). So the authority's point and flag
+ (no value, no function) go to every other rank that sees the dof and has no entry
+ of its own, and it adopts the condition (``DOFBoundaryConditions.adoptDOF``, which
+ calls the same setter as the constructor): every copy then loads the same g and
+ zeroes the same column. Those adoptions are appended to ``adopt`` as
+ ``(component, local dof number, point, flag)``, and the caller applies them.
+
Returns the local dof indices to zero (an int array, maybe empty).
"""
mpi = Comm.get().comm.tompi4py()
@@ -2452,17 +2467,27 @@ def strongDirichletNonAuthorityDofs(model, par_r):
s2g = numpy.asarray(par_r.subdomain2global)
nloc = s2g.shape[0]
hold = numpy.zeros(nloc, dtype=bool)
+ info = {} # local dof -> (point, flag) of what this rank's dictionary says, where it can be handed on
+ where = {} # local dof -> (component, dof number) for every dof the dictionaries can hold
outside = 0
dbcs = model.dirichletConditionsForceDOF
if hasattr(dbcs, 'DOFBoundaryConditionsDict'): # one object, not one per component (a single-component model)
dbcs = {0: dbcs}
for cj, dbc in dbcs.items():
+ flags = getattr(dbc, 'DOFBoundaryMaterialFlag', {})
for dofN in dbc.DOFBoundaryConditionsDict:
d = model.offset[cj] + model.stride[cj] * dofN
if d < nloc:
hold[d] = True
+ if dofN in flags and dofN in dbc.DOFBoundaryPointDict and hasattr(dbc, 'adoptDOF'):
+ info[d] = (numpy.array(dbc.DOFBoundaryPointDict[dofN], dtype=float), int(flags[dofN]))
else:
outside += 1
+ if hasattr(dbc, 'adoptDOF'):
+ for dofN in range(model.u[cj].femSpace.dim):
+ d = model.offset[cj] + model.stride[cj] * dofN
+ if d < nloc:
+ where[d] = (cj, dofN)
# a layout whose Dirichlet dofs are not subdomain dofs (a serial-periodic numbering) is left as it was;
# every rank must agree, so the decision is collective
# (and likewise where two local dofs share a global number, as merged periodic dofs do)
@@ -2475,7 +2500,7 @@ def strongDirichletNonAuthorityDofs(model, par_r):
send = [None] * size
for r in numpy.unique(gown):
sel = gown == r
- send[r] = (s2g[ghosts[sel]], hold[ghosts[sel]])
+ send[r] = (s2g[ghosts[sel]], hold[ghosts[sel]], [info.get(int(d)) for d in ghosts[sel]])
recv = mpi.alltoall(send)
owned_order = numpy.argsort(s2g[:nproc])
owned_sorted = s2g[:nproc][owned_order]
@@ -2484,36 +2509,48 @@ def strongDirichletNonAuthorityDofs(model, par_r):
for src, item in enumerate(recv):
if item is None:
continue
- for g, h in zip(*item):
- rec = any_holder.setdefault(int(g), [None, None]) # [lowest holder rank among ghosts, owner holds]
+ for g, h, i in zip(*item):
+ rec = any_holder.setdefault(int(g), [None, None, None]) # [lowest holder rank among ghosts, its info, ...]
if h and (rec[0] is None or src < rec[0]):
rec[0] = src
+ rec[1] = i
zero_owned = []
+ authority_of = {}
for g, rec in any_holder.items():
d = int(owned_order[numpy.searchsorted(owned_sorted, g)])
owner_holds = bool(hold[d])
- rec[1] = owner_holds
if rec[0] is None and not owner_holds:
continue # nobody holds it
authority = rank if owner_holds else rec[0]
- rec.append(authority)
+ auth_info = info.get(d) if owner_holds else rec[1]
+ authority_of[g] = (authority, auth_info)
if authority != rank:
zero_owned.append(d)
+ if adopt is not None and auth_info is not None and not owner_holds and d in where:
+ adopt.append(where[d] + auth_info)
reply = [None] * size
for src, item in enumerate(recv):
if item is None:
continue
flags = numpy.zeros(len(item[0]), dtype=bool)
+ given = [None] * len(item[0])
for k, g in enumerate(item[0]):
- rec = any_holder[int(g)]
- if len(rec) == 3 and rec[2] != src:
- flags[k] = True
- reply[src] = flags
+ if int(g) in authority_of:
+ authority, auth_info = authority_of[int(g)]
+ if authority != src:
+ flags[k] = True
+ given[k] = auth_info
+ reply[src] = (flags, given)
back = mpi.alltoall(reply)
zero_ghost = []
for r in numpy.unique(gown):
sel = numpy.where(gown == r)[0]
- zero_ghost.extend(ghosts[sel][back[r]].tolist())
+ flags, given = back[r]
+ zero_ghost.extend(ghosts[sel][flags].tolist())
+ if adopt is not None:
+ for dloc, auth_info in zip(ghosts[sel], given):
+ if auth_info is not None and not hold[dloc] and int(dloc) in where:
+ adopt.append(where[int(dloc)] + auth_info)
# an owned dof that no other rank sees is never shared: nothing to do for it
return numpy.array(sorted(zero_owned + zero_ghost), dtype=cmeshTools.INDEX_DTYPE)
@@ -2526,7 +2563,13 @@ def attachStrongDirichletAuthority(model, par_r, par_jacobian):
return
if getattr(par_r, 'proteus2petsc_subdomain', None) is not None or par_r.getBlockSize() != 1:
return # permuted or block layouts are not handled
- idx = strongDirichletNonAuthorityDofs(model, par_r)
+ adopt = []
+ idx = strongDirichletNonAuthorityDofs(model, par_r, adopt)
+ dbcs = model.dirichletConditionsForceDOF
+ if hasattr(dbcs, 'DOFBoundaryConditionsDict'):
+ dbcs = {0: dbcs}
+ for cj, dofN, x, flag in adopt:
+ dbcs[cj].adoptDOF(dofN, x, flag)
par_r.dirichlet_nonauthority = idx
par_jacobian.dirichlet_nonauthority = idx
- logEvent("Strong Dirichlet authority on rank %i: %i local dofs not contributed" % (Comm.get().rank(), idx.shape[0]), level=4)
+ logEvent("Strong Dirichlet authority on rank %i: %i local dofs not contributed, %i adopted" % (Comm.get().rank(), idx.shape[0], len(adopt)), level=4)
diff --git a/proteus/LinearSolvers.py b/proteus/LinearSolvers.py
index 7b743d8fbc..20b4d93ee3 100644
--- a/proteus/LinearSolvers.py
+++ b/proteus/LinearSolvers.py
@@ -16,7 +16,7 @@
from math import *
import math
from .Profiling import logEvent
-from .mprans import cArgumentsDict
+from . import cArgumentsDict
class LinearSolver(object):
""" The base class for linear solvers.
@@ -928,7 +928,7 @@ def __init__(self, linear_smoother, pde_type='general_saddle_point'):
pde_type : str
Currently supports Stokes and navierStokes
"""
- from proteus.mprans import RANS2P
+ from proteus.kernels import RANS2P
if linear_smoother.PCType!='schur':
raise Exception('This function only works with the' \
'LinearSmoothers for Schur Complements.')
@@ -4015,7 +4015,7 @@ class OperatorConstructor_rans2p(OperatorConstructor):
Arguments:
----------
- LevelModel : :class:`proteus.mprans.RANS2P.LevelModel`
+ LevelModel : :class:`proteus.kernels.RANS2P.LevelModel`
Level transport model derived from the rans2p class.
"""
def __init__(self,levelModel):
diff --git a/proteus/MeshAdaptPUMI/AdaptHelper.py b/proteus/MeshAdaptPUMI/AdaptHelper.py
index e28f32cf0b..8cd79d3384 100644
--- a/proteus/MeshAdaptPUMI/AdaptHelper.py
+++ b/proteus/MeshAdaptPUMI/AdaptHelper.py
@@ -5,7 +5,7 @@
from proteus import MeshTools
from proteus import SimTools
import proteus.Domain
-import proteus.mprans
+import proteus.kernels
def gatherGlobalMesh(sub, mpicomm, nd, vertices=None):
"""Assemble the whole (partitioned-numbering) mesh on rank 0 from the owned
@@ -285,7 +285,8 @@ def PUMI_recomputeStructures(self,modelListOld):
#clsvof needs to call poststep as well once, disc_ICs need to be turned off after initial time step
try:
- if(isinstance(self.modelList[self.phaseIdx].levelModelList[0],proteus.mprans.CLSVOF.LevelModel)):
+ from proteus.kernels import CLSVOF # call time: proteus.kernels.CLSVOF imports proteus, which imports this module
+ if(isinstance(self.modelList[self.phaseIdx].levelModelList[0],CLSVOF.LevelModel)):
model = self.modelList[self.phaseIdx]
self.postStep(model)
model.levelModelList[0].coefficients.disc_ICs = modelListOld[self.phaseIdx].levelModelList[0].coefficients.disc_ICs
@@ -564,11 +565,12 @@ def PUMI_transferFields(self):
lm.u_store[ci] = lm.u[ci].copy()
#for each type of phase tracking model, this will need to be done
+ from proteus.kernels import VOF, NCLS # call time, as above
for m in self.modelList:
for lm in m.levelModelList:
try:
- if(isinstance(lm,proteus.mprans.VOF.LevelModel) or
- isinstance(lm,proteus.mprans.NCLS.LevelModel)
+ if(isinstance(lm,VOF.LevelModel) or
+ isinstance(lm,NCLS.LevelModel)
):
lm.setUnknowns(m.uList[0])
except:
diff --git a/proteus/mprans/MeshSmoothing.pxd b/proteus/MeshSmoothing.pxd
similarity index 100%
rename from proteus/mprans/MeshSmoothing.pxd
rename to proteus/MeshSmoothing.pxd
diff --git a/proteus/mprans/MeshSmoothing.pyx b/proteus/MeshSmoothing.pyx
similarity index 100%
rename from proteus/mprans/MeshSmoothing.pyx
rename to proteus/MeshSmoothing.pyx
diff --git a/proteus/MeshTools.py b/proteus/MeshTools.py
index 1acfc50b04..62f2f23850 100644
--- a/proteus/MeshTools.py
+++ b/proteus/MeshTools.py
@@ -9198,6 +9198,58 @@ def writeMeshFiles(domain, meshOptions):
else:
raise TypeError("writeMeshFiles: no mesh generator for a " + type(domain).__name__)
+def _tetgenFileProblems(fileprefix):
+ """What stops ``fileprefix`` from being partitioned from its tetgen files (``parun -F``), as strings.
+
+ ``partitionNodesFromTetgenFiles`` reads ``.node`` and ``.ele`` and, for the faces and edges the
+ subdomains need, ``.face`` and ``.edge`` (``tetgen -Vfeen``). A missing file is a problem. Their
+ markers are optional to the reader (a file whose header announces none gives flag 0), so a header
+ with no marker column is only a warning (:func:`_tetgenMarkerWarnings`). What a header cannot tell
+ is whether the files belong together (a stale ``.edge``).
+ """
+ problems = []
+ for ext in ("node", "ele", "face", "edge"):
+ name = "{0:s}.{1:s}".format(fileprefix, ext)
+ if not os.path.isfile(name):
+ problems.append("missing " + name)
+ return problems
+
+
+def _tetgenMarkerWarnings(fileprefix):
+ """A header without the boundary marker column leaves every face or edge unflagged: say so."""
+ warnings = []
+ for ext in ("face", "edge"):
+ name = "{0:s}.{1:s}".format(fileprefix, ext)
+ try:
+ with open(name) as f:
+ header = f.readline().split()
+ except OSError:
+ continue
+ if len(header) < 2 or header[1] != "1":
+ warnings.append("{0:s} has no boundary marker column in its header, so every {1:s} gets flag 0 "
+ "(tetgen without -B writes it)".format(name, ext))
+ return warnings
+
+
+def _requireTetgenFilesToPartition(comm, fileprefix):
+ """Exit, on every rank and naming the files, unless the tetgen files of ``fileprefix`` can be partitioned.
+
+ Rank 0 looks (it is where the files are written, and the other ranks must agree with it); the
+ ranks read them collectively afterwards.
+ """
+ import sys
+ result = None
+ if comm.isMaster():
+ result = (_tetgenFileProblems(fileprefix), _tetgenMarkerWarnings(fileprefix))
+ problems, warnings = comm.comm.tompi4py().bcast(result, root=0)
+ for warning in warnings:
+ logEvent("Warning: " + warning, level=1)
+ if problems:
+ sys.exit("ERROR: parun -F partitions the mesh from its tetgen files and cannot: %s. "
+ "Make them with `tetgen -Vfeen %s.poly` (the f flag writes .face, ee writes .edge), "
+ "or set genMesh so that this run does." % ("; ".join(problems), fileprefix))
+
+
def _generateMesh(domain,meshOptions,generatePartitionedMeshFromFiles=False,numerics=None):
# convenience function to generate a mesh using triangle/tetgen/gmsh
comm = Comm.get()
@@ -9577,8 +9629,9 @@ def _generateMesh(domain,meshOptions,generatePartitionedMeshFromFiles=False,nume
parallelPartitioningType=meshOptions.parallelPartitioningType)
elif generatePartitionedMeshFromFiles:
logEvent("Generating partitioned mesh from Tetgen files")
- if("f" not in meshOptions.triangleOptions or "ee" not in meshOptions.triangleOptions):
- sys.exit("ERROR: Remake the mesh with the `f` flag and `ee` flags in triangleOptions.")
+ # the files on disk decide, not the options string that may have made them: a deck that
+ # reads a stored mesh (genMesh False) has no triangleOptions to say how it was made
+ _requireTetgenFilesToPartition(comm, fileprefix)
mlMesh.generatePartitionedMeshFromTetgenFiles(fileprefix, nbase,mesh,meshOptions.nLevels,
nLayersOfOverlap=meshOptions.nLayersOfOverlapForParallel,
parallelPartitioningType=meshOptions.parallelPartitioningType)
diff --git a/proteus/mprans/MoveMeshMonitor.py b/proteus/MoveMeshMonitor.py
similarity index 99%
rename from proteus/mprans/MoveMeshMonitor.py
rename to proteus/MoveMeshMonitor.py
index 04729b7df2..2dfba2c415 100644
--- a/proteus/mprans/MoveMeshMonitor.py
+++ b/proteus/MoveMeshMonitor.py
@@ -2,8 +2,8 @@
import copy
from proteus.Profiling import logEvent
from proteus import TransportCoefficients
-from proteus.mprans import MeshSmoothing as ms
-from proteus.mprans import cMoveMeshMonitor as cmm
+from proteus import MeshSmoothing as ms
+from proteus import cMoveMeshMonitor as cmm
class Coefficients(TransportCoefficients.PoissonEquationCoefficients):
"""
diff --git a/proteus/NumericalSolution.py b/proteus/NumericalSolution.py
index 2b7b6574e8..fdf41e1c86 100644
--- a/proteus/NumericalSolution.py
+++ b/proteus/NumericalSolution.py
@@ -19,7 +19,7 @@
from . import Viewers
from . import Gauges
from . import WallLimit
-from .mprans import PressureNormalization
+from .kernels import PressureNormalization
from .Archiver import ArchiveFlags
from . import Domain
from .MeshAdaptPUMI import Checkpoint,AdaptHelper
@@ -173,6 +173,32 @@ class StepTimeError(RuntimeError):
``t_system_last < tn`` test as if the run had reached the final time, so it finished with exit code 0."""
+#: Module paths a hot-start state written before C49 R1 can carry, and where those modules are now (first match wins;
+#: whole path components only). The kernel packages became one, proteus.kernels; a few helper modules of
+#: proteus.mprans went to proteus/ and proteus/mbd, and proteus.ADR (top level) became proteus.kernels.ADR.
+_MOVED_MODULES = (("proteus.mprans.SpatialTools", "proteus.SpatialTools"),
+ ("proteus.mprans.BoundaryConditions", "proteus.BoundaryConditions"),
+ ("proteus.mprans.BodyDynamics", "proteus.mbd.BodyDynamics"),
+ ("proteus.mprans.MeshSmoothing", "proteus.MeshSmoothing"),
+ ("proteus.mprans.MoveMeshMonitor", "proteus.MoveMeshMonitor"),
+ ("proteus.mprans.cMoveMeshMonitor", "proteus.cMoveMeshMonitor"),
+ ("proteus.mprans.cArgumentsDict", "proteus.cArgumentsDict"),
+ ("proteus.mprans", "proteus.kernels"),
+ ("proteus.richards", "proteus.kernels"),
+ ("proteus.m_comp_co2", "proteus.kernels"),
+ ("proteus.elastoplastic", "proteus.kernels"),
+ ("proteus.ADR", "proteus.kernels.ADR"))
+
+
+def _current_module_path(text):
+ """``text`` (a class path such as 'proteus.kernels.NCLS.RKEV lag=True') with a leading old module path replaced by
+ the current one; anything else comes back unchanged."""
+ for old, new in _MOVED_MODULES:
+ if text == old or text.startswith(old + ".") or text.startswith(old + " "):
+ return new + text[len(old):]
+ return text
+
+
class NS_base(object): # (HasTraits):
r"""
The base class for managing the numerical solution of PDE's.
@@ -1509,6 +1535,13 @@ def digest(a):
digest(mesh.elementNumbering_subdomain2global),
digest(mesh.nodeNumbering_subdomain2global)], dtype='int64')
+ @staticmethod
+ def _normalize_archived_policy(policy):
+ """An archived step policy with the module paths a state written before C49 R1 carries (proteus.kernels.NCLS.RKEV,
+ proteus.kernels.Richards...) read as the current ones (proteus.kernels.NCLS.RKEV, ...). Read side only: the
+ policy written now carries the current paths."""
+ return {k: _current_module_path(v) if isinstance(v, str) else v for k, v in policy.items()}
+
def _hot_start_policy(self, model, index):
"""The step policy a ``continue`` hot start must find unchanged: the
time integrator and its order, the step controllers, the shock
@@ -1877,7 +1910,7 @@ def _solverStateUsable(self, model, index, tCount):
differs = []
if "policy" in state:
import json
- then = json.loads(bytes(state["policy"]).decode())
+ then = self._normalize_archived_policy(json.loads(bytes(state["policy"]).decode()))
now = json.loads(json.dumps(self._hot_start_policy(model, index), default=str))
differs = ["%s: archived %s, now %s" % (k, then.get(k), now.get(k))
for k in sorted(set(then) | set(now)) if then.get(k) != now.get(k)]
diff --git a/proteus/SWFlow/models/GN_sw_p.py b/proteus/SWFlow/models/GN_sw_p.py
index 23438ea240..1af0c7d97f 100644
--- a/proteus/SWFlow/models/GN_sw_p.py
+++ b/proteus/SWFlow/models/GN_sw_p.py
@@ -1,6 +1,6 @@
from proteus import *
from proteus.default_p import *
-from proteus.mprans import GN_SW2DCV
+from proteus.kernels import GN_SW2DCV
from proteus.Domain import RectangularDomain
import numpy as np
from proteus import Context
diff --git a/proteus/SWFlow/models/sw_p.py b/proteus/SWFlow/models/sw_p.py
index cd8bfec3eb..46a95dbc05 100644
--- a/proteus/SWFlow/models/sw_p.py
+++ b/proteus/SWFlow/models/sw_p.py
@@ -1,6 +1,6 @@
from proteus import *
from proteus.default_p import *
-from proteus.mprans import SW2DCV
+from proteus.kernels import SW2DCV
from proteus.Domain import RectangularDomain
import numpy as np
from proteus import Context
diff --git a/proteus/SpatialTools.py b/proteus/SpatialTools.py
index 9f6e7abe28..fffb9d6677 100644
--- a/proteus/SpatialTools.py
+++ b/proteus/SpatialTools.py
@@ -37,6 +37,13 @@
from .Profiling import logEvent
from subprocess import check_call
from proteus import Comm
+from itertools import compress
+import csv
+import numbers
+import os
+from math import atan2, acos, asin
+from proteus import AuxiliaryVariables, Archiver, Profiling, Gauges
+from proteus.mbd import BodyDynamics as bd
from copy import deepcopy
from functools import reduce
@@ -1325,23 +1332,6 @@ def rotation3D(points, rot, axis=(0., 0., 1.), pivot=(0., 0., 0.)):
return points_rot
-def assembleDomain(domain):
- """
- This function sets up everything needed for the domain, meshing, and
- AuxiliaryVariables calculations (if any).
- It should always be called after defining and manipulating all the shapes
- to be attached to the domain.
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- """
- # reinitialize geometry of domain
- _assembleGeometry(domain, BC_class=bc.BC_Base)
- _generateMesh(domain)
-
def _assembleGeometry(domain, BC_class):
"""
Assembles all the geometrical informations of the shapes attached to a
@@ -1677,4 +1667,2151 @@ def extrude2Dto3D(extrusion, vertices, segments, facets, regions=None):
if regions is not None:
for region in regions_extruded:
region += extrusion/2.
- return vertices, segments, facets, regions_extruded
\ No newline at end of file
+ return vertices, segments, facets, regions_extruded
+
+
+# -----------------------------------------------------------------------------
+# TWO-PHASE FLOW (RANS) SHAPES, formerly proteus.SpatialTools (merged here by C49 R1)
+#
+# Importing this module makes every predefined shape a ShapeRANS (the bases are reassigned below), as importing
+# proteus.SpatialTools did, so a shape of either kind has the rigid-body, relaxation-zone, gauge and
+# auxiliary-variable methods; the boundary conditions of a shape are BC_RANS. assembleDomain (below) takes the
+# two-phase path when any shape of the domain is a ShapeRANS and the generic one when none is.
+# -----------------------------------------------------------------------------
+
+class ShapeRANS(Shape):
+ """
+ Base/super class of all shapes. Sets the boundary condition class to
+ proteus.BoundaryConditions.BC_RANS.
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+ nd: Optional[int]
+ Number of dimensions of the shape. If not set, will take the number of
+ dimensions of the domain.
+ """
+
+ def __init__(self, domain, nd):
+ super(ShapeRANS, self).__init__(domain, nd, BC_class=bc.BC_RANS)
+ self.mass = None
+ self.density = None
+ self.free_x = (1, 1, 1)
+ self.free_r = (1, 1, 1)
+ self.record_values = False
+ self.zones = {} # for absorption/generation zones
+ self.auxiliaryVariables = {} # list of auxvar attached to shape
+ self.It = None # inertia tensor
+
+ def _attachAuxiliaryVariable(self, key, auxvar=None, gauge=None):
+ """
+ Attaches an auxiliary variable to the auxiliaryVariables dictionary of
+ the shape (used in buildDomain function)
+
+ Parameters
+ ----------
+ key: string
+ Dictionary key defining the auxiliaryVariable to attach
+ auxvar:
+ auxiliaryVariable to associate with key
+
+ gauge: Gauges
+
+ Notes
+ -----
+ This function is called automatically when using other functions to set
+ auxiliaryVariables and should not be used manually.
+ """
+ if key not in self.auxiliaryVariables:
+ if key == 'RigidBody':
+ self.auxiliaryVariables[key] = auxvar
+ if self.holes is None:
+ self.holes = np.array([self.barycenter[:self.nd]])
+ elif key == 'WallFunction':
+ self.auxiliaryVariables[key] = auxvar
+ elif key == 'kWallFunction':
+ self.auxiliaryVariables[key] = auxvar
+ elif key == 'RelaxZones':
+ self.auxiliaryVariables[key] = self.zones
+ elif str(key).startswith('Gauge_'):
+ self.auxiliaryVariables[key] = [gauge]
+ else:
+ logEvent("auxiliaryVariable key: "
+ "{key} not recognized.".format(key=str(key)), level=1)
+ elif str(key).startswith('Gauge_'):
+ if gauge not in self.auxiliaryVariables[key]:
+ self.auxiliaryVariables[key] += [gauge]
+ else:
+ logEvent(
+ "Attempted to put identical "
+ "gauge at key: {key}".format(key=str(key)), level=1)
+ else:
+ logEvent("Key {key} is already attached.".format(key=str(key)),
+ level=1)
+
+ def attachPointGauges(self, model_key, gauges, activeTime=None,
+ sampleRate=0,
+ fileName='point_gauges.csv'):
+ """Attaches Point Gauges (in the Proteus/Gauges.py style) to the shape.
+
+ Parameters
+ ----------
+ model_key: string
+ Label of the model to use as a key for selecting particular gauges.
+ See proteus Gauges.py PointGauges class for the remaining parameters.
+ """
+ new_gauges = Gauges.PointGauges(gauges, activeTime, sampleRate,
+ fileName)
+ self._attachAuxiliaryVariable('Gauge_' + model_key,
+ gauge=new_gauges)
+
+ def attachLineGauges(self, model_key, gauges, activeTime=None,
+ sampleRate=0,
+ fileName='line_gauges.csv'):
+ """Attaches Line Gauges (in the Proteus/Gauges.py style) to the shape.
+
+ Parameters
+ ----------
+ model_key: string
+ Label of the model to use as a key for selecting particular gauges.
+ See proteus Gauges.py LineGauges class for the remaining parameters.
+ """
+ new_gauges = Gauges.LineGauges(gauges, activeTime, sampleRate,
+ fileName)
+ self._attachAuxiliaryVariable('Gauge_' + model_key,
+ gauge=new_gauges)
+
+ def attachLineIntegralGauges(self, model_key, gauges, activeTime=None,
+ sampleRate=0,
+ fileName='line_integral_gauges.csv'):
+ """Attaches Line Integral Gauges (in the Proteus/Gauges.py style).
+
+ Parameters
+ ----------
+ model_key: string
+ Label of the model to use as a key for selecting particular gauges.
+ See proteus Gauges.py LineIntegralGauges class for the remaining parameters.
+ """
+ new_gauges = Gauges.LineIntegralGauges(gauges, activeTime,
+ sampleRate, fileName)
+ self._attachAuxiliaryVariable('Gauge_' + model_key,
+ gauge=new_gauges)
+
+ def setTank(self):
+ """
+ Sets tank boundary conditions (for moving domain).
+ """
+ for boundcond in self.BC_list:
+ boundcond.setTank()
+
+ def setTurbulentWall(self, wall):
+ """
+ Sets a turbulent wall as an object to be attacched to auxiliaryVariable.
+ The objects has to be defined with WallFunction class.
+
+ Parameters
+ ----------
+ wall: list of WallFunction class object
+ """
+
+ auxvar = wall
+ self._attachAuxiliaryVariable('WallFunction', auxvar)
+
+ def setTurbulentKWall(self, kWall):
+ """
+ Sets a turbulent wall as an object to be attacched to auxiliaryVariable.
+ The objects has to be defined with WallFunction class.
+
+ Parameters
+ ----------
+ kWall: list of WallFunction class object for kappa
+ """
+
+ auxvar = kWall
+ self._attachAuxiliaryVariable('kWallFunction', auxvar)
+
+ def setAbsorptionZones(self, flags, epsFact_porous, center, orientation,
+ dragAlpha, vert_axis=None,dragBeta=0.,
+ porosity=1.):
+ """
+ Sets a region (given the local flag) to an absorption zone
+
+ Parameters
+ ----------
+ dragAlpha: Optional
+ Relaxation zone coefficient.
+ flags: array_like, int
+ Local flags of the region. Can be an integer or a list.
+ epsFact_porous: float
+ Half of absorption zone (region) length (used for blending func).
+ center: array_like
+ Coordinates of the center of the absorption zone.
+ orientation: array_like
+ Orientation vector pointing TOWARDS incoming waves.
+ vert_axis: Optional[int]
+ index of vertical position vector (x:0, y:1, z:2), must always be
+ aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ self._attachAuxiliaryVariable('RelaxZones')
+ waves = None
+ wind_speed = np.array([0., 0., 0.])
+ if isinstance(flags, numbers.Integral):
+ flags = [int(flags)]
+ epsFact_porous = [epsFact_porous]
+ center = np.array([center])
+ orientation = np.array([orientation])
+ dragAlpha = [dragAlpha]
+ dragBeta = [dragBeta]
+ porosity = [porosity]
+ for i, flag in enumerate(flags):
+ self._checkNd(center[i])
+ self._checkNd(orientation[i])
+ ori = get_unit_vector(orientation[i])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=ori,
+ center=center[i],
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous[i],
+ dragAlpha=dragAlpha[i],
+ dragBeta=dragBeta[i],
+ porosity=porosity[i],
+ vert_axis=vert_axis)
+
+ def setGenerationZones(self, flags, epsFact_porous, center, orientation,
+ waves, dragAlpha,vert_axis=None,
+ wind_speed=(0., 0., 0.), dragBeta=0.,
+ porosity=1., smoothing=0.):
+ """
+ Sets a region (given the local flag) to a generation zone
+
+ Parameters
+ ----------
+ flags: array_like, int
+ Local flags of the region. Can be an integer or a list.
+ epsFact_porous: float
+ Half of absorption zone (region) length (used for blending func).
+ center: array_like
+ Coordinates of the center of the absorption zone.
+ orientation: array_like
+ Orientation vector pointing ACCORDING WITH the direction of generated waves.
+ waves: proteus.WaveTools
+ Class instance of wave generated from proteus.WaveTools.
+ dragAlpha: Optional[float]
+ Relaxation zone coefficient.
+ vert_axis: Optional[int]
+ index of vertical position vector (x:0, y:1, z:2), must always be
+ aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
+ wind_speed: Optional[array_like]
+ Speed of wind in generation zone (default is (0., 0., 0.))
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ self._attachAuxiliaryVariable('RelaxZones')
+ if isinstance(flags, numbers.Integral):
+ flags = [int(flags)]
+ epsFact_porous = [epsFact_porous]
+ center = np.array([center])
+ orientation = np.array([orientation])
+ waves = [waves]
+ wind_speed = np.array([wind_speed])
+ dragAlpha = [dragAlpha]
+ dragBeta = [dragBeta]
+ porosity = [porosity]
+ smoothing = [smoothing]
+ for i, flag in enumerate(flags):
+ self._checkNd(center[i])
+ self._checkNd(orientation[i])
+ ori = get_unit_vector(orientation[i])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=ori,
+ center=center[i],
+ waves=waves[i],
+ wind_speed=wind_speed[i],
+ epsFact_porous=epsFact_porous[i],
+ dragAlpha=dragAlpha[i],
+ dragBeta=dragBeta[i],
+ porosity=porosity[i],
+ smoothing=smoothing[i],
+ vert_axis=vert_axis)
+
+ def setPorousZones(self, flags, dragAlpha, dragBeta,
+ porosity):
+ """
+ Sets a region (given the local flag) to a porous zone
+
+ Parameters
+ ----------
+ flags: array_like, int
+ Local flags of the region. Can be an integer or a list.
+ dragAlpha: float
+ Darcy-type coefficient
+ dragBeta: float
+ Forchheimer-type coefficient
+ porosity: float
+ Porosity
+ """
+ self._attachAuxiliaryVariable('RelaxZones')
+ if isinstance(flags, numbers.Integral):
+ flags = [int(flags)]
+ dragAlpha = [dragAlpha]
+ dragBeta = [dragBeta]
+ porosity = [porosity]
+ for i, flag in enumerate(flags):
+ # note for porous zone:
+ # epsFact_porous = q_phi_sponge, --> Hs always equal to 1.
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='porous',
+ orientation=None,
+ center=None,
+ waves=None,
+ wind_speed=None,
+ epsFact_porous=1.,
+ dragAlpha=dragAlpha[i],
+ dragBeta=dragBeta[i],
+ porosity=porosity[i])
+
+# -----------------------------------------------------------------------------
+# ADDING FUNCTIONALITY TO SHAPE FROM proteus.SpatialTools
+# -----------------------------------------------------------------------------
+
+
+# reassigning base/super class to access all functions from ShapeRANS and Shape
+Rectangle.__bases__ = (ShapeRANS,)
+Cuboid.__bases__ = (ShapeRANS,)
+Sphere.__bases__ = (ShapeRANS,)
+Cylinder.__bases__ = (ShapeRANS,)
+CustomShape.__bases__ = (ShapeRANS,)
+ShapeSTL.__bases__ = (ShapeRANS,)
+Circle.__bases__ = (ShapeRANS,)
+
+# adding extra functionality to predefined shapes
+
+
+def _CuboidsetInertiaTensor(self):
+ """
+ Sets the inertia tensor of the cuboid
+ (!) should not be used manually
+ """
+ L, W, H = self.dim
+ self.It = [[(W**2.+H**2.)/12., 0, 0],
+ [0, (L**2.+H**2.)/12., 0],
+ [0, 0, (W**2.+L**2.)/12.]]
+
+
+Cuboid._setInertiaTensor = _CuboidsetInertiaTensor
+
+
+def _RectanglesetInertiaTensor(self):
+ """
+ Sets the inertia tensor of the rectangle
+ (!) should not be used manually
+ """
+ L, H = self.dim
+ self.It = (L**2+H**2)/12
+
+
+Rectangle._setInertiaTensor = _RectanglesetInertiaTensor
+
+
+# -----------------------------------------------------------------------------
+# DEFINING NEW SHAPES TYPES
+# -----------------------------------------------------------------------------
+
+class Tank3D(ShapeRANS):
+ """
+ Class to create a 3D tank (cuboidal shape).
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+ dim: Optional[array_like]
+ Dimensions of the cuboid.
+ coords: Optional[array_like]
+ Coordinates of the centroid of the shape.
+ """
+ count = 0
+
+ def __init__(self, domain, dim=(0., 0., 0.), coords=None):
+ super(Tank3D, self).__init__(domain, nd=3)
+ self.__class__.count += 1
+ self.name = "tank3d" + repr(self.__class__.count)
+ if coords is None:
+ self.coords = np.array(dim)/2.
+ self.from_0 = True
+ else:
+ self.coords = coords
+ self.from_0 = False
+ self.holes = None
+ self.boundaryTags = {'z-': 1,
+ 'x-': 2,
+ 'y+': 3,
+ 'x+': 4,
+ 'y-': 5,
+ 'z+': 6,
+ 'sponge': 7,
+ 'wall': 8}
+ self.b_or = np.array([[0., 0., -1.],
+ [-1., 0., 0.],
+ [0., 1., 0.],
+ [1., 0., 0.],
+ [0., -1., 0.],
+ [0., 0., 1.]])
+ self.BC = {'z-': self.BC_class(shape=self, name='z-',
+ b_or=self.b_or, b_i=0),
+ 'x-': self.BC_class(shape=self, name='x-',
+ b_or=self.b_or, b_i=1),
+ 'y+': self.BC_class(shape=self, name='y+',
+ b_or=self.b_or, b_i=2),
+ 'x+': self.BC_class(shape=self, name='x+',
+ b_or=self.b_or, b_i=3),
+ 'y-': self.BC_class(shape=self, name='y+',
+ b_or=self.b_or, b_i=4),
+ 'z+': self.BC_class(shape=self, name='z+',
+ b_or=self.b_or, b_i=5),
+ 'sponge': self.BC_class(shape=self, name='sponge'),
+ 'wall': self.BC_class(shape=self, name='wall')}
+ self.BC_list = [self.BC['z-'],
+ self.BC['x-'],
+ self.BC['y+'],
+ self.BC['x+'],
+ self.BC['y+'],
+ self.BC['z+'],
+ self.BC['sponge'],
+ self.BC['wall']]
+ # self.BC = BCContainer(self.BC_dict)
+ for i in range(6):
+ self.BC_list[i].setTank()
+ self.barycenter = np.array([0., 0., 0.])
+ self.spongeLayers = {'y+': None, 'y-': None, 'x+': None, 'x-': None}
+ self.setDimensions(dim)
+
+ def setSponge(self, x_p=None, x_n=None, y_p=None, y_n=None):
+ """
+ Set length of sponge layers of the tank (used for wave absorption or
+ generation zones).
+ (!) Sponge layers expand outwards.
+
+ Parameters
+ ----------
+ x_p: Optional[float]
+ length of sponge layer in +x direction.
+ x_n: Optional[float]
+ length of sponge layer in -x direction.
+ y_p: Optional[float]
+ length of sponge layer in +y direction.
+ y_n: Optional[float]
+ length of sponge layer in -y direction.
+ """
+ self.spongeLayers['x+'] = x_p
+ self.spongeLayers['x-'] = x_n
+ self.spongeLayers['y+'] = y_p
+ self.spongeLayers['y-'] = y_n
+ self.setDimensions(self.dim)
+
+ def setDimensions(self, dim):
+ """
+ Set dimension of the tank
+ Parameters
+ ----------
+ dim: array_like
+ dimensions of the tank (excluding sponge layers), array of length 3.
+ """
+ L, W, H = dim
+ self.dim = dim
+ if self.from_0 is True:
+ x, y, z = L/2., W/2., H/2.
+ else:
+ x, y, z = self.coords
+ self.coords = [x, y, z]
+ x0, x1 = x - 0.5 * L, x + 0.5 * L
+ y0, y1 = y - 0.5 * W, y + 0.5 * W
+ z0, z1 = z - 0.5 * H, z + 0.5 * H
+ # ---------------------------------------------
+ # first add all vecors, facets, regions at the bottom
+ # ---------------------------------------------
+ bt = self.boundaryTags
+ x_p = self.spongeLayers['x+'] or 0.
+ x_n = self.spongeLayers['x-'] or 0.
+ y_p = self.spongeLayers['y+'] or 0.
+ y_n = self.spongeLayers['y-'] or 0.
+ vertices = [[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0],
+ [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]]
+ vertexFlags = [bt['z-'], bt['z-'], bt['z-'], bt['z-'],
+ bt['z+'], bt['z+'], bt['z+'], bt['z+']]
+ facets = [[[0, 1, 2, 3]], [[4, 5, 6, 7]]]
+ segments = []
+ segmentFlags = []
+ volumes = [[[0, 1]]]
+ facetFlags = [bt['z-'], bt['z+']]
+ regions = [[(x0+x1)/2., (y0+y1)/2., (z0+z1)/2.]]
+ regionFlags = [1]
+ self.regionIndice = {'tank': 0}
+ v_i = 8 # index of next vector to add
+ r_i = 1 # index of next region to add
+ f_i = len(facets)
+ nb_sponge = 0 # number of sponge layers defined
+
+ ymin = y0 - y_n
+ ymax = y1 + y_p
+ xmin = x0 - x_n
+ xmax = x1 + x_p
+ corners = False
+ # y-
+ if y_n:
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ if corners:
+ vertices += [[x0, ymin, z0], [x0, ymin, z1],
+ [x1, ymin, z0], [x1, ymin, z1]]
+ else:
+ vertices += [[xmin, ymin, z0], [xmin, ymin, z1],
+ [xmax, ymin, z0], [xmax, ymin, z1]]
+ vertexFlags += [bt['z-'], bt['z+'],
+ bt['z-'], bt['z+']]
+ facets += [[[v0, v1, v3, v2]]]
+ facetFlags += [bt['y-']]
+ volumes[0][0] += [f_i]
+ regions += [[(x0+x1)/2., (y0+(ymin))/2., (z0+z1)/2.]]
+ self.regionIndice['y-'] = r_i
+ regionFlags += [r_i + 1]
+ facets += [[[0, 1, v1, v0]],
+ [[4, 5, v3, v2]],
+ [[0, 1, 5, 4]],
+ [[0, v0, v2, 4]],
+ [[1, v1, v3, 5]]]
+ facetFlags += [bt['z-'],
+ bt['z+'],
+ bt['sponge']]
+ if x_n > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['x-']]
+ if x_p > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['x+']]
+ volumes[0][0][-1] = f_i + 3 # add to volume
+ r_i += 1
+ nb_sponge += 1
+ volumes += [[[len(facets) - i - 1 for i in range(6)]]]
+ x_n_facet_i = len(facets) - 2
+ else:
+ facets += [[[0, 1, 5, 4]]]
+ facetFlags += [bt['y-']]
+ volumes[0][0] += [f_i]
+ v_i = len(vertices)
+ f_i = len(facets)
+ # x+
+ if x_p:
+ if corners:
+ vertices += [[xmax, y0, z0], [xmax, y0, z1],
+ [xmax, y1, z0], [xmax, y1, z1]]
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ vertexFlags += [bt['z-'], bt['z+'],
+ bt['z-'], bt['z+']]
+ else:
+ v0 = v_i - 2
+ v1 = v_i
+ v2 = v_i - 1
+ v3 = v_i + 1
+ if not y_n:
+ vertices += [[xmax, ymin, z0], [xmax, ymin, z1]]
+ vertexFlags += [bt['z-'], bt['z+']]
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ vertices += [[xmax, ymax, z0], [xmax, ymax, z1]]
+ vertexFlags += [bt['z-'], bt['z+']]
+ facets += [[[v0, v1, v3, v2]]]
+ facetFlags += [bt['x+']]
+ volumes[0][0] += [f_i]
+ regions += [[(x1+(xmax))/2., (y0+y1)/2., (z0+z1)/2.]]
+ self.regionIndice['x+'] = r_i
+ regionFlags += [r_i + 1]
+ facets += [[[1, 2, v1, v0]],
+ [[5, 6, v3, v2]],
+ [[1, 2, 6, 5]]]
+ facetFlags += [bt['z-'],
+ bt['z+'],
+ bt['sponge']]
+ if corners or not y_n:
+ facets += [[[1, v0, v2, 5]]]
+ if y_n > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['y-']]
+ facets += [[[2, v1, v3, 6]]]
+ if y_p > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['y+']]
+ volumes[0][0][-1] = f_i + 3 # add to volume
+ r_i += 1
+ nb_sponge += 1
+ volumes += [[[len(facets) - i - 1 for i in range(6)]]]
+ else:
+ facets += [[[1, 2, 6, 5]]]
+ facetFlags += [bt['x+']]
+ volumes[0][0] += [f_i]
+ v_i = len(vertices)
+ f_i = len(facets)
+ # y+
+ if y_p:
+ if corners:
+ vertices += [[x1, ymax, z0], [x1, ymax, z1],
+ [x0, ymax, z0], [x0, ymax, z1]]
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ vertexFlags += [bt['z-'], bt['z+'],
+ bt['z-'], bt['z+']]
+ else:
+ v0 = v_i - 2
+ v1 = v_i
+ v2 = v_i - 1
+ v3 = v_i + 1
+ if not x_p:
+ vertices += [[xmax, ymax, z0], [xmax, ymax, z1]]
+ vertexFlags += [bt['z-'], bt['z+']]
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ vertices += [[xmin, ymax, z0], [xmin, ymax, z1]]
+ vertexFlags += [bt['z-'], bt['z+']]
+ facets += [[[v0, v1, v3, v2]]]
+ volumes[0][0] += [f_i]
+ facetFlags += [bt['y+']]
+ regions += [[(x0+x1)/2., (y1+(ymax))/2., (z0+z1)/2.]]
+ self.regionIndice['y+'] = r_i
+ regionFlags += [r_i + 1]
+ facets += [[[2, 3, v1, v0]],
+ [[6, 7, v3, v2]],
+ [[2, 3, 7, 6]]]
+ facetFlags += [bt['z-'],
+ bt['z+'],
+ bt['sponge']]
+ if corners or not x_p:
+ facets += [[[2, v0, v2, 6]]]
+ if x_p > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['x+']]
+ facets += [[[3, v1, v3, 7]]]
+ if x_n > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['x-']]
+ volumes[0][0][-1] = f_i + 3
+ r_i += 1
+ nb_sponge += 1
+ volumes += [[[len(facets) - i - 1 for i in range(6)]]]
+ else:
+ facets += [[[3, 2, 6, 7]]]
+ facetFlags += [bt['y+']]
+ volumes[0][0] += [f_i]
+ v_i = len(vertices)
+ f_i = len(facets)
+ # x-
+ if x_n:
+ volumes[0][0] += [f_i]
+ if corners:
+ vertices += [[xmin, y0, z0], [xmin, y0, z1],
+ [xmin, y1, z0], [xmin, y1, z1]]
+ v0 = v_i
+ v1 = v_i + 2
+ v2 = v_i + 1
+ v3 = v_i + 3
+ vertexFlags += [bt['z-'], bt['z+'],
+ bt['z-'], bt['z+']]
+ else:
+ if not y_p:
+ vertices += [[xmin, ymax, z0], [xmin, ymax, z1]]
+ v0 = v_i - 2
+ v1 = v_i
+ v2 = v_i - 1
+ v3 = v_i + 1
+ vertexFlags += [bt['z-'], bt['z+']]
+ if not y_n:
+ vertices += [[xmin, ymin, z0], [xmin, ymin, z1]]
+ if not y_p:
+ v0 = v_i + 2
+ v1 = v_i
+ v2 = v_i + 3
+ v3 = v_i + 1
+ else:
+ v0 = v_i
+ v1 = v_i - 2
+ v2 = v_i + 1
+ v3 = v_i - 1
+ vertexFlags += [bt['z-'], bt['z+']]
+ else:
+ v1 = v_i - 2
+ v0 = 8
+ v3 = v_i - 1
+ v2 = 9
+ if not y_p:
+ v1 = v_i
+ v3 = v_i + 1
+ facets += [[[v0, v1, v3, v2]]]
+ facetFlags += [bt['x-']]
+ regions += [[(x0+(xmin))/2., (y0+y1)/2., (z0+z1)/2.]]
+ self.regionIndice['x-'] = r_i
+ regionFlags += [r_i + 1]
+ facets += [[[0, 3, v1, v0]],
+ [[4, 7, v3, v2]],
+ [[0, 3, 7, 4]]]
+ facetFlags += [bt['z-'],
+ bt['z+'],
+ bt['sponge']]
+ volumes[0][0][-1] = f_i + 3
+ if corners or not y_n or not y_p:
+ if corners or not y_n:
+ facets += [[[0, v0, v2, 4]]]
+ if y_n > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['y-']]
+ if corners or not y_p:
+ facets += [[[3, v1, v3, 7]]]
+ if y_p > 0:
+ facetFlags += [bt['wall']]
+ else:
+ facetFlags += [bt['y+']]
+ r_i += 1
+ nb_sponge += 1
+ if corners or not y_n:
+ volumes += [[[len(facets) - i - 1 for i in range(6)]]]
+ else:
+ volumes += [[[len(facets) - i - 1 for i in range(5)] + [x_n_facet_i]]]
+ else:
+ facets += [[[0, 3, 7, 4]]]
+ facetFlags += [bt['x-']]
+ volumes[0][0] += [f_i]
+ v_i = len(vertices)
+ f_i = len(facets)
+ self.vertices = np.array(vertices)
+ self.vertices = np.dot(self.vertices, self.coords_system)
+ self.vertexFlags = np.array(vertexFlags)
+ self.segments = np.array(segments)
+ self.segmentFlags = np.array(segmentFlags)
+ self.facets = np.array(facets)
+ self.facetFlags = np.array(facetFlags)
+ self.regions = np.array(regions)
+ self.regionFlags = np.array(regionFlags)
+ self.volumes = volumes
+
+ def setAbsorptionZones(self, dragAlpha, allSponge=False,
+ y_n=False, y_p=False,
+ x_n=False, x_p=False,
+ dragBeta=0., porosity=1.):
+ """
+ Sets regions (x+, x-, y+, y-) to absorption zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient.
+ allSponge: bool
+ If True, all sponge layers are converted to absorption zones.
+ x_p: bool
+ If True, x+ region is converted to absorption zone.
+ x_n: bool
+ If True, x- region is converted to absorption zone.
+ y_p: bool
+ If True, y+ region is converted to absorption zone.
+ y_n: bool
+ If True, y- region is converted to absorption zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ self.abs_zones = {'y-': y_n, 'y+': y_p, 'x-': x_n, 'x+': x_p}
+ if allSponge is True:
+ for key in self.abs_zones:
+ self.abs_zones[key] = True
+ waves = None
+ wind_speed = np.array([0., 0., 0.])
+ sl = self.spongeLayers
+ for key, value in list(self.abs_zones.items()):
+ if value is True:
+ self._attachAuxiliaryVariable('RelaxZones')
+ ind = self.regionIndice[key]
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers[key]/2.
+ center = np.array(self.coords)
+ zeros_to_append = 3 - len(center)
+ if zeros_to_append:
+ for i in range(zeros_to_append):
+ center = np.append(center, [0])
+ if key == 'x-':
+ center[0] += -0.5 * self.dim[0] - 0.5 * sl['x-']
+ orientation = np.array([1., 0., 0.])
+ elif key == 'x+':
+ center[0] += +0.5 * self.dim[0] + 0.5 * sl['x+']
+ orientation = np.array([-1., 0., 0.])
+ elif key == 'y-':
+ center[1] += -0.5 * self.dim[1] - 0.5 * sl['y-']
+ orientation = np.array([0., 1., 0.])
+ elif key == 'y+':
+ center[1] += +0.5 * self.dim[1] + 0.5 * sl['y+']
+ orientation = np.array([0., -1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity)
+
+ def setGenerationZones(self, dragAlpha, smoothing, waves=None,
+ wind_speed=(0., 0., 0.), allSponge=False, y_n=False,
+ y_p=False, x_n=False, x_p=False, dragBeta=0.,
+ porosity=1.):
+ """
+ Sets regions (x+, x-, y+, y-) to generation zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient.
+ smoothing: float
+ Smoothing distance (typically 3.*he)
+ waves: proteus.WaveTools
+ Class instance of wave generated from proteus.WaveTools.
+ wind_speed: Optional[array_like]
+ Speed of wind in generation zone (default is (0., 0., 0.))
+ allSponge: bool
+ If True, all sponge layers are converted to generation zones.
+ x_p: bool
+ If True, x+ region is converted to generation zone.
+ x_n: bool
+ If True, x- region is converted to generation zone.
+ y_p: bool
+ If True, y+ region is converted to generation zone.
+ y_n: bool
+ If True, y- region is converted to generation zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ self.abs_zones = {'y-': y_n, 'y+': y_p, 'x-': x_n, 'x+': x_p}
+ if allSponge is True:
+ for key in self.abs_zones:
+ self.abs_zones[key] = True
+ waves = waves
+ wind_speed = np.array(wind_speed)
+ sl = self.spongeLayers
+ for key, value in list(self.abs_zones.items()):
+ if value is True:
+ self._attachAuxiliaryVariable('RelaxZones')
+ ind = self.regionIndice[key]
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers[key]/2.
+ center = np.array(self.coords)
+ zeros_to_append = 3 - len(center)
+ if zeros_to_append:
+ for i in range(zeros_to_append):
+ center = np.append(center, [0])
+ if key == 'x-':
+ center[0] += -0.5 * self.dim[0] - sl['x-']/2.
+ orientation = np.array([1., 0., 0.])
+ self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ elif key == 'x+':
+ center[0] += +0.5 * self.dim[0] + sl['x+']/2.
+ orientation = np.array([-1., 0., 0.])
+ self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ elif key == 'y-':
+ center[1] += -0.5 * self.dim[1] - sl['y-']/2.
+ orientation = np.array([0., 1., 0.])
+ self.BC['y-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ elif key == 'y+':
+ center[1] += +0.5 * self.dim[1] + sl['y+']/2.
+ orientation = np.array([0., -1., 0.])
+ self.BC['y+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity,
+ smoothing=smoothing)
+
+
+class Tank2D(ShapeRANS):
+ """
+ Class to create a 2D tank (rectangular shape).
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+ dim: array_like
+ Dimensions of the tank (excluding sponge layers).
+ coords: Optional[array_like]
+ Coordinates of the centroid of the shape.
+ """
+ count = 0
+
+ def __init__(self, domain, dim, coords=None):
+ super(Tank2D, self).__init__(domain, nd=2)
+ if coords is None:
+ self.coords = np.array(dim)/2.
+ self.from_0 = True
+ else:
+ self.coords = coords
+ self.from_0 = False
+ self.dim = dim
+ self._nameSelf()
+ self._setupBCs()
+ self.spongeLayers = {'x-': None,
+ 'x+': None}
+ self.constructShape()
+
+ def _nameSelf(self):
+ self.__class__.count += 1
+ self.name = "tank2D" + repr(self.__class__.count)
+
+ def _setupBCs(self):
+ self.boundaryTags = {'y-': 1, 'x+': 2, 'y+': 3, 'x-': 4, 'sponge': 5}
+ self.b_or = np.array([[0., -1., 0.],
+ [1., 0., 0.],
+ [0., 1., 0.],
+ [-1., 0., 0.]])
+ self.BC = {'y-': self.BC_class(shape=self, name='y-',
+ b_or=self.b_or, b_i=0),
+ 'x+': self.BC_class(shape=self, name='x+',
+ b_or=self.b_or, b_i=1),
+ 'y+': self.BC_class(shape=self, name='y+',
+ b_or=self.b_or, b_i=2),
+ 'x-': self.BC_class(shape=self, name='x-',
+ b_or=self.b_or, b_i=3),
+ 'sponge': self.BC_class(shape=self, name='sponge')}
+ self.BC_list = [self.BC['y-'],
+ self.BC['x+'],
+ self.BC['y+'],
+ self.BC['x-'],
+ self.BC['sponge']]
+ # self.BC = BCContainer(self.BC_dict)
+ for i in range(4):
+ self.BC_list[i].setTank()
+
+ def constructShape(self):
+ """
+ Construct the geometry of the tank: segments, regions, etc.
+
+ Parameters
+ ----------
+ frame: array_like
+ An array of (x,y) coordinates in counterclockwise order to define
+ the boundaries of the main (that is, excluding extensions such as
+ sponge zones) shape. This can be generated with tank2DFrame or
+ subclass specific methods.
+ frame_flags: array_like
+ A corresponding array of boundary tags associated with each point
+ in the frame. This can be generated with tank2DFrame or subclass
+ specific methods.
+ """
+ self._findEdges(self.dim)
+ vertices, vertexFlags = self._constructVertices()
+ segments, segmentFlags = self._constructSegments(vertices, vertexFlags)
+ regions, regionFlags = self._constructRegions(vertices, vertexFlags,
+ segments, segmentFlags)
+ facets, facetFlags = self._constructFacets()
+
+ self.vertices = np.array(vertices)
+ self.vertexFlags = np.array(vertexFlags)
+ self.segments = np.array(segments)
+ self.segmentFlags = np.array(segmentFlags)
+ self.regions = np.array(regions)
+ self.regionFlags = np.array(regionFlags)
+ self.facets = np.array(facets)
+ self.facetFlags = np.array(facetFlags)
+
+ def _findEdges(self, dim):
+
+ coords = self.coords
+ from_0 = self.from_0
+
+ if from_0:
+ self.x0 = 0
+ self.x1 = dim[0]
+ self.y0 = 0
+ self.y1 = dim[1]
+ else: # not from_0 and coords is not None
+ self.x0 = coords[0] - 0.5 * dim[0]
+ self.x1 = coords[0] + 0.5 * dim[0]
+ self.y0 = coords[1] - 0.5 * dim[1]
+ self.y1 = coords[1] + 0.5 * dim[1]
+
+ def _constructVertices(self):
+ vertices = [[self.x0, self.y0],
+ [self.x1, self.y0],
+ [self.x1, self.y1],
+ [self.x0, self.y1]]
+ vertexFlags = [self.boundaryTags['y-'],
+ self.boundaryTags['y-'],
+ self.boundaryTags['y+'],
+ self.boundaryTags['y+']]
+ if self.spongeLayers['x-']:
+ vertices += [[self.x0 - self.spongeLayers['x-'], self.y0],
+ [self.x0 - self.spongeLayers['x-'], self.y1]]
+ vertexFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]
+ if self.spongeLayers['x+']:
+ vertices += [[self.x1 + self.spongeLayers['x+'], self.y0],
+ [self.x1 + self.spongeLayers['x+'], self.y1]]
+ vertexFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]
+ return vertices, vertexFlags
+
+ def _constructSegments(self, vertices, vertexFlags):
+ segments = [[0, 1], [1, 2], [2, 3], [3, 0]]
+ segmentFlags = [self.boundaryTags['y-'],
+ self.boundaryTags['x+'],
+ self.boundaryTags['y+'],
+ self.boundaryTags['x-']]
+ added_vertices = 0
+ if self.spongeLayers['x-']:
+ segments += [[0, 4 + added_vertices],
+ [4 + added_vertices, 5 + added_vertices],
+ [5 + added_vertices, 3]]
+ segmentFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['x-'],
+ self.boundaryTags['y+']]
+ segmentFlags[3] = self.boundaryTags['sponge']
+ added_vertices += 2
+ if self.spongeLayers['x+']:
+ segments += [[1, 4 + added_vertices],
+ [4 + added_vertices, 5 + added_vertices],
+ [5 + added_vertices, 2]]
+ segmentFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['x+'],
+ self.boundaryTags['y+']]
+ segmentFlags[1] = self.boundaryTags['sponge']
+ added_vertices += 2
+ return segments, segmentFlags
+
+ def _constructFacets(self):
+ facets = [[[0, 1, 2, 3]]]
+ facetFlags = [1]
+ added_vertices = 0
+ added_facets = 0
+ if self.spongeLayers['x-']:
+ facets += [[[3, 0, 4, 5]]]
+ facetFlags += [2 + added_facets]
+ added_vertices += 2
+ added_facets += 1
+ if self.spongeLayers['x+']:
+ facets += [[[2, 1, added_vertices + 4, added_vertices + 5]]]
+ facetFlags += [2 + added_facets]
+ return facets, facetFlags
+
+ def _constructRegions(self, vertices, vertexFlags, segments, segmentFlags):
+ regions = [[self.x0 + 0.01 * (self.x1 - self.x0), 0.5 * (self.y0 + self.y1)], ]
+ ind_region = 1
+ regionFlags = [ind_region, ]
+ self.regionIndice = {'tank': ind_region - 1}
+ if self.spongeLayers['x-']:
+ regions += [[self.x0 - 0.5 * self.spongeLayers['x-'],
+ 0.5 * (self.y0 + self.y1)]]
+ ind_region += 1
+ regionFlags += [ind_region]
+ self.regionIndice['x-'] = ind_region - 1
+ if self.spongeLayers['x+']:
+ regions += [[self.x1 + 0.5 * self.spongeLayers['x+'],
+ 0.5 * (self.y0 + self.y1)]]
+ ind_region += 1
+ regionFlags += [ind_region]
+ self.regionIndice['x+'] = ind_region - 1
+ return regions, regionFlags
+
+ def setSponge(self, x_n=None, x_p=None):
+ """
+ Set length of sponge layers of the tank (used for wave absorption or
+ generation zones).
+ (!) Sponge layers expand outwards.
+
+ Parameters
+ ----------
+ x_p: Optional[float]
+ length of sponge layer in +x direction.
+ x_n: Optional[float]
+ length of sponge layer in -x direction.
+ """
+ self.spongeLayers['x-'] = x_n
+ self.spongeLayers['x+'] = x_p
+ self.constructShape()
+
+ def setAbsorptionZones(self, dragAlpha, x_n=False, x_p=False,
+ dragBeta=0., porosity=1.):
+ """
+ Sets regions (x+, x-) to absorption zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient.
+ allSponge: bool
+ If True, all sponge layers are converted to absorption zones.
+ x_p: bool
+ If True, x+ region is converted to absorption zone.
+ x_n: bool
+ If True, x- region is converted to absorption zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ waves = None
+ wind_speed = np.array([0., 0., 0.])
+ if x_n or x_p:
+ self._attachAuxiliaryVariable('RelaxZones')
+ if x_n is True:
+ center = np.array([self.coords[0]-0.5*self.dim[0]-0.5*self.spongeLayers['x-'],
+ self.coords[1],
+ 0.])
+ ind = self.regionIndice['x-']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x-']/2.
+ orientation = np.array([1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity)
+ if x_p is True:
+ center = np.array([self.coords[0]+0.5*self.dim[0]+0.5*self.spongeLayers['x+'],
+ self.coords[1],
+ 0.])
+ ind = self.regionIndice['x+']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x+']/2.
+ orientation = np.array([-1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity)
+
+ def setGenerationZones(self, dragAlpha, smoothing,
+ waves=None, wind_speed=(0., 0., 0.),
+ x_n=False, x_p=False,
+ dragBeta=0., porosity=1.):
+ """
+ Sets regions (x+, x-) to generation zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient
+ smoothing:
+ Smoothing distance
+ waves: proteus.WaveTools
+ Class instance of wave generated from proteus.WaveTools.
+ wind_speed: Optional[array_like]
+ Speed of wind in generation zone (default is (0., 0., 0.))
+ allSponge: bool
+ If True, all sponge layers are converted to generation zones.
+ x_p: bool
+ If True, x+ region is converted to generation zone.
+ x_n: bool
+ If True, x- region is converted to generation zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ waves = waves
+ wind_speed = np.array(wind_speed)
+ if x_n or x_p:
+ self._attachAuxiliaryVariable('RelaxZones')
+ if x_n is True:
+ center = np.array([self.coords[0]-0.5*self.dim[0]-0.5*self.spongeLayers['x-'],
+ self.coords[1],
+ 0.])
+ ind = self.regionIndice['x-']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x-']/2.
+ orientation = np.array([1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity,
+ smoothing=smoothing)
+ self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ if x_p is True:
+ center = np.array([self.coords[0]+0.5*self.dim[0]+0.5*self.spongeLayers['x+'],
+ self.coords[1],
+ 0.])
+ ind = self.regionIndice['x+']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x+']/2.
+ orientation = np.array([-1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity,
+ smoothing=smoothing)
+ self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+
+#[temp] no tests yet!
+
+
+class TankWithObstacles2D(Tank2D):
+ """
+ Class to create a 2D rectangular tank with obstacles built out of any wall.
+
+ An obstacle is defined by a contiguous list of points which start and end
+ on the walls or corners of the tank.
+
+ This also covers special boundary conditions. To tag a segment with a
+ unique boundary tag, add the starting vertex (in the counterclockwise
+ format the shape is generated in) of the segment as a value in a dictionary
+ element keyed to the name of the boundary tag.
+
+ (!) Warning: If each of the four corners of the rectangular tank is inside
+ an obstacle or a vertex for an obstacle, then the tank's region is defined
+ in a pseudorandom manner, which may make it unreliable when dealing with
+ holes caused by other shapes.
+ (!) Warning: Obstacle boundary tags are keyed to whichever edge they started
+ from. If this is undesirable, it may be manually overriden by applying
+ special boundary conditions to affected segments.
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+ dim: Optional[array_like]
+ Dimensions of the cuboid.
+ obstacles: Optional[array_like]
+ A list of lists of (x,y) coordinates. Each (x,y) coordinate is a length
+ and height relative to the x-,y- corner of the tank. Each list of
+ coordinates is an obstacle defined by points connected in the order of
+ their index. The list of lists gives all such obstacles in a
+ counterclockwise manner of which they should be appended, starting from
+ the (x-,y-) corner.
+ special_boundaries: Optional[mapping]
+ A dictionary of lists of vertices keyed to boundary names. The vertices
+ listed will be given the boundary name they are keyed to, overriding
+ any other designation they would be given.
+ If this is a distinct boundary name, the segment starting from the vertex
+ will be assigned the same boundary tag.
+ full_circle: Optional[bool]
+ A boolean tag to check if the final obstacle ends on the same edge that
+ the first obstacle starts on. Default is False.
+ coords: Optional[array_like]
+ Coordinates of the centroid of the shape.
+ hole: Optional[bool]
+ If True (default), the obstacle of the tank is just an open hole at the
+ bottom of the tank. If False, a segment at the bottom of the obstacle is
+ created to close the hole.
+ obstacle_regions: Optional[array_like]
+ To use only if hole=False.(x,y) coordinates of a point inside the
+ obstacle in order to fill the obstacle with what should be inside
+ (for example a porous material).
+
+ """
+
+ def __init__(self, domain, dim=(0., 0.),
+ obstacles=None, special_boundaries=None,
+ full_circle=False,
+ coords=None, hole=True, obstacle_regions=None):
+ if obstacles:
+ self.obstacles = obstacles
+ else:
+ self.obstacles = []
+
+ self.special_boundaries = []
+ self.special_BC_vertices = []
+ self.full_circle = full_circle
+
+ self.spongeLayers = {'x-': None,
+ 'x+': None}
+
+ if special_boundaries:
+ for key in list(special_boundaries.keys()):
+ self.special_boundaries += [key for v in special_boundaries[key]]
+ self.special_BC_vertices += special_boundaries[key]
+
+ self.corners = {'x-y-': False, 'x+y-': False,
+ 'x+y+': False, 'x-y+': False}
+
+ self.hole = hole
+ self.obstacle_regions = obstacle_regions
+ super(TankWithObstacles2D, self).__init__(domain, dim, coords)
+
+ def _setupBCs(self):
+ super(TankWithObstacles2D, self)._setupBCs()
+ for boundary in self.special_boundaries:
+ if boundary not in list(self.boundaryTags.keys()):
+ self.boundaryTags[boundary] = len(self.boundaryTags) + 1
+ self.BC[boundary] = self.BC_class(shape=self, name=boundary)
+ self.BC_list += [self.BC[boundary]]
+ # add boundaryTags
+ self.obstacle_flags = []
+ max_flag = 0
+ for tag, flag in list(self.boundaryTags.items()):
+ if flag > max_flag:
+ max_flag = flag
+ flag = max_flag + 1
+ for i in range(len(self.obstacles)):
+ tag = 'obstacle' + repr(i + 1)
+ self.boundaryTags[tag] = flag
+ self.obstacle_flags += [flag]
+ self.BC[tag] = self.BC_class(shape=self, name=tag)
+ self.BC_list += [self.BC[tag]]
+ flag += 1
+ if self.hole is False:
+ assert len(self.obstacles) == len(self.obstacle_regions), 'must have same number of regions as obstacles'
+
+ def _resetEdgesFromVertices(self, vertices):
+ """
+ Resets self.x0, self.x1, self.y0, self.y1 based on the actual shape.
+
+ In particular, they will form a bounding box form around the shape -
+ the furthest points in x and y dimensions, both high and low.
+
+ Parameters
+ ----------
+ vertices: array_like
+ """
+ sorted_vertices = sorted(vertices, key=lambda vertex: vertex[1])
+ self.y0 = sorted_vertices[0][1]
+ self.y1 = sorted_vertices[-1][1]
+ sorted_vertices = sorted(vertices, key=lambda vertex: vertex[0])
+ self.x0 = sorted_vertices[0][0]
+ self.x1 = sorted_vertices[-1][0]
+
+ def _findSpongeLayerCorners(self, vertices):
+ """
+ Finds the corners for horizontal (x-, x+) sponge layers.
+
+ Parameters
+ ----------
+ vertices: array_like
+ """
+ self._resetEdgesFromVertices(vertices)
+
+ potential_x_n_corners = [vertex for vertex in vertices
+ if np.isclose(vertex[0], self.x0)]
+ potential_x_p_corners = [vertex for vertex in vertices
+ if np.isclose(vertex[0], self.x1)]
+
+ potential_x_n_corners.sort(key=lambda vertex: vertex[1])
+ potential_x_p_corners.sort(key=lambda vertex: vertex[1])
+
+ self.x0y0 = potential_x_n_corners[0]
+ self.x0y1 = potential_x_n_corners[-1]
+ self.x1y0 = potential_x_p_corners[0]
+ self.x1y1 = potential_x_p_corners[-1]
+
+ def _constructVertices(self):
+
+ def getClockwiseOrder(first_point):
+ clockwise_ordering = ('x-y-', 'y-', 'x+y-', 'x+',
+ 'x+y+', 'y+', 'x-y+', 'x-')
+ index = clockwise_ordering.index(first_point)
+ return clockwise_ordering[index:] + clockwise_ordering[:index]
+
+ def findLocation(vertex):
+ """
+ Given an (x,y) coordinate gives a label associated to corner or edge
+ """
+ dim = [self.x1 - self.x0, self.y1 - self.y0]
+ if np.isclose(vertex[0], 0) and np.isclose(vertex[1], 0):
+ return 'x-y-'
+ elif np.isclose(vertex[0], dim[0]) and np.isclose(vertex[1], dim[1]):
+ return 'x+y+'
+ elif np.isclose(vertex[0], 0) and np.isclose(vertex[1], dim[1]):
+ return 'x-y+'
+ elif np.isclose(vertex[0], dim[0]) and np.isclose(vertex[1], 0):
+ return 'x+y-'
+ elif np.isclose(vertex[0], 0):
+ return 'x-'
+ elif np.isclose(vertex[0], dim[0]):
+ return 'x+'
+ elif np.isclose(vertex[1], 0):
+ return 'y-'
+ elif np.isclose(vertex[1], dim[1]):
+ return 'y+'
+ else:
+ raise ValueError("Point " + str(vertex) + " does not seem to"
+ "be on a tank wall.")
+
+ def checkClosure(start_point, end_point):
+ if start_point == end_point:
+ return True
+
+ def addCorner(corner_flag):
+ if corner_flag == 'x-y-':
+ corner = [[self.x0, self.y0]]
+ elif corner_flag == 'x+y-':
+ corner = [[self.x1, self.y0]]
+ elif corner_flag == 'x+y+':
+ corner = [[self.x1, self.y1]]
+ elif corner_flag == 'x-y+':
+ corner = [[self.x0, self.y1]]
+ # vertex flags
+ if corner_flag in ['x-y-', 'x+y-']:
+ corner_tag = [self.boundaryTags['y-']]
+ else:
+ corner_tag = [self.boundaryTags['y+']]
+
+ return corner, corner_tag
+
+ def addIntermediateCorners(first, last):
+ """
+ Returns corner vertices (and flags) in between two segments
+ """
+ ordering = getClockwiseOrder(first)
+ corners = [x for x in ordering
+ if x in list(self.corners.keys())
+ and ordering.index(x) < ordering.index(last)
+ ]
+ corner_vertices = []
+ corner_flags = []
+
+ for corner in corners:
+ self.corners[corner] = True
+ vertex, flag = addCorner(corner)
+ corner_vertices += vertex
+ corner_flags += flag
+
+ return corner_vertices, corner_flags
+
+ def addRemainingCorners(first, last):
+ if first == last:
+ if self.full_circle:
+ return []
+ else:
+ return addAllCorners(first)
+ else:
+ return addIntermediateCorners(first, last)
+
+ def addAllCorners(starting_point):
+ """
+ Returns all corners and flags.
+ """
+ corner_vertices = []
+ corner_flags = []
+
+ ordering = getClockwiseOrder(starting_point)
+
+ for potential_corner in ordering:
+ if potential_corner in list(self.corners.keys()):
+ self.corners[potential_corner] = True
+ vertex, flag = addCorner(potential_corner)
+ corner_vertices += vertex
+ corner_flags += flag
+
+ return corner_vertices, corner_flags
+
+ def addSpongeVertices():
+ sponge_vertices = []
+ sponge_vertexFlags = []
+ if self.spongeLayers['x-']:
+ sponge_vertices += [[v[0] - self.spongeLayers['x-'], v[1]]
+ for v in [self.x0y0, self.x0y1]]
+ sponge_vertexFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]
+ if self.spongeLayers['x+']:
+ sponge_vertices += [[v[0] + self.spongeLayers['x+'], v[1]]
+ for v in [self.x1y0, self.x1y1]]
+ sponge_vertexFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]
+ return sponge_vertices, sponge_vertexFlags
+
+ #--------------------------------------------------------#
+ vertices = []
+ vertexFlags = []
+ former_end = None
+ first_start = None
+
+ for nb, obstacle in enumerate(self.obstacles):
+ start = findLocation(obstacle[0])
+ end = findLocation(obstacle[-1])
+
+ if start == end and checkClosure(obstacle[0], obstacle[-1]):
+ raise ValueError("Obstacles must be open (start and end"
+ " vertices must be distinct)")
+ if start == former_end and checkClosure(obstacle[0], vertices[-1]):
+ vertices.pop()
+ vertexFlags.pop()
+
+ # ---- In-Between Corner Vertices ---- #
+ if former_end is not None:
+ new_vertices, new_flags = addIntermediateCorners(former_end, start)
+ vertices += new_vertices
+ vertexFlags += new_flags
+
+ # ---- Obstacle ---- #
+ if self.hole is True:
+ vertices += obstacle
+ vertexFlags += [self.boundaryTags[start]
+ for i in range(len(obstacle))]
+ elif self.hole is False:
+ vertices += obstacle
+ vertexFlags += [self.boundaryTags['obstacle' + repr(nb + 1)]
+ for i in range(len(obstacle))]
+
+ # ---- Paperwork ---- #
+ former_end = end
+ if first_start is None:
+ first_start = start
+
+ # ---- Remaining Corner Vertices ---- #
+ if first_start is not None:
+ new_vertices, new_flags = addRemainingCorners(former_end,
+ first_start)
+ else:
+ new_vertices, new_flags = addAllCorners('x-')
+
+ vertices += new_vertices
+ vertexFlags += new_flags
+
+ # ---- Check for Special Conditions ---- #
+ for vertex in self.special_BC_vertices:
+ flag_index = vertices.index(vertex)
+ boundary_index = self.special_BC_vertices.index(vertex)
+ boundary_name = self.special_boundaries[boundary_index]
+ vertexFlags[flag_index] = self.boundaryTags[boundary_name]
+
+ # ---- Adjustments for Sponge Zones ---- #
+ self._findSpongeLayerCorners(vertices=vertices)
+
+ # ---- Add Sponge Zone Vertices ---- #
+ new_vertices, new_flags = addSpongeVertices()
+ vertices += new_vertices
+ vertexFlags += new_flags
+
+ return vertices, vertexFlags
+
+ def _constructSegments(self, vertices, vertexFlags):
+ # VertexFlag --> SegmentFlag logic:
+ #
+ # if EITHER are x+ --> segment is x+
+ # UNLESS the other is x- --> y+
+ # if EITHER are x- --> segment is x-
+ # UNLESS the other is x+ --> y-
+ # if it STARTS y- --> segment is y-
+ # UNLESS they are vertical --> x+
+ # if it STARTS y+ --> segment is y+
+ # UNLESS they are vertical --> x-
+ # if BOTH are *** --> segment is ***
+ # (if two different *** are around, it takes the first)
+ segments = []
+ segmentFlags = []
+
+ on_sponge_edge = {'x-': False, 'x+': False}
+ sponge_edges_covered = {'x-': False, 'x+': False}
+
+ def checkSpongeStatus(start_index, end_index):
+ start_vertex = vertices[start_index]
+ if self.spongeLayers['x-']:
+ if not on_sponge_edge['x-']:
+ if start_vertex in (self.x0y0, self.x0y1):
+ on_sponge_edge['x-'] = True
+ elif not sponge_edges_covered['x-']:
+ if start_vertex in (self.x0y0, self.x0y1):
+ on_sponge_edge['x-'] = False
+ sponge_edges_covered['x-'] = True
+ else:
+ vertexFlags[start_index] = self.boundaryTags['sponge']
+ else:
+ pass
+
+ if self.spongeLayers['x+']:
+ if not on_sponge_edge['x+']:
+ if start_vertex in (self.x1y0, self.x1y1):
+ on_sponge_edge['x+'] = True
+ elif not sponge_edges_covered['x+']:
+ if start_vertex in (self.x1y0, self.x1y1):
+ on_sponge_edge['x+'] = False
+ sponge_edges_covered['x+'] = True
+ else:
+ vertexFlags[start_index] = self.boundaryTags['sponge']
+ else:
+ pass
+
+ end_vertex = vertices[end_index]
+ if on_sponge_edge['x-']:
+ if end_vertex not in (self.x0y0, self.x0y1):
+ vertexFlags[end_index] = self.boundaryTags['sponge']
+ if on_sponge_edge['x+']:
+ if end_vertex not in (self.x1y0, self.x1y1):
+ vertexFlags[end_index] = self.boundaryTags['sponge']
+
+ def getSegmentFlag(start, end):
+ if ((self.spongeLayers['x-'] and not sponge_edges_covered['x-']) or
+ (self.spongeLayers['x+'] and not sponge_edges_covered['x+'])):
+ checkSpongeStatus(start, end)
+
+ if on_sponge_edge['x-'] or on_sponge_edge['x+']:
+ return [self.boundaryTags['sponge'], ]
+
+ else:
+ if vertexFlags[start] in self.obstacle_flags:
+ if vertexFlags[end] == vertexFlags[start]:
+ return [vertexFlags[start], ]
+ else:
+ return [self.boundaryTags['y-'], ]
+ elif vertexFlags[start] == self.boundaryTags['x+']:
+ if vertexFlags[end] == self.boundaryTags['x-']:
+ return [self.boundaryTags['y+'], ]
+ else:
+ return [self.boundaryTags['x+'], ]
+
+ elif vertexFlags[start] == self.boundaryTags['x-']:
+ if vertexFlags[end] == self.boundaryTags['x+']:
+ return [self.boundaryTags['y-'], ]
+ else:
+ return [self.boundaryTags['x-'], ]
+
+ elif vertexFlags[end] == self.boundaryTags['x+']:
+ if vertexFlags[start] in [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]:
+ return [self.boundaryTags['x+'], ]
+
+ elif vertexFlags[end] == self.boundaryTags['x-']:
+ if vertexFlags[start] in [self.boundaryTags['y-'],
+ self.boundaryTags['y+']]:
+ return [self.boundaryTags['x-'], ]
+
+ elif vertexFlags[start] == self.boundaryTags['y-']:
+ if (vertexFlags[end] == self.boundaryTags['y+']
+ and np.isclose(vertices[start][0], vertices[end][0])
+ ):
+ return [self.boundaryTags['x+'], ]
+ else:
+ return [self.boundaryTags['y-'], ]
+
+ elif vertexFlags[start] == self.boundaryTags['y+']:
+ if (vertexFlags[end] == self.boundaryTags['y-']
+ and np.isclose(vertices[start][0], vertices[end][0])
+ ):
+ return [self.boundaryTags['x-'], ]
+ else:
+ return [self.boundaryTags['y+'], ]
+
+ else:
+ return [vertexFlags[start], ]
+
+ # ---- Initial Sponge Logic ---- #
+ sponge_vertex_count = 0
+
+ if self.spongeLayers['x-']:
+ sponge_vertex_count += 2
+ if self.spongeLayers['x+']:
+ sponge_vertex_count += 2
+
+ # ---- Build Main Segments ---- #
+ for i in range(len(vertices) - 1 - sponge_vertex_count):
+ segments += [[i, i + 1], ]
+ segmentFlags += getSegmentFlag(i, i + 1)
+ segments += [[len(vertices) - 1 - sponge_vertex_count, 0], ]
+ segmentFlags += getSegmentFlag(len(vertices) - 1 - sponge_vertex_count,
+ 0)
+ if self.hole is False:
+ start_vertex_obstacle = 0
+ for obstacle in self.obstacles:
+ segments += [[start_vertex_obstacle, start_vertex_obstacle + (len(obstacle) - 1)]]
+ segmentFlags += [self.boundaryTags['y-']]
+ start_vertex_obstacle += len(obstacle)
+
+ # ---- Build Sponge Segments ---- #
+ if self.spongeLayers['x-']:
+ segments += [[vertices.index(self.x0y0),
+ len(vertices) - sponge_vertex_count],
+ [len(vertices) - sponge_vertex_count,
+ len(vertices) - sponge_vertex_count + 1],
+ [len(vertices) - sponge_vertex_count + 1,
+ vertices.index(self.x0y1)]
+ ]
+ segmentFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['x-'],
+ self.boundaryTags['y+']]
+ if self.spongeLayers['x+']:
+ segments += [[vertices.index(self.x1y0), len(vertices) - 2],
+ [len(vertices) - 2, len(vertices) - 1],
+ [len(vertices) - 1, vertices.index(self.x1y1)]
+ ]
+ segmentFlags += [self.boundaryTags['y-'],
+ self.boundaryTags['x+'],
+ self.boundaryTags['y+']]
+
+ return segments, segmentFlags
+
+ def _constructRegions(self, vertices, vertexFlags, segments, segmentFlags):
+
+ ind_region = 0
+ self.regionIndice = {}
+ regions = []
+ regionFlags = []
+
+ if self.hole is False:
+ for i, region in enumerate(self.obstacle_regions):
+ regions = [[region[0], region[1]]]
+ ind_region += 1
+ regionFlags = [ind_region, ]
+ self.regionIndice['obstacle' + repr(i + 1)] = ind_region - 1
+
+ if True in list(self.corners.values()):
+ regions += self._getCornerRegion()
+ else:
+ regions += self._getRandomRegion(vertices, segments)
+
+ ind_region += 1
+ regionFlags += [ind_region]
+ self.regionIndice['tank'] = ind_region - 1
+
+ sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
+ sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
+ sponge_x0 = self.x0y0[0]
+ sponge_x1 = self.x1y0[0]
+
+ if self.spongeLayers['x-']:
+ regions += [[sponge_x0 - 0.5 * self.spongeLayers['x-'],
+ sponge_half_height_x0]]
+ ind_region += 1
+ regionFlags += [ind_region]
+ self.regionIndice['x-'] = ind_region - 1
+ if self.spongeLayers['x+']:
+ regions += [[sponge_x1 + 0.5 * self.spongeLayers['x+'],
+ sponge_half_height_x1]]
+ ind_region += 1
+ regionFlags += [ind_region]
+ self.regionIndice['x+'] = ind_region - 1
+
+ return regions, regionFlags
+
+ def _findExtrema(self, points):
+ """
+ Return the extrema of a series of points in n dimensions in the form:
+ max(x1), max(x2), ... , max(xn), min(x1), ... , min(xn)
+ """
+ points = np.array(points)
+ return np.max(points, 0).tolist() + np.min(points, 0).tolist()
+
+ def _getCornerRegion(self):
+ eps = np.finfo(float).eps
+ if self.corners['x-y-']:
+ return [[self.x0 + eps, self.y0 + eps], ]
+ elif self.corners['x+y-']:
+ return [[self.x1 - eps, self.y0 + eps], ]
+ elif self.corners['x+y+']:
+ return [[self.x1 - eps, self.y1 - eps], ]
+ elif self.corners['x-y+']:
+ return [[self.x0 + eps, self.y1 - eps], ]
+
+ def _getRandomRegion(self, vertices, segments):
+ x_p, y_p, x_n, y_n = self._findExtrema(vertices)
+ if self.spongeLayers['x-']:
+ x_n += self.spongeLayers['x-']
+ if self.spongeLayers['x+']:
+ x_p -= self.spongeLayers['x+']
+
+ count = 0
+ allowed_tries = 100
+
+ while True:
+ count += 1
+ vertical_line = np.random.uniform(x_n, x_p)
+ if True in [np.isclose(vertical_line, vertex[0]) for vertex in
+ vertices]:
+ continue
+
+ lowest_intersect = second_intersect = y_p
+
+ for segment in segments:
+ line_x0 = vertices[segment[0]][0]
+ line_y0 = vertices[segment[0]][1]
+ line_x1 = vertices[segment[1]][0]
+ line_y1 = vertices[segment[1]][1]
+ if (line_x0 < vertical_line < line_x1
+ or line_x0 > vertical_line > line_x1):
+ # (due to the strict inequality check and
+ # our selection of vertical_line - x1 > x0 should be sure)
+ intersection_height = line_y0 + (
+ (line_y1 - line_y0)
+ * (vertical_line - line_x0)
+ / (line_x1 - line_x0)
+ )
+ if intersection_height < lowest_intersect:
+ second_intersect = lowest_intersect
+ lowest_intersect = intersection_height
+ elif intersection_height < second_intersect:
+ second_intersect = intersection_height
+
+ interior_point = 0.5 * (lowest_intersect + second_intersect)
+
+ if lowest_intersect < interior_point < second_intersect:
+ break
+ if count > allowed_tries:
+ ValueError(
+ "Cannot find a proper interior point of the defined "
+ "shape after " + str(count) + " tries.")
+
+ return [[vertical_line, interior_point], ]
+
+ def setAbsorptionZones(self, dragAlpha, x_n=False, x_p=False,
+ dragBeta=0., porosity=1.):
+ """
+ Sets regions (x+, x-) to absorption zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient
+ allSponge: bool
+ If True, all sponge layers are converted to absorption zones.
+ x_p: bool
+ If True, x+ region is converted to absorption zone.
+ x_n: bool
+ If True, x- region is converted to absorption zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
+ sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
+ sponge_x0 = self.x0y0[0]
+ sponge_x1 = self.x1y0[0]
+
+ waves = None
+ wind_speed = np.array([0., 0., 0.])
+ if x_n or x_p:
+ self._attachAuxiliaryVariable('RelaxZones')
+ if x_n is True:
+ center = np.array([sponge_x0 - 0.5 * self.spongeLayers['x-'],
+ sponge_half_height_x0, 0.])
+ ind = self.regionIndice['x-']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x-']/2.
+ orientation = np.array([1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity)
+ if x_p is True:
+ center = np.array([sponge_x1 + 0.5 * self.spongeLayers['x+'],
+ sponge_half_height_x1, 0.])
+ ind = self.regionIndice['x+']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x+']/2.
+ orientation = np.array([-1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='absorption',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity)
+
+ def setGenerationZones(self, dragAlpha, smoothing, waves=None,
+ wind_speed=(0., 0., 0.), x_n=False, x_p=False,
+ dragBeta=0., porosity=1.):
+ """
+ Sets regions (x+, x-) to generation zones
+
+ Parameters
+ ----------
+ dragAlpha: float
+ Relaxation zone coefficient.
+ smoothing: float
+ Smoothing distance (typically 3*he)
+ waves: proteus.WaveTools
+ Class instance of wave generated from proteus.WaveTools.
+ wind_speed: Optional[array_like]
+ Speed of wind in generation zone (default is (0., 0., 0.))
+ allSponge: bool
+ If True, all sponge layers are converted to generation zones.
+ x_p: bool
+ If True, x+ region is converted to generation zone.
+ x_n: bool
+ If True, x- region is converted to generation zone.
+ dragBeta: Optional[float]
+ Relaxation zone coefficient.
+ porosity: Optional[float]
+ Relaxation zone coefficient.
+ """
+ sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
+ sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
+ sponge_x0 = self.x0y0[0]
+ sponge_x1 = self.x1y0[0]
+
+ waves = waves
+ wind_speed = np.array(wind_speed)
+ if x_n or x_p:
+ self._attachAuxiliaryVariable('RelaxZones')
+ if x_n is True:
+
+ center = np.array([sponge_x0 - 0.5 * self.spongeLayers['x-'],
+ sponge_half_height_x0, 0.])
+ ind = self.regionIndice['x-']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x-']/2.
+ orientation = np.array([1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity,
+ smoothing=smoothing)
+ self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+ if x_p is True:
+
+ center = np.array([sponge_x1 + 0.5 * self.spongeLayers['x+'],
+ sponge_half_height_x1, 0.])
+ ind = self.regionIndice['x+']
+ flag = self.regionFlags[ind]
+ epsFact_porous = self.spongeLayers['x+']/2.
+ orientation = np.array([-1., 0.])
+ self.zones[flag] = bc.RelaxationZone(shape=self,
+ zone_type='generation',
+ orientation=orientation,
+ center=center,
+ waves=waves,
+ wind_speed=wind_speed,
+ epsFact_porous=epsFact_porous,
+ dragAlpha=dragAlpha,
+ dragBeta=dragBeta,
+ porosity=porosity,
+ smoothing=smoothing)
+ self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
+ wind_speed=wind_speed,
+ smoothing=smoothing)
+
+
+
+def assembleDomain(domain):
+ """
+ This function sets up everything needed for the domain, meshing, and
+ AuxiliaryVariables calculations (if any).
+ It should always be called after defining and manipulating all the shapes
+ to be attached to the domain.
+
+ If any shape of the domain is a ShapeRANS (the predefined shapes are, once this module is imported; so are
+ Tank2D, Tank3D and TankWithObstacles2D) the two-phase flow boundary conditions (BC_RANS) are used, the
+ boundary between processors is set non-material, the auxiliary variables of the shapes are assembled and the
+ mesh is generated unless the domain is a PUMIDomain. A domain without such a shape gets the generic boundary
+ conditions (BC_Base) and a mesh.
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+ """
+ if any(isinstance(shape, ShapeRANS) for shape in domain.shape_list):
+ _assembleGeometry(domain, BC_class=bc.BC_RANS)
+ domain.BCbyFlag[0].setNonMaterial() # set BC for boundary between processors
+ assembleAuxiliaryVariables(domain)
+ if(domain.name != "PUMIDomain"):
+ _generateMesh(domain)
+ else:
+ # reinitialize geometry of domain
+ _assembleGeometry(domain, BC_class=bc.BC_Base)
+ _generateMesh(domain)
+
+
+def assembleAuxiliaryVariables(domain):
+ """
+ Adds the auxiliary variables to the domain.
+
+ Parameters
+ ----------
+ domain: proteus.Domain.D_base
+ Domain class instance that hold all the geometrical informations and
+ boundary conditions of the shape.
+
+ Notes
+ -----
+ Should be called after assembleGeometry
+ """
+
+ domain.auxiliaryVariables = {
+ 'dissipation': [],
+ 'kappa': [],
+ 'ls': [],
+ 'ls_consrv': [],
+ 'moveMesh': [],
+ 'redist': [],
+ 'twp': [],
+ 'vof': [],
+ 'thp': [],
+ 'vos': [],
+ 'SWFlow' :[]
+ }
+
+ zones_global = {}
+ start_region = 0
+ start_rflag = 0
+ start_flag = 0
+ for shape in domain.shape_list:
+ aux = domain.auxiliaryVariables
+ # ----------------------------
+ # RIGID BODIES
+ if 'RigidBody' in list(shape.auxiliaryVariables.keys()):
+ body = shape.auxiliaryVariables['RigidBody']
+ aux['twp'] += [body]
+ # fixing mesh on rigid body
+ for boundcond in shape.BC_list:
+ boundcond.setRigidBodyMoveMesh(body)
+ # update the indice for force/moment calculations
+ body.i_start = start_flag + 1
+ body.i_end = start_flag + 1 + len(shape.BC_list)
+ if 'ChRigidBody' in list(shape.auxiliaryVariables.keys()):
+ body = shape.auxiliaryVariables['ChRigidBody']
+ for boundcond in shape.BC_list:
+ boundcond.setChMoveMesh(body)
+ if body.boundaryFlags.size == 0:
+ flags = []
+ for tag, flag in shape.boundaryTags.items():
+ flags += [start_flag+flag]
+ body.setBoundaryFlags(flags)
+ if 'WallFunction' in list(shape.auxiliaryVariables.keys()):
+ wall = shape.auxiliaryVariables['WallFunction']
+ for ii in range(len(wall)):
+ aux['twp'] += [wall[ii]]
+ logEvent('WALL ATTACHED TO AUXVAR --> %s' % wall[ii])
+ if 'kWallFunction' in list(shape.auxiliaryVariables.keys()):
+ kWall = shape.auxiliaryVariables['kWallFunction']
+ for ii in range(len(kWall)):
+ aux['kappa'] += [kWall[ii]]
+ logEvent('kWALL ATTACHED TO AUXVAR --> %s' % kWall[ii])
+ # ----------------------------
+ # ABSORPTION/GENERATION ZONES
+
+ if 'RelaxZones' in list(shape.auxiliaryVariables.keys()):
+ if not zones_global:
+ aux['twp'] += [bc.RelaxationZoneWaveGenerator(zones_global,
+ domain.nd)]
+ # add relaxation zones to SWFlow AuxiliaryVariables
+ aux['SWFlow'] += [bc.RelaxationZoneWaveGenerator(zones_global,
+ domain.nd)]
+ if not hasattr(domain, 'porosityTypes'):
+ # create arrays of default values
+ domain.porosityTypes = np.ones(len(domain.regionFlags) + 1)
+ domain.dragAlphaTypes = np.zeros(len(domain.regionFlags) + 1)
+ domain.dragBetaTypes = np.zeros(len(domain.regionFlags) + 1)
+ domain.epsFact_porous = np.zeros(len(domain.regionFlags) + 1)
+ i0 = start_region + 1
+ for flag, zone in list(shape.zones.items()):
+ ind = [i for i, f in enumerate(shape.regionFlags) if f == flag]
+ for i1 in ind:
+ domain.porosityTypes[i0 + i1] = zone.porosity
+ domain.dragAlphaTypes[i0 + i1] = zone.dragAlpha
+ domain.dragBetaTypes[i0 + i1] = zone.dragBeta
+ domain.epsFact_porous[i0 + i1] = zone.epsFact_porous
+ # update dict with global key instead of local key
+ key = flag + start_rflag
+ zones_global[key] = zone
+ start_flag += len(shape.BC_list)
+ # ----------------------------
+ # GAUGES
+ gauge_dict = {key: shape.auxiliaryVariables.get(key, [])
+ for key in list(shape.auxiliaryVariables.keys())
+ if str(key).startswith('Gauge_')}
+ for key in list(gauge_dict.keys()):
+ key_name = key.split('_', 1)[1] # Cutting off "Gauge_" prefix
+ if key_name not in aux:
+ # It is probably too dangerous to simply put "aux[key_name] = []"
+ # as this system is fragile to typos. Instead, we throw an error.
+ raise ValueError('ERROR: Gauge key ',
+ key_name,
+ ' is not a recognized model by SpatialTools.',
+ ' The known models in our dictionary are ',
+ str(list(aux.keys()))
+ )
+ else:
+ aux[key_name] += gauge_dict[key]
+ if shape.regions is not None:
+ start_region += len(shape.regions)
+ start_rflag = max(domain.regionFlags[0:start_region])
+
+
+def get_unit_vector(vector):
+ return np.array(vector)/np.linalg.norm(vector)
diff --git a/proteus/SplitOperator.py b/proteus/SplitOperator.py
index 70e74ee792..af48d46251 100644
--- a/proteus/SplitOperator.py
+++ b/proteus/SplitOperator.py
@@ -6,6 +6,7 @@
"""
import numpy
from .Profiling import logEvent
+from .Comm import globalMax
class System(object):
def __init__(self):
@@ -1016,3 +1017,53 @@ def initialize_dt_system(self,t0,tOut):
(self.system.name,
self.stepSequence),
level=1)
+
+
+# From the 2012 gwvd decks (erdc/proteus-gwvd@14961d2 src/Gwvd_consolidated_classes.py), moved here from proteus/gwvd.
+
+class ISO_fixed_MinModelStep(ISO_fixed_MinAdaptiveModelStep):
+ """
+ Iterate flow and transport within a step (Povich 2013, Sec. 4.5) until the max norm of the owned
+ residuals of both models is below atol_iso, then advance.
+ """
+
+ def __init__(self, modelList, system=defaultSystem, stepExact=False, atol_iso=1.e-8):
+ ISO_fixed_MinAdaptiveModelStep.__init__(self, modelList, system, stepExact)
+ self.atol_iso = atol_iso
+ self.convergence_flag = False
+ self.velocity_Postprocess = False
+
+ def setFromOptions(self, soOptions):
+ self.velocity_Postprocess = False
+ if 'atol_iso' in dir(soOptions):
+ self.atol_iso = soOptions.atol_iso
+ if 'velocity_Postprocess' in dir(soOptions):
+ self.velocity_Postprocess = soOptions.velocity_Postprocess
+
+ def converged(self):
+ if self.convergence_flag and self.its != 0:
+ self.its = 0
+ self.convergence_flag = False
+ return True
+ return False
+
+ def SysNorm(self, rSys):
+ # The 2012 code takes the signed maximum of each residual (not max |r|), so negative
+ # residuals never block convergence. Kept for fidelity with the published runs.
+ return max(globalMax(float(r.max())) for r in rSys)
+
+ def sequenceTaken(self):
+ self.its += 1
+ rSys = []
+ for model in self.modelList:
+ lm = model.levelModelList[-1]
+ lm.getResidual(model.uList[-1], model.rList[-1])
+ rSys.append(model.rList[-1][:lm.mesh.subdomainMesh.nNodes_owned])
+ rNorm = self.SysNorm(rSys)
+ logEvent("ISO iteration %d: max residual %12.5e (atol_iso %12.5e)" % (self.its, rNorm, self.atol_iso), level=1)
+ if rNorm < self.atol_iso and self.its != 0:
+ self.convergence_flag = True
+ if self.convergence_flag:
+ for model in self.modelList:
+ model.stepController.updateTimeHistory()
+ model.stepController.choose_dt_model()
diff --git a/proteus/StepControl.py b/proteus/StepControl.py
index b4f5541161..749226610d 100644
--- a/proteus/StepControl.py
+++ b/proteus/StepControl.py
@@ -1355,3 +1355,37 @@ def stepExact_model(self,tOut):
self.set_dt_allLevels()
#self.substeps = [self.t_model]
self.setSubsteps([self.t_model])
+
+
+# From the 2012 gwvd decks (erdc/proteus-gwvd@14961d2 src/Gwvd_consolidated_classes.py), moved here from proteus/gwvd.
+
+class Fixed_dt_controller_systemit(Min_dt_controller):
+ """Fixed model step dt = nOptions.DT, for the iterated (ISO) coupling of flow and transport."""
+
+ def __init__(self, model, nOptions):
+ Min_dt_controller.__init__(self, model, nOptions)
+ self.dt = nOptions.DT
+ self.dt_model_last = None
+ model.levelModelList[-1].timeIntegration.isAdaptive = True # needed by the ISO controller
+
+ def initialize_dt_model(self, t0, tOut):
+ self.saveSolution()
+ self.dt_model = self.dt
+ if self.dt_model_last is None:
+ self.dt_model_last = self.dt_model
+ self.set_dt_allLevels()
+ self.substeps = [self.t_model]
+ logEvent("Initializing time step on model %s to dt = %12.5e" % (self.model.name, self.dt_model), level=1)
+
+ def choose_dt_model(self):
+ self.solverFailures = 0
+ self.errorFailures = 0
+ self.saveSolution()
+ self.dt_model = self.dt
+ if self.dt_model_last is None:
+ self.dt_model_last = self.dt_model
+ self.set_dt_allLevels()
+ self.setSubsteps([self.t_model])
+
+ def stepExact_model(self, tOut):
+ pass
diff --git a/proteus/TimeIntegration.py b/proteus/TimeIntegration.py
index 506ff0043c..ee44d1e434 100644
--- a/proteus/TimeIntegration.py
+++ b/proteus/TimeIntegration.py
@@ -4308,4 +4308,62 @@ def calculateCoefs(self):
self.beta_bdf[ci].flat[:] -= self.mt1_last[ci].flat
+# From the 2012 gwvd decks (erdc/proteus-gwvd@14961d2 src/Gwvd_consolidated_classes.py), moved here from proteus/gwvd.
+
+class NonConservativeBackwardEuler(BackwardEuler):
+ """Backward Euler on the primary variable: m_t = dm (u - u_last)/dt, with dm frozen at the new iterate.
+
+ Until the time history is initialized, m_t is reported as zero. Current proteus spins up model 0
+ (the flow) before the transport history exists, when u_last is still zero and dt is the default
+ 1.0; the flow source omega (drho/dc) c_t / rho would then see a fictitious c_t = omega rho c.
+ """
+
+ def __init__(self, transport, integrateInterpolationPoints=False):
+ BackwardEuler.__init__(self, transport,
+ integrateInterpolationPoints=integrateInterpolationPoints)
+ self.historyInitialized = False
+
+ def initializeTimeHistory(self, resetFromDOF=True):
+ BackwardEuler.initializeTimeHistory(self, resetFromDOF)
+ self.historyInitialized = True
+
+ def calculateElementCoefficients(self, q):
+ self.calculateCoefs()
+ if not self.historyInitialized:
+ for ci in self.m_last.keys():
+ self.m_tmp[ci][:] = q[('u', ci)]
+ q[('mt', ci)].fill(0.0)
+ return
+ for ci in self.m_last.keys():
+ self.m_tmp[ci][:] = q[('u', ci)]
+ q[('mt', ci)][:] = q[('u', ci)]
+ q[('mt', ci)] -= self.m_last[ci]
+ q[('mt', ci)] /= self.dt
+ q[('mt', ci)] *= q[('dm', ci, ci)]
+ for cj in range(self.nc):
+ if ('dmt', ci, cj) in q:
+ q[('dmt', ci, cj)][:] = q[('dm', ci, cj)]
+ q[('dmt', ci, cj)] /= self.dt
+ if ('dm_sge', ci, cj) in q and ('dmt_sge', ci, cj) in q:
+ q[('dmt_sge', ci, cj)][:] = q[('dm_sge', ci, cj)]
+ q[('dmt_sge', ci, cj)] /= self.dt
+
+ def calculateGeneralizedInterpolationCoefficients(self, cip):
+ if not self.integrateInterpolationPoints:
+ return
+ for ci in self.m_ip_last.keys():
+ self.m_ip_tmp[ci][:] = cip[('u', ci)]
+ cip[('mt', ci)][:] = cip[('u', ci)]
+ cip[('mt', ci)] -= self.m_ip_last[ci]
+ cip[('mt', ci)] /= self.dt
+ cip[('mt', ci)] *= cip[('dm', ci, ci)]
+ for cj in range(self.nc):
+ if ('dmt', ci, cj) in cip:
+ cip[('dmt', ci, cj)][:] = cip[('dm', ci, cj)]
+ cip[('dmt', ci, cj)] /= self.dt
+ if ('dmt_sge', ci, cj) in cip:
+ cip[('dmt_sge', ci, cj)][:] = cip[('dm_sge', ci, cj)]
+ cip[('dmt_sge', ci, cj)] /= self.dt
+
+
## @}
diff --git a/proteus/TransportCoefficients.py b/proteus/TransportCoefficients.py
index a240604b66..d267b93327 100644
--- a/proteus/TransportCoefficients.py
+++ b/proteus/TransportCoefficients.py
@@ -10258,4 +10258,263 @@ def evaluate(self,t,c):
c[('df',2,3)],
c[('df',3,1)],
c[('df',3,2)],
- c[('df',3,3)])
\ No newline at end of file
+ c[('df',3,3)])
+
+
+########################################################################
+# Variable-density groundwater flow and transport (continuous Galerkin path), from proteus/gwvd.
+# Ported from erdc/proteus-gwvd@14961d2 (src/GwvdCoefficients.py, src/gwvdCoefficients.c; Povich et al. 2013,
+# Comput. Geosci. 17:529). Primary variables: the freshwater head h and the normalized mass fraction c (`mf`).
+# The flow "velocity" handed to transport is the mass flux rho*q from the flow model's velocity
+# post-processing (`conservativeFlux`). The C coefficient evaluators are reimplemented with numpy.
+########################################################################
+
+def density_eval(mf, epsilon, rho_fw):
+ """Linear density relation rho = rho_fw (1 + epsilon c)."""
+ return rho_fw * (1.0 + epsilon * mf)
+
+
+def var_visc(mf, mf_s):
+ """Relative viscosity of Lever & Jackson (1985), as in the 2012 code (a ratio, not a viscosity)."""
+ mf_a = mf * mf_s
+ return 1.0 + 1.85 * mf_a - 4.1 * mf_a**2 + 44.5 * mf_a**3
+
+
+def knabnerFrolkovicConsistentVelCorrection_Triangle_P1(epsilon, c_l2g, c_dof, J, Jinv, gravity,
+ q_rhog_consistent, eps_tol=1.0e-9):
+ """Knabner-Frolkovic (1996) consistent rho*g on P1 triangles, Eqs. 3.3-3.16.
+
+ Writes J^{-T} hhat into q_rhog_consistent (nElements x 2), where hhat holds the reference-element
+ derivatives of the integrated buoyancy term. For the linear density used here the exact integral
+ is the mean of the two vertex values, which is what the 2012 C code evaluates.
+ """
+ JeT = numpy.swapaxes(J[:, 0], 1, 2)
+ JeTinv = numpy.swapaxes(Jinv[:, 0], 1, 2)
+ ghat = numpy.einsum('eij,j->ei', JeT, gravity)
+ c_e = c_dof[c_l2g[:, :3]]
+ h1 = numpy.where(numpy.abs(c_e[:, 1] - c_e[:, 0]) <= eps_tol,
+ epsilon * c_e[:, 0], 0.5 * epsilon * (c_e[:, 1] + c_e[:, 0]))
+ h2 = numpy.where(numpy.abs(c_e[:, 2] - c_e[:, 0]) <= eps_tol,
+ epsilon * c_e[:, 0], 0.5 * epsilon * (c_e[:, 2] + c_e[:, 0]))
+ h_hat = numpy.stack([ghat[:, 0] * h1, ghat[:, 1] * h2], axis=1)
+ q_rhog_consistent[:] = numpy.einsum('eij,ej->ei', JeTinv, h_hat)
+
+
+class VariableDensity_mod2_FlowEquationCoefficients(TC_base):
+ """
+ Variable-density subsurface flow in non-divergence (mod2) form for the freshwater head h:
+
+ S rho h_t + div(f - a grad h) + r = 0,
+ a = k rho_fw g rho / mu, f = -a epsilon c e_z (or -a (rho g)~ with the consistent velocity),
+ r = omega (drho/dc) c_t / rho.
+
+ The mass fraction c and its time derivative come from the transport model.
+ """
+
+ def __init__(self, aOfX=None, rOfX=None, bOfX=None, S=1.0, omega=.3, epsilon=.025, rho_fw=1000.0,
+ gc=9.8, Kx=1.0e-10, Ky=1.0e-10, Kz=1.0e-10, mu=1.0e-3, mf_s=0.167, drho_dmf=200.0,
+ rho_source=0.0, T_model=None, C_model=None, flowModelIndex=0, transModelIndex=1,
+ cModelIndex=2, nc=1, nd=2, consistentVelocityFlag=0, consistentVelocityFunction=None,
+ variableViscosityFlag=0, rho_eval=None, rhoInt_eval=None, gravity=None,
+ getInterface=None, Height=1.0):
+ self.aOfX = aOfX
+ self.rOfX = rOfX
+ self.bOfX = bOfX
+ self.omega = omega
+ self.epsilon = epsilon
+ self.S = S
+ self.gc = gc
+ self.rho_fw = rho_fw
+ self.Kx = Kx
+ self.Ky = Ky
+ self.Kz = Kz
+ self.mu = mu
+ self.mf_s = mf_s
+ self.rho_source = rho_source
+ self.nd = nd
+ self.drho_dmf = drho_dmf
+ self.T_model = T_model
+ self.C_model = C_model
+ self.getInterface = getInterface
+ self.Height = Height
+ self.consistentVelocityFlag = consistentVelocityFlag # 0 none, 1 Knabner-Frolkovic 96
+ self.variableViscosityFlag = variableViscosityFlag
+ if C_model is not None:
+ raise NotImplementedError("surface-water coupling (C_model) is not ported")
+ if consistentVelocityFlag == 1 and nd != 2:
+ raise NotImplementedError("only the P1 triangle consistent velocity is ported")
+ mass, advection, diffusion, potential, reaction, hamiltonian = {}, {}, {}, {}, {}, {}
+ for i in range(nc):
+ mass[i] = {i: 'linear'}
+ advection[i] = {i: 'constant'}
+ diffusion[i] = {i: {i: 'constant'}}
+ potential[i] = {i: 'u'}
+ reaction[i] = {i: 'constant'}
+ TC_base.__init__(self, nc, mass, advection, diffusion, potential,
+ reaction, hamiltonian, variableNames=['h'])
+ self.transModelIndex = transModelIndex
+ self.flowModelIndex = flowModelIndex
+ self.cModelIndex = cModelIndex
+ self.q_mf = None
+ self.q_mfdt = None
+ self.ebqe_mf = None
+ self.ebqe_mfdt = None
+ self.ebq_mf = None
+ self.ebq_mfdt = None
+ self.consistentVelocityFunction = consistentVelocityFunction
+ self.q_rhog_consistent = None
+ self.rho_eval = rho_eval
+ self.rhoInt_eval = rhoInt_eval
+ self.gravity = gravity
+
+ def preStep(self, t, firstStep=False):
+ """Build the consistent rho*g from the current mass fraction, if requested."""
+ if self.consistentVelocityFlag == 1 and self.T_model is not None:
+ assert self.transModel.u[0].femSpace.isSpace('C0',('lagrange','bernstein'),1,'simplex')
+ knabnerFrolkovicConsistentVelCorrection_Triangle_P1(self.epsilon,
+ self.transModel.u[0].femSpace.dofMap.l2g,
+ self.transModel.u[0].dof,
+ self.model.q['J'],
+ self.model.q['inverse(J)'],
+ numpy.asarray(self.gravity, 'd'),
+ self.q_rhog_consistent)
+
+ def initializeMesh(self, mesh):
+ self.elementBoundaryElements = mesh.elementBoundaryElementsArray
+ self.exteriorElementBoundaries = mesh.exteriorElementBoundariesArray
+
+ def attachModels(self, modelList):
+ self.model = modelList[self.flowModelIndex]
+ if self.T_model is not None:
+ self.transModel = modelList[self.transModelIndex]
+ self.q_mf = self.transModel.q[('u', 0)]
+ self.q_mfdt = self.transModel.q[('mt', 0)]
+ self.ebqe_mf = self.transModel.ebqe[('u', 0)]
+ self.ebqe_mfdt = numpy.zeros(self.ebqe_mf.shape, 'd')
+ if ('u', 0) in self.transModel.ebq:
+ self.ebq_mf = self.transModel.ebq[('u', 0)]
+ self.ebq_mfdt = numpy.zeros(self.ebq_mf.shape, 'd')
+ if self.consistentVelocityFlag != 0:
+ self.q_rhog_consistent = numpy.zeros((self.q_mf.shape[0], self.nd), 'd')
+
+ def evaluate(self, t, c):
+ if self.q_mf is not None and c[('u', 0)].shape == self.q_mf.shape:
+ mf, mfdt, b_flag = self.q_mf, self.q_mfdt, 0
+ elif self.ebqe_mf is not None and c[('u', 0)].shape == self.ebqe_mf.shape:
+ mf, mfdt, b_flag = self.ebqe_mf, self.ebqe_mfdt, 1
+ elif self.ebq_mf is not None and c[('u', 0)].shape == self.ebq_mf.shape:
+ # as in 2012: element-boundary points have no c_t, so the coefficients are left unset
+ return
+ else:
+ raise RuntimeError("no mass fraction for points of shape %s" % (c[('u', 0)].shape,))
+ nd = self.nd
+ a = c[('a', 0, 0)]
+ assert a.shape[-1] == nd * nd, "expected full (non-sparse) diffusion storage"
+ density = density_eval(mf, self.epsilon, self.rho_fw)
+ logEvent("gwvd flow: t=%g b_flag=%d max|c_t|=%g" % (t, b_flag, numpy.abs(mfdt).max()), level=5)
+ c[('m', 0)][:] = c[('u', 0)] * self.S * density # replaced by the time integrator
+ c[('dm', 0, 0)][:] = self.S * density
+ c[('r', 0)][:] = self.drho_dmf * mfdt / density
+ K = [self.Kx, self.Ky, self.Kz][:nd]
+ denom = self.mu if self.variableViscosityFlag == 0 else var_visc(mf, self.mf_s)
+ a.fill(0.0)
+ for I in range(nd):
+ a[..., I * nd + I] = K[I] * self.gc * self.rho_fw * density / denom
+ f, df = c[('f', 0)], c[('df', 0, 0)]
+ df.fill(0.0)
+ if self.consistentVelocityFlag == 1:
+ if b_flag == 0:
+ rhog = self.q_rhog_consistent[:, numpy.newaxis, :]
+ else:
+ eN = self.elementBoundaryElements[self.exteriorElementBoundaries, 0]
+ rhog = self.q_rhog_consistent[eN][:, numpy.newaxis, :]
+ A = a.reshape(a.shape[:-1] + (nd, nd))
+ f[:] = -numpy.einsum('...ij,...j->...i', A, numpy.broadcast_to(rhog, f.shape))
+ else:
+ f.fill(0.0)
+ f[..., nd - 1] = -a[..., (nd - 1) * nd + nd - 1] * self.epsilon * mf
+
+
+class VDGroundwater_mod2_TransportCoefficients(TC_base):
+ """
+ Mass-fraction transport in advective (Hamilton-Jacobi) form driven by the flow model's mass flux v:
+
+ omega rho c_t + v . grad c - div(a grad c) = 0,
+ a = rho d omega I + alpha_T |v| I + (alpha_L - alpha_T) v v^T / |v|.
+ """
+
+ def __init__(self, nc=1, nd=2, omega=0.3, alpha_L=1.0, alpha_T=0.2, rho_fw=1000, d=1.3e-9,
+ epsilon=0.0, rho_source=0.0, mf_source=0.0, flowModelIndex=0, transModelIndex=1,
+ cModelIndex=2, C_Model=None, F_Model=0, getInterface=None, Height=1.0):
+ self.nd = nd
+ self.omega = omega
+ self.nc = nc
+ self.d = d
+ self.alpha_L = alpha_L
+ self.alpha_T = alpha_T
+ self.rho_fw = rho_fw
+ self.epsilon = epsilon
+ self.rho_source = rho_source
+ self.mf_source = mf_source
+ self.F_Model = F_Model
+ self.C_Model = C_Model
+ self.flowModelIndex = flowModelIndex
+ self.transModelIndex = transModelIndex
+ self.cModelIndex = cModelIndex
+ self.getInterface = getInterface
+ self.Height = Height
+ if C_Model is not None:
+ raise NotImplementedError("surface-water coupling (C_Model) is not ported")
+ mass, advection, diffusion, potential, reaction, hamiltonian = {}, {}, {}, {}, {}, {}
+ for i in range(nc):
+ mass[i] = {i: 'linear'}
+ advection[i] = {i: 'linear'}
+ diffusion[i] = {i: {i: 'constant'}}
+ potential[i] = {i: 'u'}
+ reaction[i] = {i: 'linear'}
+ hamiltonian[i] = {i: 'linear'}
+ TC_base.__init__(self, nc, mass, advection, diffusion, potential,
+ reaction, hamiltonian, variableNames=['mf'])
+
+ def attachModels(self, modelList):
+ self.model = modelList[self.transModelIndex]
+ if self.F_Model is not None:
+ flow = modelList[self.flowModelIndex]
+ self.flowModel = flow
+ self.q_v = flow.q[('velocity', 0)]
+ self.ebq_v = flow.ebq.get(('velocity', 0))
+ self.ebqe_v = flow.ebqe[('velocity', 0)]
+ self.ebq_global_v = flow.ebq_global.get(('velocity', 0))
+
+ def evaluate(self, t, c):
+ shape = c[('df', 0, 0)].shape
+ for v in (self.q_v, self.ebq_v, self.ebqe_v, self.ebq_global_v):
+ if v is not None and v.shape == shape:
+ break
+ else:
+ raise RuntimeError("no flow velocity for points of shape %s" % (shape,))
+ nd = self.nd
+ a = c[('a', 0, 0)]
+ assert a.shape[-1] == nd * nd, "expected full (non-sparse) diffusion storage"
+ u = c[('u', 0)]
+ density = density_eval(u, self.epsilon, self.rho_fw)
+ c[('m', 0)][:] = u # replaced by NonConservativeBackwardEuler: m_t = dm (u - u_last)/dt
+ c[('dm', 0, 0)][:] = self.omega * density
+ c[('r', 0)].fill(0.0)
+ c[('dr', 0, 0)].fill(0.0)
+ c[('f', 0)].fill(0.0)
+ c[('df', 0, 0)].fill(0.0)
+ c[('H', 0)][:] = numpy.einsum('...i,...i->...', c[('grad(u)', 0)], v)
+ c[('dH', 0, 0)][:] = v
+ norm_v = numpy.sqrt(numpy.einsum('...i,...i->...', v, v))
+ safe = numpy.where(norm_v > 0.0, norm_v, 1.0)
+ a.fill(0.0)
+ for I in range(nd):
+ a[..., I * nd + I] = (density * self.d * self.omega
+ + numpy.where(norm_v > 0.0,
+ self.alpha_T * norm_v
+ + (self.alpha_L - self.alpha_T) * v[..., I]**2 / safe, 0.0))
+ for J in range(I + 1, nd):
+ off = numpy.where(norm_v > 0.0, (self.alpha_L - self.alpha_T) * v[..., I] * v[..., J] / safe, 0.0)
+ a[..., I * nd + J] = off
+ a[..., J * nd + I] = off
diff --git a/proteus/TwoPhaseFlow/TwoPhaseFlowProblem.py b/proteus/TwoPhaseFlow/TwoPhaseFlowProblem.py
index b300492026..9742aaf28d 100644
--- a/proteus/TwoPhaseFlow/TwoPhaseFlowProblem.py
+++ b/proteus/TwoPhaseFlow/TwoPhaseFlowProblem.py
@@ -139,7 +139,7 @@ def assert_boundaryConditions(self):
# check diffusive flux BCs
assert 'pressure_increment_DFBC' in boundaryConditions,"Provide pressure_increment_DFBC"
else:
- assert self.domain.useSpatialTools is True, 'Either define boundaryConditions dict or use proteus.mprans.SpatialTools to set Boundary Conditions and run function assembleDomain'
+ assert self.domain.useSpatialTools is True, 'Either define boundaryConditions dict or use proteus.SpatialTools to set Boundary Conditions and run function assembleDomain'
def initializeAll(self):
@@ -231,7 +231,7 @@ def __init__(self,modelList,system=defaultSystem,stepExact=True):
def unattachedAuxiliaryVariables(domain_auxvars, model_list):
"""
The entries of domain.auxiliaryVariables (a dict of lists, as filled by
- proteus.mprans.SpatialTools.assembleDomain) that none of the models in
+ proteus.SpatialTools.assembleDomain) that none of the models in
model_list has in its auxiliaryVariables, as {key: [objects]}.
"""
if not isinstance(domain_auxvars, dict):
@@ -390,7 +390,7 @@ def __init__(self,ProblemInstance):
self.initialConditions = None
self.boundaryConditions=None
- # to use proteus.mprans.BoundaryConditions
+ # to use proteus.BoundaryConditions
# but only if SpatialTools was used to make the domain
self.useBoundaryConditionsModule = True
diff --git a/proteus/TwoPhaseFlow/utils/Parameters.py b/proteus/TwoPhaseFlow/utils/Parameters.py
index 3c0fa5fe7b..3fc77cc085 100644
--- a/proteus/TwoPhaseFlow/utils/Parameters.py
+++ b/proteus/TwoPhaseFlow/utils/Parameters.py
@@ -14,7 +14,8 @@
parallel=False
# models
-from proteus.mprans import (RANS2P,
+from proteus import MoveMeshMonitor
+from proteus.kernels import (RANS2P,
RANS3PF,
VOF,
RDLS,
@@ -23,7 +24,6 @@
CLSVOF,
AddedMass,
MoveMesh,
- MoveMeshMonitor,
Pres,
PresInit,
PresInc,
diff --git a/proteus/__init__.py b/proteus/__init__.py
index 96d5bc8cd3..434d993d5f 100644
--- a/proteus/__init__.py
+++ b/proteus/__init__.py
@@ -41,7 +41,7 @@
from . import _threads
_threads.apply_defaults(_threads.launched_size())
-__version__ = '2.0.0rc1'
+__version__ = '2.0.0rc2'
#: What ``from proteus import *`` binds. It is that surface, not an
#: inventory of submodules: several exist that are deliberately absent,
@@ -95,7 +95,6 @@
"cmeshTools",
"cnumericalFlux",
"cTwophaseDarcyCoefficients",
- "cADR",
"WaveTools",
"Context",
"BoundaryConditions",
diff --git a/proteus/_kernel_aliases.py b/proteus/_kernel_aliases.py
new file mode 100644
index 0000000000..4bfdd1fc10
--- /dev/null
+++ b/proteus/_kernel_aliases.py
@@ -0,0 +1,88 @@
+"""Deprecated import paths of the kernel packages (C49 R1).
+
+proteus.mprans, proteus.richards, proteus.m_comp_co2 and proteus.elastoplastic became proteus.kernels, and a few modules
+of proteus.mprans went elsewhere (SpatialTools and BoundaryConditions were merged into proteus.SpatialTools and
+proteus.BoundaryConditions, BodyDynamics went to proteus.mbd, MeshSmoothing, MoveMeshMonitor, cMoveMeshMonitor and
+cArgumentsDict to proteus). Each old package is a thin ``__init__`` that calls :func:`install`: ``proteus.mprans.X``
+(``import``, ``from ... import``, a dotted use after an import) is then the very module object of its new home, so
+``proteus.mprans.RANS2P is proteus.kernels.RANS2P`` and classes report their new module path. The old paths warn once
+per package with a DeprecationWarning, stay through 2.0.x and are removed at 2.1.
+
+What an alias cannot do: Cython ``cimport`` (update it), and ``proteus.richards.ADR`` / ``cADR`` (removed with the
+Richards ADR model, no replacement: proteus.kernels.ADR is the unrelated top-level ADR model).
+"""
+import importlib
+import importlib.abc
+import importlib.util
+import sys
+import warnings
+
+_HERE_TO_PROTEUS = ("MeshSmoothing", "MoveMeshMonitor", "cMoveMeshMonitor", "cArgumentsDict")
+
+#: old package -> {submodule: new module path, or None when it was removed}; every other submodule of an old package
+#: is the one of the same name in proteus.kernels
+_SPECIAL = {
+ "proteus.mprans": dict({"SpatialTools": "proteus.SpatialTools",
+ "BoundaryConditions": "proteus.BoundaryConditions",
+ "BodyDynamics": "proteus.mbd.BodyDynamics"},
+ **{name: "proteus." + name for name in _HERE_TO_PROTEUS}),
+ "proteus.richards": {"ADR": None, "cADR": None},
+ "proteus.m_comp_co2": {},
+ "proteus.elastoplastic": {},
+}
+
+
+def _target(fullname):
+ package, _, name = fullname.rpartition(".")
+ table = _SPECIAL.get(package)
+ if table is None:
+ return None
+ new = table.get(name, "proteus.kernels." + name)
+ if new is None:
+ return None
+ try:
+ return new if importlib.util.find_spec(new) is not None else None
+ except ModuleNotFoundError:
+ return None
+
+
+class _AliasFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader):
+ def find_spec(self, fullname, path=None, target=None):
+ new = _target(fullname)
+ if new is None:
+ return None
+ spec = importlib.util.spec_from_loader(fullname, self)
+ spec.loader_state = {"target": new}
+ return spec
+
+ def create_module(self, spec):
+ module = importlib.import_module(spec.loader_state["target"])
+ spec.loader_state["spec"] = module.__spec__ # the import system is about to replace it with this alias's
+ return module
+
+ def exec_module(self, module):
+ module.__spec__ = module.__spec__.loader_state["spec"]
+
+
+_FINDER = _AliasFinder()
+
+
+def install(package):
+ """Called by the ``__init__`` of an old package: warn, and make its submodules aliases (and attributes) of the new ones."""
+ warnings.warn("%s is deprecated: the kernels are in proteus.kernels (SpatialTools and BoundaryConditions in "
+ "proteus.SpatialTools and proteus.BoundaryConditions, BodyDynamics in proteus.mbd); the old path "
+ "stays through 2.0.x and is removed at 2.1" % package, DeprecationWarning, stacklevel=3)
+ if _FINDER not in sys.meta_path:
+ sys.meta_path.insert(0, _FINDER)
+
+ def __getattr__(name, _package=package):
+ # proteus.mprans.RANS2P after only `import proteus.mprans`, as the old package's submodule attributes did
+ # (not `__path__` and the other module attributes)
+ if name.startswith("__"):
+ raise AttributeError(name)
+ try:
+ return importlib.import_module("%s.%s" % (_package, name))
+ except ModuleNotFoundError:
+ raise AttributeError("module %r has no attribute %r" % (_package, name)) from None
+
+ sys.modules[package].__getattr__ = __getattr__
diff --git a/proteus/cADR.py b/proteus/cADR.py
new file mode 100644
index 0000000000..e4a63019d4
--- /dev/null
+++ b/proteus/cADR.py
@@ -0,0 +1,8 @@
+"""Deprecated: the ADR extension is proteus.kernels.cADR (C49 R1). ``proteus.cADR`` is that module, through 2.0.x."""
+import sys
+import warnings
+
+from proteus.kernels import cADR as _cADR
+
+warnings.warn("proteus.cADR is deprecated: use proteus.kernels.cADR (removed at 2.1)", DeprecationWarning, stacklevel=2)
+sys.modules[__name__] = _cADR
diff --git a/proteus/mprans/cMoveMeshMonitor.pyx b/proteus/cMoveMeshMonitor.pyx
similarity index 99%
rename from proteus/mprans/cMoveMeshMonitor.pyx
rename to proteus/cMoveMeshMonitor.pyx
index 553eb830c2..13e59bd857 100644
--- a/proteus/mprans/cMoveMeshMonitor.pyx
+++ b/proteus/cMoveMeshMonitor.pyx
@@ -10,8 +10,8 @@ from libcpp cimport bool
from proteus.Profiling import logEvent
INDEX_DTYPE = np.dtype('i%d' % sizeof(proteus_index_t)) # dtype of proteus_index_t (index_type.h)
-from proteus.mprans import MeshSmoothing as ms
-from proteus.mprans cimport MeshSmoothing as ms
+from proteus import MeshSmoothing as ms
+from proteus cimport MeshSmoothing as ms
from proteus import Comm
from mpi4py import MPI
diff --git a/proteus/elastoplastic/__init__.py b/proteus/elastoplastic/__init__.py
index 954f14b54b..9b79a88fc5 100644
--- a/proteus/elastoplastic/__init__.py
+++ b/proteus/elastoplastic/__init__.py
@@ -1,6 +1,6 @@
-"""
-Modules for simulating elastic and plastic materials
-"""
+"""Deprecated: the elastoplastic kernel is in proteus.kernels (C49 R1); see proteus._kernel_aliases."""
+from proteus import _kernel_aliases
-__all__ = ["ElastoPlastic",
- "cElastoPlastic"]
\ No newline at end of file
+_kernel_aliases.install(__name__)
+
+__all__ = ["ElastoPlastic", "cElastoPlastic"]
diff --git a/proteus/gwvd/GwvdCoefficients.py b/proteus/gwvd/GwvdCoefficients.py
deleted file mode 100644
index 393ece79fe..0000000000
--- a/proteus/gwvd/GwvdCoefficients.py
+++ /dev/null
@@ -1,265 +0,0 @@
-"""
-Variable-density groundwater flow and transport coefficients (continuous Galerkin path).
-
-Ported from erdc/proteus-gwvd@14961d2: `src/GwvdCoefficients.py` (classes) and
-`src/gwvdCoefficients.c` (`density_eval`, `knabnerFrolkovicConsistentVelCorrection_Triangle_P1`,
-`vdgroundwater_mod2_FlowCoefficientsEvaluate`, `vdgroundwater_mod2_TransportCoefficientsEvaluate`).
-The primary variables are the freshwater head h and the normalized mass fraction c (`mf`).
-The flow "velocity" handed to transport is the mass flux rho*q from the flow model's velocity
-post-processing (`conservativeFlux`).
-"""
-import numpy as np
-from proteus import TransportCoefficients
-from proteus import FemTools
-from proteus.Profiling import logEvent
-
-
-def density_eval(mf, epsilon, rho_fw):
- """Linear density relation rho = rho_fw (1 + epsilon c)."""
- return rho_fw * (1.0 + epsilon * mf)
-
-
-def var_visc(mf, mf_s):
- """Relative viscosity of Lever & Jackson (1985), as in the 2012 code (a ratio, not a viscosity)."""
- mf_a = mf * mf_s
- return 1.0 + 1.85 * mf_a - 4.1 * mf_a**2 + 44.5 * mf_a**3
-
-
-def knabnerFrolkovicConsistentVelCorrection_Triangle_P1(epsilon, c_l2g, c_dof, J, Jinv, gravity,
- q_rhog_consistent, eps_tol=1.0e-9):
- """Knabner-Frolkovic (1996) consistent rho*g on P1 triangles, Eqs. 3.3-3.16.
-
- Writes J^{-T} hhat into q_rhog_consistent (nElements x 2), where hhat holds the reference-element
- derivatives of the integrated buoyancy term. For the linear density used here the exact integral
- is the mean of the two vertex values, which is what the 2012 C code evaluates.
- """
- JeT = np.swapaxes(J[:, 0], 1, 2)
- JeTinv = np.swapaxes(Jinv[:, 0], 1, 2)
- ghat = np.einsum('eij,j->ei', JeT, gravity)
- c_e = c_dof[c_l2g[:, :3]]
- h1 = np.where(np.abs(c_e[:, 1] - c_e[:, 0]) <= eps_tol,
- epsilon * c_e[:, 0], 0.5 * epsilon * (c_e[:, 1] + c_e[:, 0]))
- h2 = np.where(np.abs(c_e[:, 2] - c_e[:, 0]) <= eps_tol,
- epsilon * c_e[:, 0], 0.5 * epsilon * (c_e[:, 2] + c_e[:, 0]))
- h_hat = np.stack([ghat[:, 0] * h1, ghat[:, 1] * h2], axis=1)
- q_rhog_consistent[:] = np.einsum('eij,ej->ei', JeTinv, h_hat)
-
-
-class VariableDensity_mod2_FlowEquationCoefficients(TransportCoefficients.TC_base):
- """
- Variable-density subsurface flow in non-divergence (mod2) form for the freshwater head h:
-
- S rho h_t + div(f - a grad h) + r = 0,
- a = k rho_fw g rho / mu, f = -a epsilon c e_z (or -a (rho g)~ with the consistent velocity),
- r = omega (drho/dc) c_t / rho.
-
- The mass fraction c and its time derivative come from the transport model.
- """
-
- def __init__(self, aOfX=None, rOfX=None, bOfX=None, S=1.0, omega=.3, epsilon=.025, rho_fw=1000.0,
- gc=9.8, Kx=1.0e-10, Ky=1.0e-10, Kz=1.0e-10, mu=1.0e-3, mf_s=0.167, drho_dmf=200.0,
- rho_source=0.0, T_model=None, C_model=None, flowModelIndex=0, transModelIndex=1,
- cModelIndex=2, nc=1, nd=2, consistentVelocityFlag=0, consistentVelocityFunction=None,
- variableViscosityFlag=0, rho_eval=None, rhoInt_eval=None, gravity=None,
- getInterface=None, Height=1.0):
- self.aOfX = aOfX
- self.rOfX = rOfX
- self.bOfX = bOfX
- self.omega = omega
- self.epsilon = epsilon
- self.S = S
- self.gc = gc
- self.rho_fw = rho_fw
- self.Kx = Kx
- self.Ky = Ky
- self.Kz = Kz
- self.mu = mu
- self.mf_s = mf_s
- self.rho_source = rho_source
- self.nd = nd
- self.drho_dmf = drho_dmf
- self.T_model = T_model
- self.C_model = C_model
- self.getInterface = getInterface
- self.Height = Height
- self.consistentVelocityFlag = consistentVelocityFlag # 0 none, 1 Knabner-Frolkovic 96
- self.variableViscosityFlag = variableViscosityFlag
- if C_model is not None:
- raise NotImplementedError("surface-water coupling (C_model) is not ported")
- if consistentVelocityFlag == 1 and nd != 2:
- raise NotImplementedError("only the P1 triangle consistent velocity is ported")
- mass, advection, diffusion, potential, reaction, hamiltonian = {}, {}, {}, {}, {}, {}
- for i in range(nc):
- mass[i] = {i: 'linear'}
- advection[i] = {i: 'constant'}
- diffusion[i] = {i: {i: 'constant'}}
- potential[i] = {i: 'u'}
- reaction[i] = {i: 'constant'}
- TransportCoefficients.TC_base.__init__(self, nc, mass, advection, diffusion, potential,
- reaction, hamiltonian, variableNames=['h'])
- self.transModelIndex = transModelIndex
- self.flowModelIndex = flowModelIndex
- self.cModelIndex = cModelIndex
- self.q_mf = None
- self.q_mfdt = None
- self.ebqe_mf = None
- self.ebqe_mfdt = None
- self.ebq_mf = None
- self.ebq_mfdt = None
- self.consistentVelocityFunction = consistentVelocityFunction
- self.q_rhog_consistent = None
- self.rho_eval = rho_eval
- self.rhoInt_eval = rhoInt_eval
- self.gravity = gravity
-
- def preStep(self, t, firstStep=False):
- """Build the consistent rho*g from the current mass fraction, if requested."""
- if self.consistentVelocityFlag == 1 and self.T_model is not None:
- assert self.transModel.u[0].femSpace.isSpace('C0',('lagrange','bernstein'),1,'simplex')
- knabnerFrolkovicConsistentVelCorrection_Triangle_P1(self.epsilon,
- self.transModel.u[0].femSpace.dofMap.l2g,
- self.transModel.u[0].dof,
- self.model.q['J'],
- self.model.q['inverse(J)'],
- np.asarray(self.gravity, 'd'),
- self.q_rhog_consistent)
-
- def initializeMesh(self, mesh):
- self.elementBoundaryElements = mesh.elementBoundaryElementsArray
- self.exteriorElementBoundaries = mesh.exteriorElementBoundariesArray
-
- def attachModels(self, modelList):
- self.model = modelList[self.flowModelIndex]
- if self.T_model is not None:
- self.transModel = modelList[self.transModelIndex]
- self.q_mf = self.transModel.q[('u', 0)]
- self.q_mfdt = self.transModel.q[('mt', 0)]
- self.ebqe_mf = self.transModel.ebqe[('u', 0)]
- self.ebqe_mfdt = np.zeros(self.ebqe_mf.shape, 'd')
- if ('u', 0) in self.transModel.ebq:
- self.ebq_mf = self.transModel.ebq[('u', 0)]
- self.ebq_mfdt = np.zeros(self.ebq_mf.shape, 'd')
- if self.consistentVelocityFlag != 0:
- self.q_rhog_consistent = np.zeros((self.q_mf.shape[0], self.nd), 'd')
-
- def evaluate(self, t, c):
- if self.q_mf is not None and c[('u', 0)].shape == self.q_mf.shape:
- mf, mfdt, b_flag = self.q_mf, self.q_mfdt, 0
- elif self.ebqe_mf is not None and c[('u', 0)].shape == self.ebqe_mf.shape:
- mf, mfdt, b_flag = self.ebqe_mf, self.ebqe_mfdt, 1
- elif self.ebq_mf is not None and c[('u', 0)].shape == self.ebq_mf.shape:
- # as in 2012: element-boundary points have no c_t, so the coefficients are left unset
- return
- else:
- raise RuntimeError("no mass fraction for points of shape %s" % (c[('u', 0)].shape,))
- nd = self.nd
- a = c[('a', 0, 0)]
- assert a.shape[-1] == nd * nd, "expected full (non-sparse) diffusion storage"
- density = density_eval(mf, self.epsilon, self.rho_fw)
- logEvent("gwvd flow: t=%g b_flag=%d max|c_t|=%g" % (t, b_flag, np.abs(mfdt).max()), level=5)
- c[('m', 0)][:] = c[('u', 0)] * self.S * density # replaced by the time integrator
- c[('dm', 0, 0)][:] = self.S * density
- c[('r', 0)][:] = self.drho_dmf * mfdt / density
- K = [self.Kx, self.Ky, self.Kz][:nd]
- denom = self.mu if self.variableViscosityFlag == 0 else var_visc(mf, self.mf_s)
- a.fill(0.0)
- for I in range(nd):
- a[..., I * nd + I] = K[I] * self.gc * self.rho_fw * density / denom
- f, df = c[('f', 0)], c[('df', 0, 0)]
- df.fill(0.0)
- if self.consistentVelocityFlag == 1:
- if b_flag == 0:
- rhog = self.q_rhog_consistent[:, np.newaxis, :]
- else:
- eN = self.elementBoundaryElements[self.exteriorElementBoundaries, 0]
- rhog = self.q_rhog_consistent[eN][:, np.newaxis, :]
- A = a.reshape(a.shape[:-1] + (nd, nd))
- f[:] = -np.einsum('...ij,...j->...i', A, np.broadcast_to(rhog, f.shape))
- else:
- f.fill(0.0)
- f[..., nd - 1] = -a[..., (nd - 1) * nd + nd - 1] * self.epsilon * mf
-
-
-class VDGroundwater_mod2_TransportCoefficients(TransportCoefficients.TC_base):
- """
- Mass-fraction transport in advective (Hamilton-Jacobi) form driven by the flow model's mass flux v:
-
- omega rho c_t + v . grad c - div(a grad c) = 0,
- a = rho d omega I + alpha_T |v| I + (alpha_L - alpha_T) v v^T / |v|.
- """
-
- def __init__(self, nc=1, nd=2, omega=0.3, alpha_L=1.0, alpha_T=0.2, rho_fw=1000, d=1.3e-9,
- epsilon=0.0, rho_source=0.0, mf_source=0.0, flowModelIndex=0, transModelIndex=1,
- cModelIndex=2, C_Model=None, F_Model=0, getInterface=None, Height=1.0):
- self.nd = nd
- self.omega = omega
- self.nc = nc
- self.d = d
- self.alpha_L = alpha_L
- self.alpha_T = alpha_T
- self.rho_fw = rho_fw
- self.epsilon = epsilon
- self.rho_source = rho_source
- self.mf_source = mf_source
- self.F_Model = F_Model
- self.C_Model = C_Model
- self.flowModelIndex = flowModelIndex
- self.transModelIndex = transModelIndex
- self.cModelIndex = cModelIndex
- self.getInterface = getInterface
- self.Height = Height
- if C_Model is not None:
- raise NotImplementedError("surface-water coupling (C_Model) is not ported")
- mass, advection, diffusion, potential, reaction, hamiltonian = {}, {}, {}, {}, {}, {}
- for i in range(nc):
- mass[i] = {i: 'linear'}
- advection[i] = {i: 'linear'}
- diffusion[i] = {i: {i: 'constant'}}
- potential[i] = {i: 'u'}
- reaction[i] = {i: 'linear'}
- hamiltonian[i] = {i: 'linear'}
- TransportCoefficients.TC_base.__init__(self, nc, mass, advection, diffusion, potential,
- reaction, hamiltonian, variableNames=['mf'])
-
- def attachModels(self, modelList):
- self.model = modelList[self.transModelIndex]
- if self.F_Model is not None:
- flow = modelList[self.flowModelIndex]
- self.flowModel = flow
- self.q_v = flow.q[('velocity', 0)]
- self.ebq_v = flow.ebq.get(('velocity', 0))
- self.ebqe_v = flow.ebqe[('velocity', 0)]
- self.ebq_global_v = flow.ebq_global.get(('velocity', 0))
-
- def evaluate(self, t, c):
- shape = c[('df', 0, 0)].shape
- for v in (self.q_v, self.ebq_v, self.ebqe_v, self.ebq_global_v):
- if v is not None and v.shape == shape:
- break
- else:
- raise RuntimeError("no flow velocity for points of shape %s" % (shape,))
- nd = self.nd
- a = c[('a', 0, 0)]
- assert a.shape[-1] == nd * nd, "expected full (non-sparse) diffusion storage"
- u = c[('u', 0)]
- density = density_eval(u, self.epsilon, self.rho_fw)
- c[('m', 0)][:] = u # replaced by NonConservativeBackwardEuler: m_t = dm (u - u_last)/dt
- c[('dm', 0, 0)][:] = self.omega * density
- c[('r', 0)].fill(0.0)
- c[('dr', 0, 0)].fill(0.0)
- c[('f', 0)].fill(0.0)
- c[('df', 0, 0)].fill(0.0)
- c[('H', 0)][:] = np.einsum('...i,...i->...', c[('grad(u)', 0)], v)
- c[('dH', 0, 0)][:] = v
- norm_v = np.sqrt(np.einsum('...i,...i->...', v, v))
- safe = np.where(norm_v > 0.0, norm_v, 1.0)
- a.fill(0.0)
- for I in range(nd):
- a[..., I * nd + I] = (density * self.d * self.omega
- + np.where(norm_v > 0.0,
- self.alpha_T * norm_v
- + (self.alpha_L - self.alpha_T) * v[..., I]**2 / safe, 0.0))
- for J in range(I + 1, nd):
- off = np.where(norm_v > 0.0, (self.alpha_L - self.alpha_T) * v[..., I] * v[..., J] / safe, 0.0)
- a[..., I * nd + J] = off
- a[..., J * nd + I] = off
diff --git a/proteus/gwvd/Gwvd_consolidated_classes.py b/proteus/gwvd/Gwvd_consolidated_classes.py
deleted file mode 100644
index 416934f96c..0000000000
--- a/proteus/gwvd/Gwvd_consolidated_classes.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""
-Time integration, step control and iterative split-operator classes used by the 2012 gwvd decks.
-
-Ported from erdc/proteus-gwvd@14961d2 `src/Gwvd_consolidated_classes.py`: only the classes the
-continuous Galerkin decks select (`Fixed_dt_controller_systemit`, `NonConservativeBackwardEuler`,
-`ISO_fixed_MinModelStep`).
-"""
-import proteus.StepControl
-import proteus.TimeIntegration
-import proteus.SplitOperator
-from proteus.Comm import globalMax
-from proteus.Profiling import logEvent
-
-
-class Fixed_dt_controller_systemit(proteus.StepControl.Min_dt_controller):
- """Fixed model step dt = nOptions.DT, for the iterated (ISO) coupling of flow and transport."""
-
- def __init__(self, model, nOptions):
- proteus.StepControl.Min_dt_controller.__init__(self, model, nOptions)
- self.dt = nOptions.DT
- self.dt_model_last = None
- model.levelModelList[-1].timeIntegration.isAdaptive = True # needed by the ISO controller
-
- def initialize_dt_model(self, t0, tOut):
- self.saveSolution()
- self.dt_model = self.dt
- if self.dt_model_last is None:
- self.dt_model_last = self.dt_model
- self.set_dt_allLevels()
- self.substeps = [self.t_model]
- logEvent("Initializing time step on model %s to dt = %12.5e" % (self.model.name, self.dt_model), level=1)
-
- def choose_dt_model(self):
- self.solverFailures = 0
- self.errorFailures = 0
- self.saveSolution()
- self.dt_model = self.dt
- if self.dt_model_last is None:
- self.dt_model_last = self.dt_model
- self.set_dt_allLevels()
- self.setSubsteps([self.t_model])
-
- def stepExact_model(self, tOut):
- pass
-
-
-class NonConservativeBackwardEuler(proteus.TimeIntegration.BackwardEuler):
- """Backward Euler on the primary variable: m_t = dm (u - u_last)/dt, with dm frozen at the new iterate.
-
- Until the time history is initialized, m_t is reported as zero. Current proteus spins up model 0
- (the flow) before the transport history exists, when u_last is still zero and dt is the default
- 1.0; the flow source omega (drho/dc) c_t / rho would then see a fictitious c_t = omega rho c.
- """
-
- def __init__(self, transport, integrateInterpolationPoints=False):
- proteus.TimeIntegration.BackwardEuler.__init__(self, transport,
- integrateInterpolationPoints=integrateInterpolationPoints)
- self.historyInitialized = False
-
- def initializeTimeHistory(self, resetFromDOF=True):
- proteus.TimeIntegration.BackwardEuler.initializeTimeHistory(self, resetFromDOF)
- self.historyInitialized = True
-
- def calculateElementCoefficients(self, q):
- self.calculateCoefs()
- if not self.historyInitialized:
- for ci in self.m_last.keys():
- self.m_tmp[ci][:] = q[('u', ci)]
- q[('mt', ci)].fill(0.0)
- return
- for ci in self.m_last.keys():
- self.m_tmp[ci][:] = q[('u', ci)]
- q[('mt', ci)][:] = q[('u', ci)]
- q[('mt', ci)] -= self.m_last[ci]
- q[('mt', ci)] /= self.dt
- q[('mt', ci)] *= q[('dm', ci, ci)]
- for cj in range(self.nc):
- if ('dmt', ci, cj) in q:
- q[('dmt', ci, cj)][:] = q[('dm', ci, cj)]
- q[('dmt', ci, cj)] /= self.dt
- if ('dm_sge', ci, cj) in q and ('dmt_sge', ci, cj) in q:
- q[('dmt_sge', ci, cj)][:] = q[('dm_sge', ci, cj)]
- q[('dmt_sge', ci, cj)] /= self.dt
-
- def calculateGeneralizedInterpolationCoefficients(self, cip):
- if not self.integrateInterpolationPoints:
- return
- for ci in self.m_ip_last.keys():
- self.m_ip_tmp[ci][:] = cip[('u', ci)]
- cip[('mt', ci)][:] = cip[('u', ci)]
- cip[('mt', ci)] -= self.m_ip_last[ci]
- cip[('mt', ci)] /= self.dt
- cip[('mt', ci)] *= cip[('dm', ci, ci)]
- for cj in range(self.nc):
- if ('dmt', ci, cj) in cip:
- cip[('dmt', ci, cj)][:] = cip[('dm', ci, cj)]
- cip[('dmt', ci, cj)] /= self.dt
- if ('dmt_sge', ci, cj) in cip:
- cip[('dmt_sge', ci, cj)][:] = cip[('dm_sge', ci, cj)]
- cip[('dmt_sge', ci, cj)] /= self.dt
-
-
-class ISO_fixed_MinModelStep(proteus.SplitOperator.ISO_fixed_MinAdaptiveModelStep):
- """
- Iterate flow and transport within a step (Povich 2013, Sec. 4.5) until the max norm of the owned
- residuals of both models is below atol_iso, then advance.
- """
-
- def __init__(self, modelList, system=proteus.SplitOperator.defaultSystem, stepExact=False, atol_iso=1.e-8):
- proteus.SplitOperator.ISO_fixed_MinAdaptiveModelStep.__init__(self, modelList, system, stepExact)
- self.atol_iso = atol_iso
- self.convergence_flag = False
- self.velocity_Postprocess = False
-
- def setFromOptions(self, soOptions):
- self.velocity_Postprocess = False
- if 'atol_iso' in dir(soOptions):
- self.atol_iso = soOptions.atol_iso
- if 'velocity_Postprocess' in dir(soOptions):
- self.velocity_Postprocess = soOptions.velocity_Postprocess
-
- def converged(self):
- if self.convergence_flag and self.its != 0:
- self.its = 0
- self.convergence_flag = False
- return True
- return False
-
- def SysNorm(self, rSys):
- # The 2012 code takes the signed maximum of each residual (not max |r|), so negative
- # residuals never block convergence. Kept for fidelity with the published runs.
- return max(globalMax(float(r.max())) for r in rSys)
-
- def sequenceTaken(self):
- self.its += 1
- rSys = []
- for model in self.modelList:
- lm = model.levelModelList[-1]
- lm.getResidual(model.uList[-1], model.rList[-1])
- rSys.append(model.rList[-1][:lm.mesh.subdomainMesh.nNodes_owned])
- rNorm = self.SysNorm(rSys)
- logEvent("ISO iteration %d: max residual %12.5e (atol_iso %12.5e)" % (self.its, rNorm, self.atol_iso), level=1)
- if rNorm < self.atol_iso and self.its != 0:
- self.convergence_flag = True
- if self.convergence_flag:
- for model in self.modelList:
- model.stepController.updateTimeHistory()
- model.stepController.choose_dt_model()
diff --git a/proteus/gwvd/__init__.py b/proteus/gwvd/__init__.py
deleted file mode 100644
index 9cdd21640a..0000000000
--- a/proteus/gwvd/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""
-Variable-density groundwater flow and transport (Povich et al. 2013, Comput. Geosci. 17:529).
-
-Port of the continuous Galerkin path of erdc/proteus-gwvd at commit 14961d2 (2012-07-31): the
-mod2 flow and transport coefficients, the Knabner-Frolkovic consistent-velocity correction and the
-time-integration, step-control and iterative split-operator classes the 2012 decks use. The C
-coefficient evaluators are reimplemented with numpy.
-"""
-__all__ = ["GwvdCoefficients", "Gwvd_consolidated_classes"]
diff --git a/proteus/mprans/.gitignore b/proteus/kernels/.gitignore
similarity index 100%
rename from proteus/mprans/.gitignore
rename to proteus/kernels/.gitignore
diff --git a/proteus/ADR.cpp b/proteus/kernels/ADR.cpp
similarity index 100%
rename from proteus/ADR.cpp
rename to proteus/kernels/ADR.cpp
diff --git a/proteus/ADR.h b/proteus/kernels/ADR.h
similarity index 99%
rename from proteus/ADR.h
rename to proteus/kernels/ADR.h
index 936c4ae4ea..bb8fd3e205 100644
--- a/proteus/ADR.h
+++ b/proteus/kernels/ADR.h
@@ -17,7 +17,7 @@
#include "cutquadric.h"
#include "UnfittedKernels.h"
#include "Unfitted.h"
-#include "mprans/ArgumentsDict.h"
+#include "ArgumentsDict.h"
#include "pyarray.h"
namespace py = pybind11;
diff --git a/proteus/ADR.py b/proteus/kernels/ADR.py
similarity index 99%
rename from proteus/ADR.py
rename to proteus/kernels/ADR.py
index 9722c96c85..9bc1c89e46 100644
--- a/proteus/ADR.py
+++ b/proteus/kernels/ADR.py
@@ -21,8 +21,8 @@
from proteus.TransportCoefficients import TC_base
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
-from proteus.cADR import *
-from proteus.mprans import cArgumentsDict
+from proteus.kernels.cADR import *
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.Transport
diff --git a/proteus/mprans/AddedMass.cpp b/proteus/kernels/AddedMass.cpp
similarity index 100%
rename from proteus/mprans/AddedMass.cpp
rename to proteus/kernels/AddedMass.cpp
diff --git a/proteus/mprans/AddedMass.h b/proteus/kernels/AddedMass.h
similarity index 100%
rename from proteus/mprans/AddedMass.h
rename to proteus/kernels/AddedMass.h
diff --git a/proteus/mprans/AddedMass.py b/proteus/kernels/AddedMass.py
similarity index 99%
rename from proteus/mprans/AddedMass.py
rename to proteus/kernels/AddedMass.py
index 7798639200..5e5fb85447 100644
--- a/proteus/mprans/AddedMass.py
+++ b/proteus/kernels/AddedMass.py
@@ -15,7 +15,8 @@
from proteus.TransportCoefficients import TC_base
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
-from . import cAddedMass, cArgumentsDict
+from . import cAddedMass
+from proteus import cArgumentsDict
from mpi4py import MPI
import proteus.NumericalFlux
import proteus.Transport
diff --git a/proteus/mprans/ArchiveBeams.py b/proteus/kernels/ArchiveBeams.py
similarity index 100%
rename from proteus/mprans/ArchiveBeams.py
rename to proteus/kernels/ArchiveBeams.py
diff --git a/proteus/mprans/CLSVOF.cpp b/proteus/kernels/CLSVOF.cpp
similarity index 100%
rename from proteus/mprans/CLSVOF.cpp
rename to proteus/kernels/CLSVOF.cpp
diff --git a/proteus/mprans/CLSVOF.h b/proteus/kernels/CLSVOF.h
similarity index 100%
rename from proteus/mprans/CLSVOF.h
rename to proteus/kernels/CLSVOF.h
diff --git a/proteus/mprans/CLSVOF.py b/proteus/kernels/CLSVOF.py
similarity index 99%
rename from proteus/mprans/CLSVOF.py
rename to proteus/kernels/CLSVOF.py
index 200dd0c16a..f411e9ff5e 100644
--- a/proteus/mprans/CLSVOF.py
+++ b/proteus/kernels/CLSVOF.py
@@ -1,13 +1,13 @@
import proteus
import proteus.MeshTools
-from proteus.mprans.cCLSVOF import *
+from proteus.kernels.cCLSVOF import *
import numpy as np
from proteus import cmeshTools
from proteus.Transport import OneLevelTransport
from proteus.Transport import TC_base, NonlinearEquation, Quadrature
from proteus.Transport import logEvent, memory, FluxBoundaryConditions, Comm
from proteus.Transport import cfemIntegrals
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.LinearAlgebraTools
import proteus.NonlinearSolvers
import proteus.NumericalFlux
diff --git a/proteus/mprans/Dissipation.cpp b/proteus/kernels/Dissipation.cpp
similarity index 100%
rename from proteus/mprans/Dissipation.cpp
rename to proteus/kernels/Dissipation.cpp
diff --git a/proteus/mprans/Dissipation.h b/proteus/kernels/Dissipation.h
similarity index 100%
rename from proteus/mprans/Dissipation.h
rename to proteus/kernels/Dissipation.h
diff --git a/proteus/mprans/Dissipation.py b/proteus/kernels/Dissipation.py
similarity index 99%
rename from proteus/mprans/Dissipation.py
rename to proteus/kernels/Dissipation.py
index 7c2d9c5a18..8a6399e98f 100644
--- a/proteus/mprans/Dissipation.py
+++ b/proteus/kernels/Dissipation.py
@@ -1,11 +1,11 @@
import proteus
-from proteus.mprans.cDissipation import *
-from proteus.mprans.cDissipation2D import *
+from proteus.kernels.cDissipation import *
+from proteus.kernels.cDissipation2D import *
import numpy as np
from proteus import cmeshTools
from proteus import Profiling as prof
from proteus import cfemIntegrals
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.Comm
import proteus.FemTools
import proteus.NonlinearSolvers
diff --git a/proteus/mprans/Dissipation2D.cpp b/proteus/kernels/Dissipation2D.cpp
similarity index 100%
rename from proteus/mprans/Dissipation2D.cpp
rename to proteus/kernels/Dissipation2D.cpp
diff --git a/proteus/mprans/Dissipation2D.h b/proteus/kernels/Dissipation2D.h
similarity index 100%
rename from proteus/mprans/Dissipation2D.h
rename to proteus/kernels/Dissipation2D.h
diff --git a/proteus/elastoplastic/ElastoPlastic.h b/proteus/kernels/ElastoPlastic.h
similarity index 99%
rename from proteus/elastoplastic/ElastoPlastic.h
rename to proteus/kernels/ElastoPlastic.h
index d8958ab10b..c401ae1ff9 100644
--- a/proteus/elastoplastic/ElastoPlastic.h
+++ b/proteus/kernels/ElastoPlastic.h
@@ -18,7 +18,7 @@
#include "tresca.h"
#include "druckerPrager.h"
#include "mcdp.h"
-#include "../mprans/ArgumentsDict.h"
+#include "ArgumentsDict.h"
#include "pyarray.h"
#include "pybind11/pybind11.h"
diff --git a/proteus/elastoplastic/ElastoPlastic.py b/proteus/kernels/ElastoPlastic.py
similarity index 99%
rename from proteus/elastoplastic/ElastoPlastic.py
rename to proteus/kernels/ElastoPlastic.py
index 37141f9791..38341eae14 100644
--- a/proteus/elastoplastic/ElastoPlastic.py
+++ b/proteus/kernels/ElastoPlastic.py
@@ -8,7 +8,7 @@
from proteus.Transport import NonlinearEquation, logEvent, memory
from proteus.Transport import FluxBoundaryConditions, Comm, cfemIntegrals
from proteus.Transport import DOFBoundaryConditions, Quadrature
-from proteus.mprans import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.Transport
import proteus.TransportCoefficients
diff --git a/proteus/mprans/EntropyViscosity.py b/proteus/kernels/EntropyViscosity.py
similarity index 100%
rename from proteus/mprans/EntropyViscosity.py
rename to proteus/kernels/EntropyViscosity.py
diff --git a/proteus/mprans/GN_SW2DCV.cpp b/proteus/kernels/GN_SW2DCV.cpp
similarity index 100%
rename from proteus/mprans/GN_SW2DCV.cpp
rename to proteus/kernels/GN_SW2DCV.cpp
diff --git a/proteus/mprans/GN_SW2DCV.h b/proteus/kernels/GN_SW2DCV.h
similarity index 100%
rename from proteus/mprans/GN_SW2DCV.h
rename to proteus/kernels/GN_SW2DCV.h
diff --git a/proteus/mprans/GN_SW2DCV.py b/proteus/kernels/GN_SW2DCV.py
similarity index 99%
rename from proteus/mprans/GN_SW2DCV.py
rename to proteus/kernels/GN_SW2DCV.py
index 8da54248a5..0c8c8946e2 100644
--- a/proteus/mprans/GN_SW2DCV.py
+++ b/proteus/kernels/GN_SW2DCV.py
@@ -1,8 +1,8 @@
import proteus
from proteus import FemTools
from proteus import LinearAlgebraTools as LAT
-from proteus.mprans.cGN_SW2DCV import *
-from proteus.mprans.SW2DCV import bathymetryAtNodes
+from proteus.kernels.cGN_SW2DCV import *
+from proteus.kernels.SW2DCV import bathymetryAtNodes
import numpy as np
from proteus import cmeshTools
from proteus.csparsity import CSR_INDEX_DTYPE
@@ -10,7 +10,7 @@
from proteus.Transport import Quadrature, logEvent, memory, BackwardEuler
from proteus.Transport import FluxBoundaryConditions, Comm, DOFBoundaryConditions
from proteus.Transport import cfemIntegrals, globalMax, SparseMat
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.TimeIntegration
import proteus.Transport
diff --git a/proteus/mprans/Kappa.cpp b/proteus/kernels/Kappa.cpp
similarity index 100%
rename from proteus/mprans/Kappa.cpp
rename to proteus/kernels/Kappa.cpp
diff --git a/proteus/mprans/Kappa.h b/proteus/kernels/Kappa.h
similarity index 100%
rename from proteus/mprans/Kappa.h
rename to proteus/kernels/Kappa.h
diff --git a/proteus/mprans/Kappa.py b/proteus/kernels/Kappa.py
similarity index 99%
rename from proteus/mprans/Kappa.py
rename to proteus/kernels/Kappa.py
index 003ab7ed59..594df646e3 100644
--- a/proteus/mprans/Kappa.py
+++ b/proteus/kernels/Kappa.py
@@ -1,12 +1,12 @@
import proteus
-from proteus.mprans.cKappa import *
-from proteus.mprans.cKappa2D import *
+from proteus.kernels.cKappa import *
+from proteus.kernels.cKappa2D import *
from proteus import Profiling as prof
import numpy as np
from proteus import cmeshTools
from proteus.Transport import OneLevelTransport
from proteus import cfemIntegrals
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.Comm
import proteus.FemTools
import proteus.NonlinearSolvers
diff --git a/proteus/mprans/Kappa2D.cpp b/proteus/kernels/Kappa2D.cpp
similarity index 100%
rename from proteus/mprans/Kappa2D.cpp
rename to proteus/kernels/Kappa2D.cpp
diff --git a/proteus/mprans/Kappa2D.h b/proteus/kernels/Kappa2D.h
similarity index 100%
rename from proteus/mprans/Kappa2D.h
rename to proteus/kernels/Kappa2D.h
diff --git a/proteus/mprans/MCorr.cpp b/proteus/kernels/MCorr.cpp
similarity index 100%
rename from proteus/mprans/MCorr.cpp
rename to proteus/kernels/MCorr.cpp
diff --git a/proteus/mprans/MCorr.h b/proteus/kernels/MCorr.h
similarity index 100%
rename from proteus/mprans/MCorr.h
rename to proteus/kernels/MCorr.h
diff --git a/proteus/mprans/MCorr.py b/proteus/kernels/MCorr.py
similarity index 99%
rename from proteus/mprans/MCorr.py
rename to proteus/kernels/MCorr.py
index 6f4d3b8818..5ef22b6bea 100644
--- a/proteus/mprans/MCorr.py
+++ b/proteus/kernels/MCorr.py
@@ -1,13 +1,13 @@
import proteus
from proteus import cfemIntegrals, Norms, Quadrature
from proteus.Comm import globalSum
-from proteus.mprans.cMCorr import *
+from proteus.kernels.cMCorr import *
import numpy as np
from proteus import cmeshTools
from proteus.Transport import OneLevelTransport, logEvent, memory, fabs
from proteus.Transport import TC_base, l2Norm, NonlinearEquation
from proteus.LinearAlgebraTools import SparseMat, ParVec_petsc4py
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NonlinearSolvers
import proteus.StepControl
import proteus.TransportCoefficients
diff --git a/proteus/mprans/MCorr3P.cpp b/proteus/kernels/MCorr3P.cpp
similarity index 100%
rename from proteus/mprans/MCorr3P.cpp
rename to proteus/kernels/MCorr3P.cpp
diff --git a/proteus/mprans/MCorr3P.h b/proteus/kernels/MCorr3P.h
similarity index 100%
rename from proteus/mprans/MCorr3P.h
rename to proteus/kernels/MCorr3P.h
diff --git a/proteus/mprans/MCorr3P.py b/proteus/kernels/MCorr3P.py
similarity index 99%
rename from proteus/mprans/MCorr3P.py
rename to proteus/kernels/MCorr3P.py
index 2aeddf1715..834219f601 100644
--- a/proteus/mprans/MCorr3P.py
+++ b/proteus/kernels/MCorr3P.py
@@ -19,7 +19,7 @@
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
from . import cMCorr3P
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NonlinearSolvers
import proteus.StepControl
import proteus.Transport
diff --git a/proteus/mprans/MoveMesh.cpp b/proteus/kernels/MoveMesh.cpp
similarity index 100%
rename from proteus/mprans/MoveMesh.cpp
rename to proteus/kernels/MoveMesh.cpp
diff --git a/proteus/mprans/MoveMesh.h b/proteus/kernels/MoveMesh.h
similarity index 100%
rename from proteus/mprans/MoveMesh.h
rename to proteus/kernels/MoveMesh.h
diff --git a/proteus/mprans/MoveMesh.py b/proteus/kernels/MoveMesh.py
similarity index 99%
rename from proteus/mprans/MoveMesh.py
rename to proteus/kernels/MoveMesh.py
index 967d2ccebc..04740a2081 100644
--- a/proteus/mprans/MoveMesh.py
+++ b/proteus/kernels/MoveMesh.py
@@ -1,13 +1,13 @@
import proteus
-from proteus.mprans.cMoveMesh2D import cMoveMesh2D_base
-from proteus.mprans.cMoveMesh import cMoveMesh_base
+from proteus.kernels.cMoveMesh2D import cMoveMesh2D_base
+from proteus.kernels.cMoveMesh import cMoveMesh_base
import numpy as np
from math import sqrt
from proteus.Transport import OneLevelTransport, TC_base, NonlinearEquation
from proteus import Quadrature, FemTools, Comm, Archiver, cfemIntegrals
from proteus.Profiling import logEvent, memory
from proteus import cmeshTools
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.Transport
import proteus.TransportCoefficients
diff --git a/proteus/mprans/MoveMesh2D.cpp b/proteus/kernels/MoveMesh2D.cpp
similarity index 100%
rename from proteus/mprans/MoveMesh2D.cpp
rename to proteus/kernels/MoveMesh2D.cpp
diff --git a/proteus/mprans/MoveMesh2D.h b/proteus/kernels/MoveMesh2D.h
similarity index 100%
rename from proteus/mprans/MoveMesh2D.h
rename to proteus/kernels/MoveMesh2D.h
diff --git a/proteus/mprans/NCLS.cpp b/proteus/kernels/NCLS.cpp
similarity index 100%
rename from proteus/mprans/NCLS.cpp
rename to proteus/kernels/NCLS.cpp
diff --git a/proteus/mprans/NCLS.h b/proteus/kernels/NCLS.h
similarity index 100%
rename from proteus/mprans/NCLS.h
rename to proteus/kernels/NCLS.h
diff --git a/proteus/mprans/NCLS.py b/proteus/kernels/NCLS.py
similarity index 99%
rename from proteus/mprans/NCLS.py
rename to proteus/kernels/NCLS.py
index 54a538ab84..0d2e98ad4d 100644
--- a/proteus/mprans/NCLS.py
+++ b/proteus/kernels/NCLS.py
@@ -1,6 +1,6 @@
import proteus
import proteus.MeshTools
-from proteus.mprans.cNCLS import *
+from proteus.kernels.cNCLS import *
import numpy as np
from proteus import cmeshTools
from proteus.Transport import OneLevelTransport, cfemIntegrals, SparseMat
@@ -10,7 +10,7 @@
from proteus.Transport import globalMax, SSP, ExplicitConsistentMassMatrixWithRedistancing
from proteus.Comm import globalSum
from proteus import Norms
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/mprans/NCLS3P.cpp b/proteus/kernels/NCLS3P.cpp
similarity index 100%
rename from proteus/mprans/NCLS3P.cpp
rename to proteus/kernels/NCLS3P.cpp
diff --git a/proteus/mprans/NCLS3P.h b/proteus/kernels/NCLS3P.h
similarity index 100%
rename from proteus/mprans/NCLS3P.h
rename to proteus/kernels/NCLS3P.h
diff --git a/proteus/mprans/NCLS3P.py b/proteus/kernels/NCLS3P.py
similarity index 99%
rename from proteus/mprans/NCLS3P.py
rename to proteus/kernels/NCLS3P.py
index ef45c5aa25..6e35d7ec91 100644
--- a/proteus/mprans/NCLS3P.py
+++ b/proteus/kernels/NCLS3P.py
@@ -15,10 +15,10 @@
from proteus.TransportCoefficients import TC_base
from proteus.SubgridError import SGE_base
from proteus.LinearAlgebraTools import ParVec_petsc4py
-from proteus.mprans import EntropyViscosity
+from proteus.kernels import EntropyViscosity
from proteus.ShockCapturing import ShockCapturing_base
from . import cNCLS3P
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NonlinearSolvers
import proteus.NumericalFlux
import proteus.ShockCapturing
diff --git a/proteus/mprans/Pres.cpp b/proteus/kernels/Pres.cpp
similarity index 100%
rename from proteus/mprans/Pres.cpp
rename to proteus/kernels/Pres.cpp
diff --git a/proteus/mprans/Pres.h b/proteus/kernels/Pres.h
similarity index 100%
rename from proteus/mprans/Pres.h
rename to proteus/kernels/Pres.h
diff --git a/proteus/mprans/Pres.py b/proteus/kernels/Pres.py
similarity index 99%
rename from proteus/mprans/Pres.py
rename to proteus/kernels/Pres.py
index d09aad2f3f..3ee019a3ab 100644
--- a/proteus/mprans/Pres.py
+++ b/proteus/kernels/Pres.py
@@ -15,7 +15,7 @@
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
from . import cPres
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.Transport
@@ -43,7 +43,7 @@ class Coefficients(TC_base):
p^{k+1} - p^{k} - phi^{k+1} + \nabla\cdot(\mu \mathbf{u}^{k+1}) = 0
"""
#: a closed domain fixes this pressure only up to a constant: NumericalSolution.postStep shifts it to zero
- #: integral mean when no Dirichlet condition fixes it (proteus.mprans.PressureNormalization)
+ #: integral mean when no Dirichlet condition fixes it (proteus.kernels.PressureNormalization)
zeroMean = True
def __init__(self,
diff --git a/proteus/mprans/PresInc.cpp b/proteus/kernels/PresInc.cpp
similarity index 100%
rename from proteus/mprans/PresInc.cpp
rename to proteus/kernels/PresInc.cpp
diff --git a/proteus/mprans/PresInc.h b/proteus/kernels/PresInc.h
similarity index 100%
rename from proteus/mprans/PresInc.h
rename to proteus/kernels/PresInc.h
diff --git a/proteus/mprans/PresInc.py b/proteus/kernels/PresInc.py
similarity index 99%
rename from proteus/mprans/PresInc.py
rename to proteus/kernels/PresInc.py
index bb1a2c2461..5be73540fe 100644
--- a/proteus/mprans/PresInc.py
+++ b/proteus/kernels/PresInc.py
@@ -17,7 +17,7 @@
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
from . import cPresInc
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.Transport
@@ -46,7 +46,7 @@ class Coefficients(TC_base):
q^t = (1-\theta_s) v_f + \theta_s v_s
"""
#: a closed domain fixes this pressure only up to a constant: NumericalSolution.postStep shifts it to zero
- #: integral mean when no Dirichlet condition fixes it (proteus.mprans.PressureNormalization)
+ #: integral mean when no Dirichlet condition fixes it (proteus.kernels.PressureNormalization)
zeroMean = True
def __init__(self,
@@ -798,7 +798,7 @@ def _settleNullSpace(self):
partial row back. Collective."""
if not self.coefficients.fixNullSpace:
return
- from proteus.mprans.PressureNormalization import _hasDirichlet
+ from proteus.kernels.PressureNormalization import _hasDirichlet
if _hasDirichlet(self):
log("PresInc: fixNullSpace ignored, a Dirichlet condition fixes the constant", level=1)
self.coefficients.fixNullSpace = False
diff --git a/proteus/mprans/PresInit.cpp b/proteus/kernels/PresInit.cpp
similarity index 100%
rename from proteus/mprans/PresInit.cpp
rename to proteus/kernels/PresInit.cpp
diff --git a/proteus/mprans/PresInit.h b/proteus/kernels/PresInit.h
similarity index 100%
rename from proteus/mprans/PresInit.h
rename to proteus/kernels/PresInit.h
diff --git a/proteus/mprans/PresInit.py b/proteus/kernels/PresInit.py
similarity index 99%
rename from proteus/mprans/PresInit.py
rename to proteus/kernels/PresInit.py
index ea77b1aa16..9a6ad9e475 100644
--- a/proteus/mprans/PresInit.py
+++ b/proteus/kernels/PresInit.py
@@ -16,7 +16,7 @@
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
from . import cPresInit
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.Transport
@@ -31,7 +31,7 @@ class Coefficients(TC_base):
p^{k+1} - p^{k} - phi^{k+1} + \nabla\cdot(\mu \mathbf{u}^{k+1}) = 0
"""
#: a closed domain fixes this pressure only up to a constant: NumericalSolution.postStep shifts it to zero
- #: integral mean when no Dirichlet condition fixes it (proteus.mprans.PressureNormalization)
+ #: integral mean when no Dirichlet condition fixes it (proteus.kernels.PressureNormalization)
zeroMean = True
def __init__(self,
diff --git a/proteus/mprans/PressureNormalization.py b/proteus/kernels/PressureNormalization.py
similarity index 100%
rename from proteus/mprans/PressureNormalization.py
rename to proteus/kernels/PressureNormalization.py
diff --git a/proteus/mprans/RANS2P.cpp b/proteus/kernels/RANS2P.cpp
similarity index 100%
rename from proteus/mprans/RANS2P.cpp
rename to proteus/kernels/RANS2P.cpp
diff --git a/proteus/mprans/RANS2P.h b/proteus/kernels/RANS2P.h
similarity index 100%
rename from proteus/mprans/RANS2P.h
rename to proteus/kernels/RANS2P.h
diff --git a/proteus/mprans/RANS2P.py b/proteus/kernels/RANS2P.py
similarity index 99%
rename from proteus/mprans/RANS2P.py
rename to proteus/kernels/RANS2P.py
index 2d0efb5b74..fb6a4f81ff 100644
--- a/proteus/mprans/RANS2P.py
+++ b/proteus/kernels/RANS2P.py
@@ -6,8 +6,8 @@
import proteus
from proteus.Gauges import open_history_file, on_hot_start, keep_steps_up_to
import sys
-from proteus.mprans.cRANS2P import *
-from proteus.mprans.cRANS2P2D import *
+from proteus.kernels.cRANS2P import *
+from proteus.kernels.cRANS2P2D import *
from proteus import Profiling
from proteus import LinearAlgebraTools as LAT
from proteus.Comm import (globalSum,
@@ -17,7 +17,7 @@
from proteus import *
from proteus.Transport import *
from proteus.Transport import OneLevelTransport
-from . import cArgumentsDict
+from proteus import cArgumentsDict
from proteus.csparsity import CSR_INDEX_DTYPE
import proteus.NumericalFlux
import proteus.Profiling
diff --git a/proteus/mprans/RANS2P2D.cpp b/proteus/kernels/RANS2P2D.cpp
similarity index 100%
rename from proteus/mprans/RANS2P2D.cpp
rename to proteus/kernels/RANS2P2D.cpp
diff --git a/proteus/mprans/RANS2P2D.h b/proteus/kernels/RANS2P2D.h
similarity index 100%
rename from proteus/mprans/RANS2P2D.h
rename to proteus/kernels/RANS2P2D.h
diff --git a/proteus/mprans/RANS2P_IB.cpp b/proteus/kernels/RANS2P_IB.cpp
similarity index 100%
rename from proteus/mprans/RANS2P_IB.cpp
rename to proteus/kernels/RANS2P_IB.cpp
diff --git a/proteus/mprans/RANS2P_IB.h b/proteus/kernels/RANS2P_IB.h
similarity index 100%
rename from proteus/mprans/RANS2P_IB.h
rename to proteus/kernels/RANS2P_IB.h
diff --git a/proteus/mprans/RANS2P_IB.py b/proteus/kernels/RANS2P_IB.py
similarity index 99%
rename from proteus/mprans/RANS2P_IB.py
rename to proteus/kernels/RANS2P_IB.py
index 3af53efbe4..5d17e2766c 100644
--- a/proteus/mprans/RANS2P_IB.py
+++ b/proteus/kernels/RANS2P_IB.py
@@ -1,6 +1,6 @@
import proteus
-import proteus.mprans.RANS2P as RANS2P
-from proteus.mprans.cRANS2P_IB import *
+import proteus.kernels.RANS2P as RANS2P
+from proteus.kernels.cRANS2P_IB import *
import numpy as np
from proteus import cmeshTools
from proteus.csparsity import CSR_INDEX_DTYPE
@@ -12,9 +12,9 @@
from proteus import *
from proteus.Transport import *
from proteus.Transport import OneLevelTransport
-from . import cArgumentsDict
+from proteus import cArgumentsDict
-class Coefficients(proteus.mprans.RANS2P.Coefficients):
+class Coefficients(proteus.kernels.RANS2P.Coefficients):
_epsFact_solid_is_used = True # the immersed-boundary kernels read it
def __init__(self,
@@ -426,7 +426,7 @@ def initializeBeams(self):
pass
-class LevelModel(proteus.mprans.RANS2P.LevelModel):
+class LevelModel(proteus.kernels.RANS2P.LevelModel):
# def __init__(self,
# uDict,
# phiDict,
diff --git a/proteus/mprans/RANS3PF.cpp b/proteus/kernels/RANS3PF.cpp
similarity index 100%
rename from proteus/mprans/RANS3PF.cpp
rename to proteus/kernels/RANS3PF.cpp
diff --git a/proteus/mprans/RANS3PF.h b/proteus/kernels/RANS3PF.h
similarity index 100%
rename from proteus/mprans/RANS3PF.h
rename to proteus/kernels/RANS3PF.h
diff --git a/proteus/mprans/RANS3PF.py b/proteus/kernels/RANS3PF.py
similarity index 99%
rename from proteus/mprans/RANS3PF.py
rename to proteus/kernels/RANS3PF.py
index 0bd428e1cb..f58aa71f1a 100644
--- a/proteus/mprans/RANS3PF.py
+++ b/proteus/kernels/RANS3PF.py
@@ -24,7 +24,7 @@
from proteus.ShockCapturing import ShockCapturing_base
from . import cRANS3PF
from . import cRANS3PF2D
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.Profiling
import proteus.ShockCapturing
diff --git a/proteus/mprans/RANS3PF2D.cpp b/proteus/kernels/RANS3PF2D.cpp
similarity index 100%
rename from proteus/mprans/RANS3PF2D.cpp
rename to proteus/kernels/RANS3PF2D.cpp
diff --git a/proteus/mprans/RANS3PF2D.h b/proteus/kernels/RANS3PF2D.h
similarity index 100%
rename from proteus/mprans/RANS3PF2D.h
rename to proteus/kernels/RANS3PF2D.h
diff --git a/proteus/mprans/RANS3PSed.cpp b/proteus/kernels/RANS3PSed.cpp
similarity index 100%
rename from proteus/mprans/RANS3PSed.cpp
rename to proteus/kernels/RANS3PSed.cpp
diff --git a/proteus/mprans/RANS3PSed.h b/proteus/kernels/RANS3PSed.h
similarity index 100%
rename from proteus/mprans/RANS3PSed.h
rename to proteus/kernels/RANS3PSed.h
diff --git a/proteus/mprans/RANS3PSed.py b/proteus/kernels/RANS3PSed.py
similarity index 99%
rename from proteus/mprans/RANS3PSed.py
rename to proteus/kernels/RANS3PSed.py
index 51c2407446..2e691fbdf3 100644
--- a/proteus/mprans/RANS3PSed.py
+++ b/proteus/kernels/RANS3PSed.py
@@ -23,7 +23,7 @@
from proteus.ShockCapturing import ShockCapturing_base
from . import cRANS3PSed
from . import cRANS3PSed2D
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/mprans/RANS3PSed2D.cpp b/proteus/kernels/RANS3PSed2D.cpp
similarity index 100%
rename from proteus/mprans/RANS3PSed2D.cpp
rename to proteus/kernels/RANS3PSed2D.cpp
diff --git a/proteus/mprans/RANS3PSed2D.h b/proteus/kernels/RANS3PSed2D.h
similarity index 100%
rename from proteus/mprans/RANS3PSed2D.h
rename to proteus/kernels/RANS3PSed2D.h
diff --git a/proteus/mprans/RDLS.cpp b/proteus/kernels/RDLS.cpp
similarity index 100%
rename from proteus/mprans/RDLS.cpp
rename to proteus/kernels/RDLS.cpp
diff --git a/proteus/mprans/RDLS.h b/proteus/kernels/RDLS.h
similarity index 100%
rename from proteus/mprans/RDLS.h
rename to proteus/kernels/RDLS.h
diff --git a/proteus/mprans/RDLS.py b/proteus/kernels/RDLS.py
similarity index 99%
rename from proteus/mprans/RDLS.py
rename to proteus/kernels/RDLS.py
index d776858a1c..b710052943 100644
--- a/proteus/mprans/RDLS.py
+++ b/proteus/kernels/RDLS.py
@@ -1,6 +1,6 @@
import proteus
from proteus import TimeIntegration
-from proteus.mprans.cRDLS import *
+from proteus.kernels.cRDLS import *
from proteus.Comm import globalMax
import numpy as np
from proteus import cmeshTools
@@ -8,7 +8,7 @@
from proteus.Transport import TC_base, NonlinearEquation, Quadrature, logEvent
from proteus.Transport import cfemIntegrals
from proteus.LinearAlgebraTools import ParVec_petsc4py
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.FemTools
import proteus.NonlinearSolvers
import proteus.ShockCapturing
diff --git a/proteus/richards/Richards.h b/proteus/kernels/Richards.h
similarity index 99%
rename from proteus/richards/Richards.h
rename to proteus/kernels/Richards.h
index d7e18c7d31..953e98d9f5 100644
--- a/proteus/richards/Richards.h
+++ b/proteus/kernels/Richards.h
@@ -7,7 +7,7 @@
#include "CompKernel.h"
#include "ModelFactory.h"
#include "../pskRelations.h"
-#include "../mprans/ArgumentsDict.h"
+#include "ArgumentsDict.h"
#include "pyarray.h"
#define nnz nSpace
diff --git a/proteus/richards/Richards.py b/proteus/kernels/Richards.py
similarity index 99%
rename from proteus/richards/Richards.py
rename to proteus/kernels/Richards.py
index d1701692ab..b5cf00ddc3 100644
--- a/proteus/richards/Richards.py
+++ b/proteus/kernels/Richards.py
@@ -10,7 +10,7 @@
from proteus.Transport import TC_base, NonlinearEquation, logEvent, memory
from proteus.Transport import FluxBoundaryConditions, Comm, cfemIntegrals
from proteus.Transport import DOFBoundaryConditions, Quadrature
-from proteus.mprans import cArgumentsDict
+from proteus import cArgumentsDict
from proteus.LinearAlgebraTools import SparseMat
from proteus import TimeIntegration
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrixForRichards
@@ -583,7 +583,7 @@ def attachModels(self, modelList):
# quadrature rule. The copy would raise a bare numpy broadcast error on
# a size mismatch and say nothing at all if the two rules merely order
# their points differently, so check the rules themselves here.
- from proteus.mprans.TADR import checkCoupledQuadrature
+ from proteus.kernels.TADR import checkCoupledQuadrature
checkCoupledQuadrature(self.model, 'Richards',
self.densityModel, 'density (transport) model')
diff --git a/proteus/mprans/SW2D.cpp b/proteus/kernels/SW2D.cpp
similarity index 100%
rename from proteus/mprans/SW2D.cpp
rename to proteus/kernels/SW2D.cpp
diff --git a/proteus/mprans/SW2D.h b/proteus/kernels/SW2D.h
similarity index 100%
rename from proteus/mprans/SW2D.h
rename to proteus/kernels/SW2D.h
diff --git a/proteus/mprans/SW2D.py b/proteus/kernels/SW2D.py
similarity index 99%
rename from proteus/mprans/SW2D.py
rename to proteus/kernels/SW2D.py
index c501d1ce4a..1a66d95b96 100644
--- a/proteus/mprans/SW2D.py
+++ b/proteus/kernels/SW2D.py
@@ -1,10 +1,10 @@
import proteus
-from proteus.mprans.cSW2D import *
+from proteus.kernels.cSW2D import *
from proteus.Comm import globalMax
import numpy as np
from proteus import cmeshTools
from proteus.Transport import OneLevelTransport
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/mprans/SW2DCV.cpp b/proteus/kernels/SW2DCV.cpp
similarity index 100%
rename from proteus/mprans/SW2DCV.cpp
rename to proteus/kernels/SW2DCV.cpp
diff --git a/proteus/mprans/SW2DCV.h b/proteus/kernels/SW2DCV.h
similarity index 100%
rename from proteus/mprans/SW2DCV.h
rename to proteus/kernels/SW2DCV.h
diff --git a/proteus/mprans/SW2DCV.py b/proteus/kernels/SW2DCV.py
similarity index 99%
rename from proteus/mprans/SW2DCV.py
rename to proteus/kernels/SW2DCV.py
index d830738f03..0c65a11717 100644
--- a/proteus/mprans/SW2DCV.py
+++ b/proteus/kernels/SW2DCV.py
@@ -1,7 +1,7 @@
import proteus
from proteus import FemTools
from proteus import LinearAlgebraTools as LAT
-from proteus.mprans.cSW2DCV import *
+from proteus.kernels.cSW2DCV import *
import numpy as np
from proteus import cmeshTools
from proteus.csparsity import CSR_INDEX_DTYPE
@@ -9,7 +9,7 @@
from proteus.Transport import Quadrature, logEvent, memory, BackwardEuler
from proteus.Transport import FluxBoundaryConditions, Comm, DOFBoundaryConditions
from proteus.Transport import cfemIntegrals, globalMax, SparseMat
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.TimeIntegration
import proteus.Transport
diff --git a/proteus/mprans/SedClosure.cpp b/proteus/kernels/SedClosure.cpp
similarity index 100%
rename from proteus/mprans/SedClosure.cpp
rename to proteus/kernels/SedClosure.cpp
diff --git a/proteus/mprans/SedClosure.h b/proteus/kernels/SedClosure.h
similarity index 100%
rename from proteus/mprans/SedClosure.h
rename to proteus/kernels/SedClosure.h
diff --git a/proteus/mprans/TADR.cpp b/proteus/kernels/TADR.cpp
similarity index 100%
rename from proteus/mprans/TADR.cpp
rename to proteus/kernels/TADR.cpp
diff --git a/proteus/mprans/TADR.h b/proteus/kernels/TADR.h
similarity index 100%
rename from proteus/mprans/TADR.h
rename to proteus/kernels/TADR.h
diff --git a/proteus/mprans/TADR.py b/proteus/kernels/TADR.py
similarity index 99%
rename from proteus/mprans/TADR.py
rename to proteus/kernels/TADR.py
index 5303ae45b8..574ce387a8 100644
--- a/proteus/mprans/TADR.py
+++ b/proteus/kernels/TADR.py
@@ -19,10 +19,10 @@
from proteus.NumericalFlux import Advection_DiagonalUpwind_Diffusion_IIPG_exterior
from proteus.LinearAlgebraTools import SparseMat, ParVec_petsc4py
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrix,ExplicitConsistentMassMatrixForVOF,TwoStageNewton
-from proteus.mprans.cTADR import cTADR_base
+from proteus.kernels.cTADR import cTADR_base
-from . import cArgumentsDict
-from proteus.mprans import EntropyViscosity
+from proteus import cArgumentsDict
+from proteus.kernels import EntropyViscosity
#: Coefficients(diagnostics=...): the run-time diagnostics a TADR model can log, each off by default since it
#: costs MPI reductions every step or call.
diff --git a/proteus/mprans/VOF.cpp b/proteus/kernels/VOF.cpp
similarity index 100%
rename from proteus/mprans/VOF.cpp
rename to proteus/kernels/VOF.cpp
diff --git a/proteus/mprans/VOF.h b/proteus/kernels/VOF.h
similarity index 100%
rename from proteus/mprans/VOF.h
rename to proteus/kernels/VOF.h
diff --git a/proteus/mprans/VOF.py b/proteus/kernels/VOF.py
similarity index 99%
rename from proteus/mprans/VOF.py
rename to proteus/kernels/VOF.py
index 586955aeb8..522308e319 100644
--- a/proteus/mprans/VOF.py
+++ b/proteus/kernels/VOF.py
@@ -21,13 +21,13 @@
from proteus.LinearAlgebraTools import SparseMat, ParVec_petsc4py
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrix,ExplicitConsistentMassMatrixForVOF,TwoStageNewton
from proteus import TimeIntegration
-from proteus.mprans.cVOF import *
+from proteus.kernels.cVOF import *
from proteus import *
from proteus.Transport import *
from proteus.Transport import OneLevelTransport
#from . import cVOF3P
-from . import cArgumentsDict
-from proteus.mprans import EntropyViscosity
+from proteus import cArgumentsDict
+from proteus.kernels import EntropyViscosity
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/mprans/VOF3P.cpp b/proteus/kernels/VOF3P.cpp
similarity index 100%
rename from proteus/mprans/VOF3P.cpp
rename to proteus/kernels/VOF3P.cpp
diff --git a/proteus/mprans/VOF3P.h b/proteus/kernels/VOF3P.h
similarity index 100%
rename from proteus/mprans/VOF3P.h
rename to proteus/kernels/VOF3P.h
diff --git a/proteus/mprans/VOF3P.py b/proteus/kernels/VOF3P.py
similarity index 99%
rename from proteus/mprans/VOF3P.py
rename to proteus/kernels/VOF3P.py
index 7cccef132e..bbacc403da 100644
--- a/proteus/mprans/VOF3P.py
+++ b/proteus/kernels/VOF3P.py
@@ -22,8 +22,8 @@
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrix,ExplicitConsistentMassMatrixForVOF,TwoStageNewton
from proteus import TimeIntegration
from . import cVOF3P
-from . import cArgumentsDict
-from proteus.mprans import EntropyViscosity
+from proteus import cArgumentsDict
+from proteus.kernels import EntropyViscosity
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/mprans/VOS3P.cpp b/proteus/kernels/VOS3P.cpp
similarity index 100%
rename from proteus/mprans/VOS3P.cpp
rename to proteus/kernels/VOS3P.cpp
diff --git a/proteus/mprans/VOS3P.h b/proteus/kernels/VOS3P.h
similarity index 100%
rename from proteus/mprans/VOS3P.h
rename to proteus/kernels/VOS3P.h
diff --git a/proteus/mprans/VOS3P.py b/proteus/kernels/VOS3P.py
similarity index 99%
rename from proteus/mprans/VOS3P.py
rename to proteus/kernels/VOS3P.py
index 19a133ac2d..7cf5d7d6d0 100644
--- a/proteus/mprans/VOS3P.py
+++ b/proteus/kernels/VOS3P.py
@@ -22,7 +22,7 @@
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrix,ExplicitConsistentMassMatrixForVOF
from proteus import TimeIntegration
from . import cVOS3P
-from . import cArgumentsDict
+from proteus import cArgumentsDict
import proteus.NumericalFlux
import proteus.ShockCapturing
import proteus.SubgridError
diff --git a/proteus/kernels/__init__.py b/proteus/kernels/__init__.py
new file mode 100644
index 0000000000..f38711247f
--- /dev/null
+++ b/proteus/kernels/__init__.py
@@ -0,0 +1,42 @@
+"""
+The model kernels: free surface incompressible flow and fluid/structure interaction (the former proteus.mprans),
+variably saturated flow (proteus.richards), compositional two-phase flow (proteus.m_comp_co2), elastic and plastic
+solids (proteus.elastoplastic) and the advection-diffusion-reaction model with the unfitted (cut cell) terms
+(proteus.ADR). One flat package since C49 R1; the old import paths are deprecated aliases (proteus/_kernel_aliases.py)
+that stay through 2.0.x and are removed at 2.1.
+"""
+
+__all__ = ["ADR",
+ "AddedMass",
+ "ArchiveBeams",
+ "CLSVOF",
+ "Dissipation",
+ "ElastoPlastic",
+ "GN_SW2DCV",
+ "Kappa",
+ "MCorr",
+ "MCorr3P",
+ "MoveMesh",
+ "NCLS",
+ "NCLS3P",
+ "Pres",
+ "PresInc",
+ "PresInit",
+ "RANS2P",
+ "RANS2P_IB",
+ "RANS3PF",
+ "RANS3PSed",
+ "RDLS",
+ "Richards",
+ "SW2D",
+ "SW2DCV",
+ "TADR",
+ "VOF",
+ "VOF3P",
+ "VOS3P",
+ "beamFEM",
+ "cADR",
+ "cElastoPlastic",
+ "cRichards",
+ "cm_comp_co2",
+ "m_comp_co2"]
diff --git a/proteus/mprans/beamFEM.py b/proteus/kernels/beamFEM.py
similarity index 100%
rename from proteus/mprans/beamFEM.py
rename to proteus/kernels/beamFEM.py
diff --git a/proteus/elastoplastic/cElastoPlastic.cpp b/proteus/kernels/cElastoPlastic.cpp
similarity index 100%
rename from proteus/elastoplastic/cElastoPlastic.cpp
rename to proteus/kernels/cElastoPlastic.cpp
diff --git a/proteus/richards/cRichards.cpp b/proteus/kernels/cRichards.cpp
similarity index 100%
rename from proteus/richards/cRichards.cpp
rename to proteus/kernels/cRichards.cpp
diff --git a/proteus/m_comp_co2/cm_comp_co2.cpp b/proteus/kernels/cm_comp_co2.cpp
similarity index 100%
rename from proteus/m_comp_co2/cm_comp_co2.cpp
rename to proteus/kernels/cm_comp_co2.cpp
diff --git a/proteus/m_comp_co2/co2_brine_eos.h b/proteus/kernels/co2_brine_eos.h
similarity index 100%
rename from proteus/m_comp_co2/co2_brine_eos.h
rename to proteus/kernels/co2_brine_eos.h
diff --git a/proteus/m_comp_co2/co2_brine_flash.h b/proteus/kernels/co2_brine_flash.h
similarity index 100%
rename from proteus/m_comp_co2/co2_brine_flash.h
rename to proteus/kernels/co2_brine_flash.h
diff --git a/proteus/elastoplastic/druckerPrager.h b/proteus/kernels/druckerPrager.h
similarity index 100%
rename from proteus/elastoplastic/druckerPrager.h
rename to proteus/kernels/druckerPrager.h
diff --git a/proteus/m_comp_co2/jet2.h b/proteus/kernels/jet2.h
similarity index 100%
rename from proteus/m_comp_co2/jet2.h
rename to proteus/kernels/jet2.h
diff --git a/proteus/m_comp_co2/m_comp_co2.h b/proteus/kernels/m_comp_co2.h
similarity index 99%
rename from proteus/m_comp_co2/m_comp_co2.h
rename to proteus/kernels/m_comp_co2.h
index 4c72e6a057..bb6d633700 100644
--- a/proteus/m_comp_co2/m_comp_co2.h
+++ b/proteus/kernels/m_comp_co2.h
@@ -9,7 +9,7 @@
#include
#include "CompKernel.h"
#include "ModelFactory.h"
-#include "../mprans/ArgumentsDict.h"
+#include "ArgumentsDict.h"
#include "pyarray.h"
#include "../pskRelations.h"
// Compositional CO2-brine EOS + analytic (p,z) flash (P3). Standalone headers
diff --git a/proteus/m_comp_co2/m_comp_co2.py b/proteus/kernels/m_comp_co2.py
similarity index 99%
rename from proteus/m_comp_co2/m_comp_co2.py
rename to proteus/kernels/m_comp_co2.py
index 2716af897c..398354740d 100644
--- a/proteus/m_comp_co2/m_comp_co2.py
+++ b/proteus/kernels/m_comp_co2.py
@@ -11,7 +11,7 @@
from proteus.Transport import TC_base, NonlinearEquation, logEvent, memory
from proteus.Transport import FluxBoundaryConditions, Comm, cfemIntegrals
from proteus.Transport import DOFBoundaryConditions, Quadrature
-from proteus.mprans import cArgumentsDict
+from proteus import cArgumentsDict
from proteus.LinearAlgebraTools import SparseMat
from proteus import TimeIntegration
from proteus.NonlinearSolvers import ExplicitLumpedMassMatrixForRichards
@@ -880,7 +880,7 @@ def apply_dissolution_flash(self, t):
recovers the instantaneous local-equilibrium flash (dissolves in place),
finite k_d lets the free-gas plume rise before it dissolves over a
slower timescale. X_sat is the physical solubility mass fraction. See
- the kernel comment in proteus/m_comp_co2/m_comp_co2.h.
+ the kernel comment in proteus/kernels/m_comp_co2.h.
"""
if self.dissolution_mode != 'flash' or self.X_sat <= 0.0:
return
diff --git a/proteus/elastoplastic/mcdp.h b/proteus/kernels/mcdp.h
similarity index 100%
rename from proteus/elastoplastic/mcdp.h
rename to proteus/kernels/mcdp.h
diff --git a/proteus/elastoplastic/mohrCoulomb.h b/proteus/kernels/mohrCoulomb.h
similarity index 100%
rename from proteus/elastoplastic/mohrCoulomb.h
rename to proteus/kernels/mohrCoulomb.h
diff --git a/proteus/elastoplastic/mohrCoulomb2.h b/proteus/kernels/mohrCoulomb2.h
similarity index 100%
rename from proteus/elastoplastic/mohrCoulomb2.h
rename to proteus/kernels/mohrCoulomb2.h
diff --git a/proteus/elastoplastic/tresca.h b/proteus/kernels/tresca.h
similarity index 100%
rename from proteus/elastoplastic/tresca.h
rename to proteus/kernels/tresca.h
diff --git a/proteus/elastoplastic/vonMises.h b/proteus/kernels/vonMises.h
similarity index 100%
rename from proteus/elastoplastic/vonMises.h
rename to proteus/kernels/vonMises.h
diff --git a/proteus/m_comp_co2/__init__.py b/proteus/m_comp_co2/__init__.py
index 5d5b48589a..66a46b021b 100644
--- a/proteus/m_comp_co2/__init__.py
+++ b/proteus/m_comp_co2/__init__.py
@@ -1,6 +1,6 @@
-"""
-Modules for simulating variably saturated single-phase flow
-"""
+"""Deprecated: the compositional CO2-brine kernel is in proteus.kernels (C49 R1); see proteus._kernel_aliases."""
+from proteus import _kernel_aliases
-__all__ = ["m_comp_co2",
- "cm_comp_co2"]
+_kernel_aliases.install(__name__)
+
+__all__ = ["m_comp_co2", "cm_comp_co2"]
diff --git a/proteus/mprans/BodyDynamics.py b/proteus/mbd/BodyDynamics.py
similarity index 99%
rename from proteus/mprans/BodyDynamics.py
rename to proteus/mbd/BodyDynamics.py
index 7e9f03307f..a832d9d45d 100644
--- a/proteus/mprans/BodyDynamics.py
+++ b/proteus/mbd/BodyDynamics.py
@@ -16,7 +16,7 @@ class instance acting as a rigid body. To set a shape as a rigid body, use
Parameters
----------
- shape: proteus.mprans.SpatialTools.Shape_RANS
+ shape: proteus.SpatialTools.Shape_RANS
Class instance of the shape associated to the rigid body calculations.
cfl_target: Optional[float]
UNUSED (to implement), sets the maximum displacement of the body
diff --git a/proteus/mbd/CouplingFSI.pyx b/proteus/mbd/CouplingFSI.pyx
index 290b2b831b..fb3569278d 100644
--- a/proteus/mbd/CouplingFSI.pyx
+++ b/proteus/mbd/CouplingFSI.pyx
@@ -56,7 +56,7 @@ cdef extern from "index_type.h":
#: width of proteus_index_t in index_type.h, same rule as cmeshTools.INDEX_DTYPE
_INDEX_DTYPE = np.dtype('i%d' % sizeof(proteus_index_t))
# chrono Python headers
-from proteus.mprans import BodyDynamics as bd
+from proteus.mbd import BodyDynamics as bd
import pychrono as chrono
from pychrono import fea as chrono_fea
@@ -160,7 +160,7 @@ cdef class ProtChBody:
----------
shape: SpatialTools.Shape
instance of shape from proteus.SpatialTools or
- proteus.mprans.SpatialTools
+ proteus.SpatialTools
"""
assert self.Shape is None, 'Shape '+self.Shape.name+' was already attached'
self.Shape = shape
diff --git a/proteus/mprans/BoundaryConditions.pxd b/proteus/mprans/BoundaryConditions.pxd
deleted file mode 100644
index 76da140831..0000000000
--- a/proteus/mprans/BoundaryConditions.pxd
+++ /dev/null
@@ -1,201 +0,0 @@
-# cython: language_level=3
-cimport cython
-from libcpp cimport bool
-cimport numpy as np
-from proteus.BoundaryConditions cimport (BC_Base,
- BoundaryCondition)
-# needed for cython > 0.27
-from proteus cimport BoundaryConditions
-
-ctypedef double[:,:,:] double_memview3
-ctypedef double[:,:] double_memview2
-ctypedef double[:] double_memview1
-ctypedef int[:] int_memview1
-
-# ctypedef double (*cpp_uOfXT) (BC_RANS, double[:], double)
-
-cdef class BC_RANS(BC_Base):
- cdef double[:] zero_array
- cdef double f
- cdef __cppClass_WavesCharacteristics waves
- cdef object body
- cdef double[:] wind_speed
- cdef double[:, :] body_python_rot_matrix
- cdef double[:] body_python_last_pos
- cdef double[:] body_python_h
- cdef public:
- # dirichlet
- cdef BoundaryCondition p_dirichlet
- cdef BoundaryCondition u_dirichlet
- cdef BoundaryCondition v_dirichlet
- cdef BoundaryCondition w_dirichlet
- cdef BoundaryCondition phi_dirichlet
- cdef BoundaryCondition vof_dirichlet
- cdef BoundaryCondition k_dirichlet
- cdef BoundaryCondition dissipation_dirichlet
- cdef BoundaryCondition pAddedMass_dirichlet
- # advective
- cdef BoundaryCondition p_advective
- cdef BoundaryCondition u_advective
- cdef BoundaryCondition v_advective
- cdef BoundaryCondition w_advective
- cdef BoundaryCondition vof_advective
- cdef BoundaryCondition k_advective
- cdef BoundaryCondition dissipation_advective
- #diffusive
- cdef BoundaryCondition u_diffusive
- cdef BoundaryCondition v_diffusive
- cdef BoundaryCondition w_diffusive
- cdef BoundaryCondition k_diffusive
- cdef BoundaryCondition dissipation_diffusive
- # mesh
- cdef BoundaryCondition hx_dirichlet
- cdef BoundaryCondition hy_dirichlet
- cdef BoundaryCondition hz_dirichlet
- cdef BoundaryCondition u_stress
- cdef BoundaryCondition v_stress
- cdef BoundaryCondition w_stress
- # sediment solver
- cdef BoundaryCondition us_dirichlet
- cdef BoundaryCondition vs_dirichlet
- cdef BoundaryCondition ws_dirichlet
- cdef BoundaryCondition vos_dirichlet
- cdef BoundaryCondition us_advective
- cdef BoundaryCondition vs_advective
- cdef BoundaryCondition ws_advective
- cdef BoundaryCondition vos_advective
- cdef BoundaryCondition us_diffusive
- cdef BoundaryCondition vs_diffusive
- cdef BoundaryCondition ws_diffusive
- # projection scheme
- cdef BoundaryCondition pInit_dirichlet
- cdef BoundaryCondition pInc_dirichlet
- cdef BoundaryCondition pInit_advective
- cdef BoundaryCondition pInc_advective
- cdef BoundaryCondition pInit_diffusive
- cdef BoundaryCondition pInc_diffusive
- # clsvof
- cdef BoundaryCondition clsvof_dirichlet
- cdef BoundaryCondition clsvof_advective
- cdef BoundaryCondition clsvof_diffusive
-
-
- # functions
- # cpdef void reset(self)
- # cpdef void setNonMaterial(self)
- # cpdef void setTank(self)
- # cpdef void setFixedNodes(self)
- # cpdef void setNoSlip(self)
- # cpdef void setFreeSlip(self)
- # cpdef void setAtmosphere(self, double[:] orientation=*, double vof_air=*)
- # cpdef void setMoveMesh(self, double[:] last_pos, double[:] h=*, double[:,:] rot_matrix=*)
- @cython.locals(hx=np.ndarray)
- cpdef double[:] __cpp_MoveMesh_h(self, double[:] x, double t)
- cpdef double __cpp_MoveMesh_hx(self, double[:] x, double t)
- cpdef double __cpp_MoveMesh_hy(self, double[:] x, double t)
- cpdef double __cpp_MoveMesh_hz(self, double[:] x, double t)
-# @cython.locals(waveHeight=double, wavePhi=double,
-# water_speed=double_memview1, x_max=double_memview1,
-# u=cython.p_double, H=double)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(self, double[:] x, double t)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(self, double[:] x, double t)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(self, double[:] x, double t)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(self, double[:] x, double t)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(self, double[:] x, double t)
- cdef double __cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(self, double[:] x, double t)
-
-ctypedef double[:] (*cfvel) (double[3], double) # pointer to velocity function
-ctypedef double (*cfeta) (double[3], double) # pointer to eta function
-ctypedef double[:] (*cfvelrel) (RelaxationZone, double[3], double) # pointer to velocity function of RelaxationZone class
-ctypedef double (*cfphirel) (RelaxationZone, double[3]) # pointer to phi function of RelaxationZone class
-ctypedef double (*cfphiwave) (RelaxationZone, double[3]) # pointer to phi function of RelaxationZone class
-ctypedef np.float64_t float64_t
-ctypedef np.int64_t int64_t
-
-cdef class RelaxationZone:
- cdef double[:] wind_speed
- cdef double[:] u_calc # calculated velocity
- # wave characteristics (if any)
- cdef cfvelrel uu
- cdef cfphirel phi
- cdef double mwl
- cdef cfeta eta
- cdef double waveHeight
- cdef double wavePhi
- cdef double waterSpeed
- cdef int nd
- cdef double[:] zero_vel
- cdef __cppClass_WavesCharacteristics waves
- cdef public:
- object Shape
- str zone_type
- double dragAlpha
- double dragBeta
- double porosity
- double epsFact_solid
- double epsFact_porous
- double vert_axis
- double[:] center
- double[:] orientation
- cpdef void calculate_init(self)
- cdef double[:] calculate_vel(self, cython.p_double x, double t)
- @cython.locals(xx=double_memview1, waveHeight=double, wavePhi=double,
- waterSpeed=double_memview1, x_max=double_memview1, H=double,
- u=cython.double[3], o1=double, o2=double, o3=double)
- cdef double[:] __cpp_calculate_vel_wave(self, double* x, double t)
- cdef double[:] __cpp_calculate_vel_zero(self, double* x, double t)
- cdef double calculate_phi(self, double* x)
- @cython.locals(d1=double, d2=double, d3=double, phi=double,
- o1=double, o2=double, o3=double)
- cdef double __cpp_calculate_phi_porous(self, double[3] x)
- cdef double __cpp_calculate_phi_porous_sponge(self, double[3] x)
-
-cdef class RelaxationZoneWaveGenerator:
- cdef int nd # dimension
- cdef int max_flag # maximum region flag of relaxation zones (initialised in calculate_init)
- cdef np.ndarray zones_array # zones array for fast access
- cdef public:
- dict zones # zones dictionary
- object model # model attached to zone
- object ar #
- # cpdef RelaxationZoneWaveGenerator attachModel(self, dict, int) # needed
- # cpdef void attachAuxiliaryVariables(self, dict) # needed
- @cython.locals(zones=np.ndarray)
- cpdef void calculate_init(self)
- cpdef void calculate(self)
- @cython.locals(m=object, zone=RelaxationZone, mType=int, nE=int, nk=int,
- qx=double_memview3, x=cython.double[3], t=double, nl=int,
- q_phi_porous=double_memview2, phi=double,
- q_velocity_solid=double_memview3, u=double_memview1, mTypes=int_memview1)
- cdef void __cpp_iterate(self) # main iteration loop
-
-
-cdef class __cppClass_WavesCharacteristics:
- cdef int vert_axis # vertical axis
- # relaxation zone info (if any)
- cdef double[:] center # center of zone
- cdef double[:] orientation # orientation of zone
- # zero array
- cdef double[:] zero_vel
- cdef double[:] _b_or
- cdef double[:] wind_speed
- cdef double vof_air
- cdef double vof_water
- cdef double smoothing
- cdef public:
- # wave class from WaveTools
- object WT
- @cython.locals(phi=double, waterSpeed=double_memview1,
- H=double)
- cdef double[:] __cpp_calculate_velocity(self, double* x, double t)
- @cython.locals(ux=double_memview1, b0=double, b1=double, b2=double, u0=double,
- u1=double, u2=double)
- cdef double __cpp_calculate_pressure(self, double* x, double t)
- @cython.locals(level=double)
- cdef double __cpp_calculate_phi(self, double* x, double t)
- @cython.locals(phi=double, H=double)
- cdef double __cpp_calculate_vof(self, double* x, double t)
- @cython.locals(H=double)
- cdef double __cpp_calculate_smoothing_H(self, double phi)
-
-cdef double* __x_to_cpp(double[:])
diff --git a/proteus/mprans/BoundaryConditions.py b/proteus/mprans/BoundaryConditions.py
deleted file mode 100644
index 2ef1676fc0..0000000000
--- a/proteus/mprans/BoundaryConditions.py
+++ /dev/null
@@ -1,1665 +0,0 @@
-#!python
-# distutils: language = c++
-# cython: profile=True, binding=True, embedsignature=True
-# cython: wraparound=False
-# cython: boundscheck=False
-# cython: initializedcheck=False
-import cython
-
-"""
-Module for creating boundary conditions. Imported in mprans.SpatialTools.py
-"""
-import os, sys
-import numpy as np
-from proteus import (AuxiliaryVariables,
- BoundaryConditions,
- Comm)
-from proteus.ctransportCoefficients import (smoothedHeaviside,
- smoothedHeaviside_integral)
-from proteus import WaveTools as wt
-from proteus.Profiling import logEvent
-from math import cos, sin, sqrt, atan2, acos, asin
-from mpi4py import MPI
-from scipy import spatial
-
-__all__ = ['BC_RANS',
- 'RelaxationZone',
- 'RelaxationZoneWaveGenerator',
- '_cppClass_WavesCharacteristics',
- 'WallFunctions',
- 'kWall']
-
-
-class BC_RANS(BoundaryConditions.BC_Base):
- """
- Class regrouping boundary conditions for two-phase flows
- """
-
- def __init__(self, shape=None, name=None, b_or=None, b_i=0., nd=None):
- super(BC_RANS, self).__init__(shape=shape, name=name, b_or=b_or, b_i=b_i, nd=nd)
- # _dirichlet
- self.p_dirichlet = BoundaryCondition() # pressure
- self.u_dirichlet = BoundaryCondition() # velocity u
- self.v_dirichlet = BoundaryCondition() # velocity v
- self.w_dirichlet = BoundaryCondition() # velocity w
- self.phi_dirichlet = BoundaryCondition() # phi
- self.vof_dirichlet = BoundaryCondition() # VOF
- self.k_dirichlet = BoundaryCondition() # kappa
- self.dissipation_dirichlet = BoundaryCondition() # dissipation
- self.pAddedMass_dirichlet = BoundaryCondition()
- # _advective
- self.p_advective = BoundaryCondition()
- self.u_advective = BoundaryCondition()
- self.v_advective = BoundaryCondition()
- self.w_advective = BoundaryCondition()
- self.vof_advective = BoundaryCondition()
- self.k_advective = BoundaryCondition()
- self.dissipation_advective = BoundaryCondition()
- # _diffusive
- self.u_diffusive = BoundaryCondition()
- self.v_diffusive = BoundaryCondition()
- self.w_diffusive = BoundaryCondition()
- self.k_diffusive = BoundaryCondition()
- self.dissipation_diffusive = BoundaryCondition()
- # moveMesh boundary conditions
- self.hx_dirichlet = BoundaryCondition()
- self.hy_dirichlet = BoundaryCondition()
- self.hz_dirichlet = BoundaryCondition()
- self.u_stress = BoundaryCondition()
- self.v_stress = BoundaryCondition()
- self.w_stress = BoundaryCondition()
- self.u_stress.uOfXT = 0.
- self.v_stress.uOfXT = 0.
- self.w_stress.uOfXT = 0.
- # sediment solver
- self.us_dirichlet = BoundaryCondition() # sediment velocity u
- self.vs_dirichlet = BoundaryCondition() # sediment velocity v
- self.ws_dirichlet = BoundaryCondition() # sediment velocity w
- self.vos_dirichlet = BoundaryCondition() # VOS
- self.us_advective = BoundaryCondition()
- self.vs_advective = BoundaryCondition()
- self.ws_advective = BoundaryCondition()
- self.vos_advective = BoundaryCondition()
- self.us_diffusive = BoundaryCondition()
- self.vs_diffusive = BoundaryCondition()
- self.ws_diffusive = BoundaryCondition()
- # projection scheme
- self.pInit_dirichlet = BoundaryCondition() # initial pressure
- self.pInc_dirichlet = BoundaryCondition() # pressure increment
- self.pInit_advective = BoundaryCondition()
- self.pInc_advective = BoundaryCondition()
- self.pInit_diffusive = BoundaryCondition()
- self.pInc_diffusive = BoundaryCondition()
- # clsvof
- self.clsvof_dirichlet = BoundaryCondition()
- self.clsvof_advective = BoundaryCondition()
- self.clsvof_diffusive = BoundaryCondition()
-
- def reset(self):
- """
- Resets all BoundaryCondtion functions to None, apart from the BCs
- affecting: moving mesh
- """
- # self.BC_type = 'None'
- self.p_dirichlet.resetBC()
- self.pInit_dirichlet.resetBC()
- self.pInc_dirichlet.resetBC()
- self.u_dirichlet.resetBC()
- self.v_dirichlet.resetBC()
- self.w_dirichlet.resetBC()
- self.phi_dirichlet.resetBC()
- self.vof_dirichlet.resetBC()
- self.k_dirichlet.resetBC()
- self.dissipation_dirichlet.resetBC()
- self.us_dirichlet.resetBC()
- self.vs_dirichlet.resetBC()
- self.ws_dirichlet.resetBC()
- self.vos_dirichlet.resetBC()
- self.p_advective.resetBC()
- self.pInit_advective.resetBC()
- self.pInc_advective.resetBC()
- self.u_advective.resetBC()
- self.v_advective.resetBC()
- self.w_advective.resetBC()
- self.vof_advective.resetBC()
- self.k_advective.resetBC()
- self.dissipation_advective.resetBC()
- self.us_advective.resetBC()
- self.vs_advective.resetBC()
- self.ws_advective.resetBC()
- self.vos_advective.resetBC()
- self.pInit_diffusive.resetBC()
- self.pInc_diffusive.resetBC()
- self.u_diffusive.resetBC()
- self.v_diffusive.resetBC()
- self.w_diffusive.resetBC()
- self.k_diffusive.resetBC()
- self.dissipation_diffusive.resetBC()
- self.us_diffusive.resetBC()
- self.vs_diffusive.resetBC()
- self.ws_diffusive.resetBC()
- self.clsvof_dirichlet.resetBC()
- self.clsvof_advective.resetBC()
- self.clsvof_diffusive.resetBC()
-
- def setNonMaterial(self):
- """
- Sets non-material boundary conditions (diffusive flux and advective vof
- to 0.).
- """
- self.reset()
- self.BC_type = 'NonMaterial'
- self.vof_advective.setConstantBC(0.)
- self.vos_advective.setConstantBC(0.)
- self.p_advective.setConstantBC(0.)
- self.u_advective.setConstantBC(0.)
- self.v_advective.setConstantBC(0.)
- self.w_advective.setConstantBC(0.)
- self.u_diffusive.setConstantBC(0.)
- self.v_diffusive.setConstantBC(0.)
- self.w_diffusive.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
- self.ws_diffusive.setConstantBC(0.)
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
- self.pInc_diffusive.setConstantBC(0.)
-
- def setTank(self, b_or=None):
- if b_or is None:
- assert self._b_or is not None, 'Boundary orientation must be defined!'
- b_or = self._b_or
- self.u_stress.uOfXT = 0.
- self.v_stress.uOfXT = 0.
- self.w_stress.uOfXT = 0.
- self.hx_dirichlet.resetBC()
- self.hy_dirichlet.resetBC()
- self.hz_dirichlet.resetBC()
- if b_or[0] == 1 or b_or[0] == -1:
- self.hx_dirichlet.setConstantBC(0.)
- self.u_stress.uOfXT = None
- elif b_or[1] == 1 or b_or[1] == -1:
- self.hy_dirichlet.setConstantBC(0.)
- self.v_stress.uOfXT = None
- elif len(b_or) > 2 and (b_or[2] == 1 or b_or[2] == -1):
- self.hz_dirichlet.setConstantBC(0.)
- self.w_stress.uOfXT = None
-
- def setFixedNodes(self):
- """
- For moving domains: fixes nodes/boundary
- """
- self.hx_dirichlet.setConstantBC(0.)
- self.hy_dirichlet.setConstantBC(0.)
- self.hz_dirichlet.setConstantBC(0.)
- self.u_stress.uOfXT = 0.
- self.v_stress.uOfXT = 0.
- self.w_stress.uOfXT = 0.
-
- def setNoSlip(self):
- """
- Sets no slip conditions at the boundary
- """
- self.reset()
- self.BC_type = 'NoSlip'
- # dirichlet
- self.u_dirichlet.setConstantBC(0.)
- self.v_dirichlet.setConstantBC(0.)
- self.w_dirichlet.setConstantBC(0.)
- self.us_dirichlet.setConstantBC(0.)
- self.vs_dirichlet.setConstantBC(0.)
- self.ws_dirichlet.setConstantBC(0.)
- self.k_dirichlet.setConstantBC(1e-20)
- self.dissipation_dirichlet.setConstantBC(1e-10)
- # advective
- self.p_advective.setConstantBC(0.)
- self.pInit_advective.setConstantBC(0.)
- self.pInc_advective.setConstantBC(0.)
- self.vof_advective.setConstantBC(0.)
- self.vos_advective.setConstantBC(0.)
- # diffusive
- self.pInc_diffusive.setConstantBC(0.)
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
-
- def setFreeSlip(self):
- """
- Sets free slip conditions at the boundary
- """
- self.reset()
- self.BC_type = 'FreeSlip'
- # dirichlet
- self.k_dirichlet.setConstantBC(1e-20)
- self.dissipation_dirichlet.setConstantBC(1e-10)
- # advective
- self.p_advective.setConstantBC(0.)
- self.pInit_advective.setConstantBC(0.)
- self.pInc_advective.setConstantBC(0.)
- self.u_advective.setConstantBC(0.)
- self.v_advective.setConstantBC(0.)
- self.w_advective.setConstantBC(0.)
- self.us_advective.setConstantBC(0.)
- self.vs_advective.setConstantBC(0.)
- self.ws_advective.setConstantBC(0.)
- self.vof_advective.setConstantBC(0.)
- self.vos_advective.setConstantBC(0.)
- # diffusive
- self.u_diffusive.setConstantBC(0.)
- self.v_diffusive.setConstantBC(0.)
- self.w_diffusive.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
- self.ws_diffusive.setConstantBC(0.)
- self.pInc_diffusive.setConstantBC(0.)
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
-
- def setConstantInletVelocity(self, U, ramp, kk, dd , b_or):
- """
- Sets constant velocity in each inlet face with ramping up and turbulence properties
- """
- self.reset()
- self.BC_type = 'constantInletVelocity'
- Uin = np.dot(U,b_or)
- uu = U[0]
- vv = U[1]
- ww = U[2]
-
- # dirichlet
- self.u_dirichlet.setLinearRamp(ramp, uu)
- self.v_dirichlet.setLinearRamp(ramp ,vv)
- self.w_dirichlet.setLinearRamp(ramp ,ww)
- self.us_dirichlet.setConstantBC(0.)
- self.vs_dirichlet.setConstantBC(0.)
- self.ws_dirichlet.setConstantBC(0.)
- self.k_dirichlet.setConstantBC(kk)
- self.dissipation_dirichlet.setConstantBC(dd)
- #advective
- self.p_advective.setLinearRamp(ramp, Uin)
- self.pInit_advective.setConstantBC(0.)
- self.pInc_advective.setLinearRamp(ramp,Uin)
- # diffusive
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
- self.ws_diffusive.setConstantBC(0.)
- def setConstantOutletPressure(self, p, rho, g ,kk, dd, b_or):
- """
- Sets constant pressure in each outlet face for single phase flows
- """
- self.reset()
- self.BC_type = 'constantOutletPressure'
- # dirichlet
- a1 = rho*g
- self.u_dirichlet.setConstantBC(0.)
- self.v_dirichlet.setConstantBC(0.)
- self.w_dirichlet.setConstantBC(0.)
- self.us_dirichlet.setConstantBC(0.)
- self.vs_dirichlet.setConstantBC(0.)
- self.ws_dirichlet.setConstantBC(0.)
-
- self.p_dirichlet.setLinearBC(p,a1)
- self.pInit_dirichlet.setLinearBC(p, a1)
- self.pInc_dirichlet.setConstantBC(0.)
- self.k_dirichlet.setConstantBC(kk)
- self.dissipation_dirichlet.setConstantBC(dd)
-
- # diffusive
- if b_or[0] == 1. or b_or[0] == -1.:
- self.u_diffusive.setConstantBC(0.)
- if b_or[1] == 1. or b_or[1] == -1.:
- self.v_diffusive.setConstantBC(0.)
- if b_or[2] == 1. or b_or[2] == -1.:
- self.w_diffusive.setConstantBC(0.)
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
- self.ws_diffusive.setConstantBC(0.)
-
- def setAtmosphere(self, orientation=None, vof_air=1.,kInflow=None,dInflow=None):
- """
- Sets atmosphere boundary conditions (water can come out)
- (!) pressure dirichlet set to 0 for this BC
-
- Parameters
- ----------
- orientation: Optional[array_like]
- orientation of the boundary. Optional if orientation was already
- passed when creating the BC_RANS class instance.
- vof_air: Optional[float]
- VOF value of air (default is 1.)
- """
- self.BC_type = 'Atmosphere'
- if orientation is None and self._b_or is not None:
- orientation = self._b_or
- assert orientation is not None, 'oritentation must be set for BC'
- self.reset()
- self.p_dirichlet.setConstantBC(0.)
- self.pInc_dirichlet.setConstantBC(0.)
- self.pInit_dirichlet.setConstantBC(0.)
- self.vof_dirichlet.setConstantBC(vof_air) # air
- self.vos_dirichlet.setConstantBC(0.)
- self.u_dirichlet.setConstantBC(0.)
- self.v_dirichlet.setConstantBC(0.)
- self.w_dirichlet.setConstantBC(0.)
- self.us_dirichlet.setConstantBC(0.)
- self.vs_dirichlet.setConstantBC(0.)
- self.ws_dirichlet.setConstantBC(0.)
- self.k_dirichlet.setConstantBC(1e-20)
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_dirichlet.setConstantBC(1e-10)
- self.dissipation_diffusive.setConstantBC(0.)
-
- if orientation[0] == 1. or orientation[0] == -1.:
- self.u_diffusive.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- if orientation[1] == 1. or orientation[1] == -1.:
- self.v_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
- if orientation[2] == 1. or orientation[2] == -1.:
- self.w_diffusive.setConstantBC(0.)
- self.ws_diffusive.setConstantBC(0.)
-
- if kInflow is not None:
- self.k_dirichlet.setConstantBC(kInflow)
- else:
- logEvent("WARNING: Dirichlet condition for k in "+str(self.BC_type)+" has not been set. Ignore if RANS is not used")
- if dInflow is not None:
- self.dissipation_dirichlet.setConstantBC(dInflow)
- else:
- logEvent("WARNING: Dirichlet condition for dissipation in "+str(self.BC_type)+" has not been set. Ignore if RANS is not used")
- def setRigidBodyMoveMesh(self, body):
- """
- Sets boundary conditions for moving the mesh with a rigid body
-
- Parameters
- ----------
- last_pos: array_like
- last position of rigig body
- h: array_like
- displacement of the body
- rot_matrix:
- rotation matrix describing displament due to rotation between last
- position and new position (3x3 array)
-
- (!) if set manually, the input arrays should be updated externally
- without loosing their memory address
- """
- def get_DBC_h(i):
- def DBC_h(x, t, n=None):
- x_0 = x - body.last_position
- new_x_0 = np.dot(x_0, body.rotation_matrix)
- hx = new_x_0 - x_0 + body.h
- return hx[i]
- return DBC_h
- self.hx_dirichlet.uOfXT = get_DBC_h(0)
- self.hy_dirichlet.uOfXT = get_DBC_h(1)
- if body.nd > 2:
- self.hz_dirichlet.uOfXT = get_DBC_h(2)
-
- def setChMoveMesh(self, body):
- self.hx_dirichlet.uOfXT = lambda x, t, n=None: body.hx(x, t)
- self.hy_dirichlet.uOfXT = lambda x, t, n=None: body.hy(x, t)
- self.hz_dirichlet.uOfXT = lambda x, t, n=None: body.hz(x, t)
-
- def setTurbulentDirichlet(self, kVal, dissipationVal):
- """
- Sets only dirichlet conditions for turbulence at the boundary.
- It's a rough approximation for evalueting the near wall turbulence
- based on empirical assumptions.
- More sophisticated wall functions are recommended to be used.
-
- Parameters
- ----------
- kVal: float.
- constant value applied on k.
- dissipationVal: float.
- constant value applied on dissipation.
- """
- # turbulent boundary conditions
- self.k_dirichlet.setConstantBC(kVal)
- self.dissipation_dirichlet.setConstantBC(dissipationVal)
- self.k_advective.resetBC()
- self.dissipation_advective.resetBC()
- self.k_diffusive.resetBC()
- self.dissipation_diffusive.resetBC()
-
- def setTurbulentZeroGradient(self):
- """
- Sets only zero-gradient conditions for turbulence at the boundary.
- More sophisticated wall functions are recommended to be used.
- """
- # turbulent boundary conditions
- self.k_dirichlet.setConstantBC(0.)
- self.dissipation_dirichlet.setConstantBC(0.)
- self.k_advective.resetBC()
- self.dissipation_advective.resetBC()
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
-
- def setWallFunction(self, wall, shearStress=False):
- """
- Sets turbulent boundaries for wall treatment.
- Calculation made on nodes outside the viscous sublayer and based
- on assumption on the velocity profile close to the wall in order to
- impose the wall shear stress.
-
- Parameters
- ----------
- wall: wall object.
- BoundaryConditions class to be attached for setting up
- all the turbulent parameters.
- shearStress: True/False.
- At the moment version with shearStress=False is the only one that
- returns good results.
- Keep it False at the moment!
-
- - When True, the wall function prescribes diffusive boundaries
- for velocity and kappa. It's like imposing the shear stress.
- - If False, the wall function prescribes dirichlet conditions.
- """
- wf = wall
- self.reset()
- self.setNoSlip()
- self.BC_type = "Wall function"
- self.dissipation_diffusive.resetBC()
- self.k_dirichlet.uOfXT = lambda x, t, n=None: wf.get_k_dirichlet(x, t, n)
- self.dissipation_dirichlet.uOfXT = lambda x, t, n=None: wf.get_dissipation_dirichlet(x, t ,n)
- self.u_dirichlet.uOfXT = lambda x, t, n=None: wf.get_u_dirichlet(x, t ,n)
- self.v_dirichlet.uOfXT = lambda x, t, n=None: wf.get_v_dirichlet(x, t ,n)
- self.w_dirichlet.uOfXT = lambda x, t, n=None: wf.get_w_dirichlet(x, t ,n)
- """
- self.dissipation_dirichlet.uOfXT = lambda x, t: wf.get_dissipation_dirichlet(x, t)
- self.vof_advective.setConstantBC(0.)
- self.p_advective.setConstantBC(0.)
- if shearStress:
- #self.k_dirichlet.uOfXT = lambda x, t: wf.get_k_dirichlet(x, t)
- self.k_advective.setConstantBC(0.)
- self.u_diffusive.uOfXT = lambda x, t: wf.get_u_diffusive(x, t)
- self.v_diffusive.uOfXT = lambda x, t: wf.get_v_diffusive(x, t)
- self.w_diffusive.uOfXT = lambda x, t: wf.get_w_diffusive(x, t)
- self.k_diffusive.setConstantBC(0.)
- else:
- self.u_dirichlet.uOfXT = lambda x, t: wf.get_u_dirichlet(x, t)
- self.v_dirichlet.uOfXT = lambda x, t: wf.get_v_dirichlet(x, t)
- self.w_dirichlet.uOfXT = lambda x, t: wf.get_w_dirichlet(x, t)
- self.k_dirichlet.uOfXT = lambda x, t: wf.get_k_dirichlet(x, t)
- """
- def setMoveMesh(self, last_pos, h=(0., 0., 0.), rot_matrix=None):
- """
- Sets boundary conditions for moving the mesh with a rigid body
-
- Parameters
- ----------
- last_pos: array_like
- last position of rigig body
- h: array_like
- displacement of the body
- rot_matrix:
- rotation matrix describing displament due to rotation between last
- position and new position (3x3 array)
-
- (!) if set manually, the input arrays should be updated externally
- without loosing their memory address
- """
- if rot_matrix is None:
- rot_matrix = np.array([[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]])
- self.body_python_rot_matrix = rot_matrix
- self.body_python_last_pos = last_pos
- self.body_python_h = h
- self.hx_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hx(x, t)
- self.hy_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hy(x, t)
- self.hz_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_MoveMesh_hz(x, t)
-
- def __cpp_MoveMesh_h(self, x, t):
- cython.declare(x_0=cython.double[3])
- cython.declare(new_x_0=cython.double[3])
- hx = np.zeros(3)
- x_0[0] = x[0] - self.body_python_last_pos[0]
- x_0[1] = x[1] - self.body_python_last_pos[1]
- x_0[2] = x[2] - self.body_python_last_pos[2]
- new_x_0 = np.dot(x_0, self.body_python_rot_matrix)
- hx[0] = new_x_0[0] - x_0[0] + self.body_python_h[0]
- hx[1] = new_x_0[1] - x_0[1] + self.body_python_h[1]
- hx[2] = new_x_0[2] - x_0[2] + self.body_python_h[2]
- return hx
-
- def __cpp_MoveMesh_hx(self, x, t):
- return self.__cpp_MoveMesh_h(x, t)[0]
-
- def __cpp_MoveMesh_hy(self, x, t):
- return self.__cpp_MoveMesh_h(x, t)[1]
-
- def __cpp_MoveMesh_hz(self, x, t):
- return self.__cpp_MoveMesh_h(x, t)[2]
-
- def setUnsteadyTwoPhaseVelocityInlet(self, wave, smoothing, vert_axis=None,orientation=None,
- wind_speed=None, vof_air=1., vof_water=0.,kInflow=1e-30, dInflow = 1e-10):
- """
- Imposes a velocity profile on the fluid with input wave and wind
- conditions.
-
- Parameters
- ----------
- wave: proteus.WaveTools
- class describing a wave (from proteus.WaveTools)
- smoothing: float
- smoothing distance (typically 3.*he)
- vert_axis: Optional[int]
- index of vertical position vector (x:0, y:1, z:2), must always be
- aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
- wind_speed: Optional[array_like]
- speed of air phase
- vof_air: Optional[float]
- VOF value of air (default is 1.)
- vof_water: Optional[float]
- VOF value of water (default is 0.)
-
- Below the sea water level: fluid velocity to wave speed.
- Above the sea water level: fluid velocity set to wind speed
- (with smoothing).
- """
- self.reset()
- if vert_axis is None:
- vert_axis = self.nd - 1
- if wind_speed is None:
- wind_speed = np.zeros(3)
- if orientation is not None:
- b_or = orientation
- else:
- b_or=self._b_or
- assert b_or is not None, "ERROR: Boundary orientation for Unsteady flow inlet is not defined"
- self.waves = __cppClass_WavesCharacteristics(waves=wave, vert_axis=vert_axis, b_or=b_or,
- wind_speed=wind_speed, smoothing=smoothing, vof_water=vof_water, vof_air=vof_air)
-
- self.u_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(x, t)
- self.v_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(x, t)
- self.w_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(x, t)
- self.phi_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(x, t)
- self.vof_dirichlet.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(x, t)
- self.p_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)
- self.pInc_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)
-
- self.pInc_diffusive.setConstantBC(0.0)
- self.pInit_advective.uOfXT = lambda x, t, n=None: self.__cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(x, t)#setConstantBC(0.0)
- self.vos_dirichlet.setConstantBC(0.0)
- self.us_dirichlet.setConstantBC(0.0)
- self.vs_dirichlet.setConstantBC(0.0)
- self.ws_dirichlet.setConstantBC(0.0)
- self.k_dirichlet.setConstantBC(kInflow)
- self.dissipation_dirichlet.setConstantBC(dInflow)
- self.dissipation_diffusive.setConstantBC(0.)
- self.k_diffusive.setConstantBC(0.0)
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_u_dirichlet(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_velocity(xx, t)[0]
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_v_dirichlet(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_velocity(xx, t)[1]
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_w_dirichlet(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_velocity(xx, t)[2]
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_p_advective(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_pressure(xx, t)
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_phi_dirichlet(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_phi(xx, t)
-
- def __cpp_UnsteadyTwoPhaseVelocityInlet_vof_dirichlet(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return self.waves.__cpp_calculate_vof(xx, t)
-
- def setTwoPhaseVelocityInlet(self, U, waterLevel, smoothing, Uwind=None,
- vert_axis=None, air=1., water=0.,
- kInflow=None, dissipationInflow=None,
- kInflowAir=None, dissipationInflowAir=None):
- """
- Imposes a velocity profile lower than the sea level and an open
- boundary for higher than the sealevel.
-
- Parameters
- ----------
- U: list.
- Velocity vector at the global system.
- Uwind: list.
- Air velocity vector at the global system.
- waterLevel: float.
- water level at global coordinate system.
- smoothing: float.
- range within smoothing function is valid.
- [3.0 times mesh element size can be a good value]
- vert_axis: optional.
- index of vertical in position vector, must always be
- aligned with gravity, by default set to 1].
- air: optional.
- Volume fraction for air (1.0 by default).
- water: optional.
- Volume fraction for water (0.0 by default).
- kInflow: float (optional).
- K inflow value for turbulent model imposed at the boundary.
- dissipationInflow: float (optional).
- Dissipation inflow value for turbulent model imposed at the boundary.
- kInflowAir: float (optional).
- Air K inflow value for turbulent model imposed at the boundary.
- dissipationInflowAir: float (optional).
- Air dissipation inflow value for turbulent model imposed at the boundary.
-
- Notes
- -----
- Below the seawater level, the condition returns the _dirichlet and
- p_advective condition according to the inflow velocity.
- Above the sea water level, the condition returns the gravity as zero,
- and sets _dirichlet condition to zero, only if there is a zero inflow
- velocity component.
- (!) This condition is best used for boundaries and gravity aligned with
- one of the main axes.
- """
- self.reset()
- self.BC_type = 'TwoPhaseVelocityInlet'
-
- if vert_axis is None:
- vert_axis = self.nd - 1
- if Uwind is None:
- Uwind = np.zeros(3)
-
- U = np.array(U)
- Uwind = np.array(Uwind)
-
- def get_inlet_ux_dirichlet(i):
- def ux_dirichlet(x, t, n=None):
- phi = x[vert_axis] - waterLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- u = H * Uwind[i] + (1 - H) * U[i]
- return u
- return ux_dirichlet
-
- def inlet_phi_dirichlet(x, t, n=None):
- phi = x[vert_axis] - waterLevel
- return phi
-
- def inlet_vof_dirichlet(x, t, n=None):
- phi = x[vert_axis] - waterLevel
- if phi >= smoothing:
- H = 1.
- elif smoothing > 0 and -smoothing < phi < smoothing:
- H = smoothedHeaviside(smoothing, phi)
- elif phi <= -smoothing:
- H = 0.
- vof = H * air + (1 - H) * water
- return vof
-
- def inlet_p_advective(x, t, n=None):
- b_or = self._b_or
- phi = x[vert_axis] - waterLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- u = H * Uwind + (1 - H) * U
- # This is the normal velocity, based on the inwards boundary
- # orientation -b_or
- u_p = np.sum(u * np.abs(b_or))
- return -u_p
-
- def inlet_k_dirichlet(x, t, n=None):
- phi = x[vert_axis] - waterLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- return H * kInflowAir + (1 - H) * kInflow
-
- def inlet_dissipation_dirichlet(x, t, n=None):
- phi = x[vert_axis] - waterLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing, phi-smoothing/2.)#smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- return H * dissipationInflowAir + (1 - H) * dissipationInflow
-
- self.u_dirichlet.uOfXT = get_inlet_ux_dirichlet(0)
- self.v_dirichlet.uOfXT = get_inlet_ux_dirichlet(1)
- self.w_dirichlet.uOfXT = get_inlet_ux_dirichlet(2)
- self.phi_dirichlet.uOfXT = inlet_phi_dirichlet
- self.vof_dirichlet.uOfXT = inlet_vof_dirichlet
- self.p_advective.uOfXT = inlet_p_advective
- if kInflow is not None:
- self.k_dirichlet.uOfXT = inlet_k_dirichlet
- self.k_advective.resetBC()
- self.k_diffusive.resetBC()
- if dissipationInflow is not None:
- self.dissipation_dirichlet.uOfXT = inlet_dissipation_dirichlet
- self.dissipation_advective.resetBC()
- self.dissipation_diffusive.resetBC()
-
- def setHydrostaticPressureOutletWithDepth(self, seaLevel, rhoUp, rhoDown, g,
- refLevel, smoothing, orientation=None,U=None, Uwind=None,
- pRef=0.0, vert_axis=None,
- air=1.0, water=0.0,
- kInflow=None, dissipationInflow=None,
- kInflowAir=None, dissipationInflowAir=None):
- """
- Returns the pressure and vof profile based on the known depth.
- If the boundary is aligned with one of the main axes, sets the tangential
- velocity components to zero as well.
- (!) This condition is best used for boundaries and gravity aligned with
- one of the main axes.
-
- Parameters
- ----------
- rhoUp: Phase density of the upper part.
- rhoDown: Phase density of the lower part.
- g: Gravitational acceleration vector.
- refLevel: Level at which pressure = pRef.
- pRef: Reference value for the pressure at x[vert_axis]=refLevel, by default set to 0.
- vert_axis: index of vertical in position vector, must always be aligned with gravity, by default set to 1.
- """
- self.reset()
-
- if vert_axis is None:
- vert_axis = self.nd - 1
-
- def hydrostaticPressureOutletWithDepth_p_dirichlet(x, t , n=None):
- p_top = pRef
- phi_top = refLevel - seaLevel
- phi = x[vert_axis] - seaLevel
- return p_top - g[vert_axis] * (rhoDown * (phi_top - phi) +
- (rhoUp - rhoDown) *
- (smoothedHeaviside_integral(smoothing, phi_top)
- -
- smoothedHeaviside_integral(smoothing, phi)))
-
- def hydrostaticPressureOutletWithDepth_phi_dirichlet(x, t, n=None):
- phi = x[vert_axis] - seaLevel
- return phi
-
- def hydrostaticPressureOutletWithDepth_vof_dirichlet(x, t, n=None):
- phi = x[vert_axis] - seaLevel
- if phi >= smoothing:
- H = 1.
- elif smoothing > 0 and -smoothing < phi < smoothing:
- H = smoothedHeaviside(smoothing, phi)
- elif phi <= -smoothing:
- H = 0.
- return H * air + (1 - H) * water
-
- def inlet_k_dirichlet(x, t, n=None):
- phi = x[vert_axis] - seaLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- return H * kInflowAir + (1 - H) * kInflow
-
- def inlet_dissipation_dirichlet(x, t, n=None):
- phi = x[vert_axis] - seaLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- return H * dissipationInflowAir + (1 - H) * dissipationInflow
-
- if orientation is not None:
- b_or = orientation
- else:
- b_or=self._b_or
- assert b_or is not None, "ERROR: Boundary orientation for Hydrostatic flow outlet is not defined"
- if b_or[0] == 1. or b_or[0] == -1.:
- self.v_dirichlet.setConstantBC(0.)
- self.w_dirichlet.setConstantBC(0.)
- self.u_diffusive.setConstantBC(0.)
- if b_or[1] == 1. or b_or[1] == -1.:
- self.u_dirichlet.setConstantBC(0.)
- self.w_dirichlet.setConstantBC(0.)
- self.v_diffusive.setConstantBC(0.)
- if b_or[2] == 1. or b_or[2] == -1.:
- self.u_dirichlet.setConstantBC(0.)
- self.v_dirichlet.setConstantBC(0.)
- self.w_diffusive.setConstantBC(0.)
-#sediment
- self.us_advective.setConstantBC(0.)
- self.vs_advective.setConstantBC(0.)
- self.ws_advective.setConstantBC(0.)
- self.vos_advective.setConstantBC(0.)
- self.us_diffusive.setConstantBC(0.)
- self.vs_diffusive.setConstantBC(0.)
-#end sediment
- self.p_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_p_dirichlet
- self.pInit_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_p_dirichlet
- self.pInc_dirichlet.setConstantBC(0.)
- self.phi_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_phi_dirichlet
- self.vof_dirichlet.uOfXT = hydrostaticPressureOutletWithDepth_vof_dirichlet
- self.k_diffusive.setConstantBC(0.)
- self.dissipation_diffusive.setConstantBC(0.)
- if U is not None:
- def get_inlet_ux_dirichlet(i):
- def ux_dirichlet(x, t, n=None):
- phi = x[vert_axis] - seaLevel
- if phi <= 0.:
- H = 0.0
- elif 0 < phi <= smoothing:
- H = smoothedHeaviside(smoothing/2., phi - smoothing/2.)
- else:
- H = 1.0
- return H * Uwind[i] + (1 - H) * U[i]
- return ux_dirichlet
-
- if Uwind is None:
- Uwind = np.zeros(3)
- U = np.array(U)
- Uwind = np.array(Uwind)
- self.u_dirichlet.uOfXT = get_inlet_ux_dirichlet(0)
- self.v_dirichlet.uOfXT = get_inlet_ux_dirichlet(1)
- self.w_dirichlet.uOfXT = get_inlet_ux_dirichlet(2)
- self.u_diffusive.resetBC()
-
- if kInflow is not None:
- self.k_dirichlet.uOfXT = inlet_k_dirichlet
- self.k_advective.resetBC()
- self.k_diffusive.resetBC()
- if dissipationInflow is not None:
- self.dissipation_dirichlet.uOfXT = inlet_dissipation_dirichlet
- self.dissipation_advective.resetBC()
- self.dissipation_diffusive.resetBC()
-
-# for regions
-
-class RelaxationZone:
- """
- Holds information about a relaxation zone (wave generation/absorption
- or porous zone)
-
- Parameters
- ----------
- zone_type: string
- type of zone, can be set to 'absorption', 'generation', or 'porous'
- center: array_like
- coordinates of center of the zone
- orientation: array_like
- orientation for absorption/generation zones: from boundary to tank
- epsFact_porous: float
- half the zone length
- waves: Optional[proteus.WaveTools]
- class instance of a wave from proteus.WaveTools (must be set for
- generation zone)
- shape: Optional[proteus.SpatialTools.Shape]
- shape class instance containing region
- dragAlpha: Optional[float]
- parameter for porous zones (default: 0.5/1.005e-6)
- dragBeta: Optional[float]
- parameter for porous zones (default: 0.)
- porosity: Optional[float]
- parameter for porous zone (default: 1.)
- vert_axis: Optional[int]
- index of vertical position vector (x:0, y:1, z:2), must always be
- aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
- smoothing: Optional[float]
- smoothing distance from the free surface (usually 3*he)
- vof_water: Optional[int]
- VOF value of water (default: 0)
- vof_air: Optional[int]
- VOF value of air (default: 1)
- """
-
- def __cinit__(self, zone_type, center, orientation, epsFact_porous,
- waves=None, shape=None, wind_speed=np.array([0., 0., 0.]),
- dragAlpha=0.5/1.005e-6, dragBeta=0., porosity=1., vert_axis=None, smoothing=0.,
- vof_water=0., vof_air=1.):
- self.Shape = shape
- self.nd = self.Shape.Domain.nd
- self.zone_type = zone_type
- self.center = center
- self.orientation = orientation
- if vert_axis is None:
- vert_axis = self.Shape.Domain.nd - 1
- self.vert_axis = vert_axis
- if waves is not None:
- self.waves = __cppClass_WavesCharacteristics(waves=waves, wind_speed=wind_speed, vert_axis=vert_axis,
- smoothing=smoothing, vof_water=vof_water, vof_air=vof_air)
- self.epsFact_porous = epsFact_porous
- self.dragAlpha = dragAlpha
- self.dragBeta = dragBeta
- self.porosity = porosity
- self.zero_vel = np.zeros(3)
-
- def calculate_init(self):
- if self.zone_type == 'generation':
- # self.u = &self.waves.u
- # self.eta = &self.waves.eta
- self.uu = self.__cpp_calculate_vel_wave
- self.phi = self.__cpp_calculate_phi_porous_sponge
- elif self.zone_type == 'absorption':
- self.uu = self.__cpp_calculate_vel_zero
- self.phi = self.__cpp_calculate_phi_porous_sponge
- elif self.zone_type == 'porous':
- self.uu = self.__cpp_calculate_vel_zero
- self.phi = self.__cpp_calculate_phi_porous
-
- def calculate_phi(self, x):
- return self.phi(self, x)
-
- def __cpp_calculate_phi_porous_sponge(self, x):
- """
- Used for RelaxationZone only
- """
- cython.declare(d=cython.double[3], o=cython.double[3])
- d[0] = self.center[0] - x[0]
- d[1] = self.center[1] - x[1]
- o[0] = self.orientation[0]
- o[1] = self.orientation[1]
- if self.nd > 2:
- d[2] = self.center[2] - x[2]
- o[2] = self.orientation[2]
- else:
- d[2] = 0
- o[2] = 0
- phi = o[0] * d[0] + o[1] * d[1] + o[2] * d[2]
- return phi
-
- def __cpp_calculate_phi_porous(self, x):
- IN_POROUS_ZONE=-10000.0
- return IN_POROUS_ZONE
-
- def calculate_vel(self, x, t):
- cython.declare(d=cython.double[3], o=cython.double[3])
- d[0] = x[0]
- d[1] = x[1]
- d[2] = x[2]
- return self.uu(self, d, t)
-
- def calculate_phi_python(self, x):
- cython.declare(xx=cython.double[3], tt=cython.double)
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- ph = self.phi(self, xx)
- return ph
-
- def calculate_vel_python(self, x, t, n=None):
- cython.declare(xx=cython.double[3], tt=cython.double)
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- tt = t
- return self.uu(self, xx, tt)
-
- def __cpp_calculate_vel_zero(self, x, t):
- return self.zero_vel
-
- def __cpp_calculate_vel_wave(self, x, t):
- return self.waves.__cpp_calculate_velocity(x, t)
-
-
-class RelaxationZoneWaveGenerator:
- """
- Prescribe a velocity penalty scaling in a material zone via a
- Darcy-Forchheimer penalty
-
- Parameters
- ----------
- zones: dict
- dictionary with key as the region flag and values as a RelaxationZone
- class
- nd: int
- number of dimensions of domain
- """
-
- def __init__(self, zones, nd):
- self.zones = zones
- self.nd = nd
-
- def attachModel(self, model, ar):
- self.model = model
- self.ar = ar
- return self
-
- def attachAuxiliaryVariables(self, avDict):
- pass
-
- def calculate_init(self):
- max_key = 0
- for key, zone in list(self.zones.items()):
- zone.calculate_init()
- if key > max_key:
- max_key = key
- self.max_flag = max_key
- self.zones_array = np.empty(self.max_flag + 1, dtype=RelaxationZone)
- for key, zone in list(self.zones.items()):
- self.zones_array[key] = zone
-
- def calculate(self):
- self.__cpp_iterate()
-
- def __cpp_iterate(self):
- nl = len(self.model.levelModelList)
- for l in range(nl): # usually only 1
- # initialisation of variables before costly loop
- m = self.model.levelModelList[l]
- nE = m.coefficients.q_phi.shape[0]
- nk = m.coefficients.q_phi.shape[1]
- t = m.timeIntegration.t
- qx = m.q['x']
- q_phi_porous = m.coefficients.q_phi_porous
- q_velocity_porous = m.coefficients.q_velocity_porous
- mTypes = m.mesh.elementMaterialTypes
- # costly loop
- for eN in range(nE):
- mType = mTypes[eN]
- if mType <= self.max_flag:
- zone = self.zones_array[mType]
- if zone is not None:
- for k in range(nk):
- x[0] = qx[eN, k, 0]
- x[1] = qx[eN, k, 1]
- x[2] = qx[eN, k, 2]
- phi = zone.calculate_phi(x)
- q_phi_porous[eN, k] = phi
- u = zone.calculate_vel(x, t)
- q_velocity_porous[eN, k, 0] = u[0]
- q_velocity_porous[eN, k, 1] = u[1]
- if self.nd > 2:
- q_velocity_porous[eN, k, 2] = u[2]
- m.q['phi_porous'] = q_phi_porous
- m.q['velocity_porous'] = q_velocity_porous
-
-
-class __cppClass_WavesCharacteristics:
- """
- Class holding information from WaveTools waves and cnvering it to
- boundary conditions to use for relaxation zones and wave inlet.
- This class is created automatically when passing WaveTools class
- instances to a relaxation zone or wave inlet BC.
-
- Parameters
- ----------
- wave: proteus.WaveTools
- class describing a wave (from proteus.WaveTools)
- vert_axis: int
- index of vertical position vector (x:0, y:1, z:2), must always be
- aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
- wind_speed: Optional[array_like]
- speed of air phase
- b_or: Optional[array_like]
- boundary orientation. Necessary for pressure calculations. Used
- for boundary conditions but not in relaxation zones.
- smoothing: Optional[float]
- smoothing distance from the free surface (usually 3*he)
- vof_water: Optional[float]
- VOF value of water (default: 0)
- vof_air: Optional[float]
- VOF value of air (default: 1)
- """
-
- def __init__(self, waves, vert_axis, wind_speed=None, b_or=None,
- smoothing=0., vof_water=0., vof_air=1.):
- self.WT = waves # wavetools wave
- self.vert_axis = vert_axis
- self.zero_vel = np.zeros(3)
- self._b_or = b_or
- self.smoothing = smoothing
- self.vof_air = vof_air
- self.vof_water = vof_water
- if wind_speed is None:
- self.wind_speed = self.zero_vel
- else:
- self.wind_speed = wind_speed
-
- def __cpp_calculate_velocity(self, x, t):
- # u is returned as a memoryview (pxd: cdef double[:]); a C array declared here lives on this
- # function's stack and the view dangles once it returns. Unnoticed until the module was built
- # with line tracing, which reuses that stack: the caller then read 0.0.
- u = np.empty(3)
- cython.declare(xx=cython.double[3])
- cython.declare(x_max=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- phi = self.__cpp_calculate_phi(x, t)
- if phi <= 0.:
- # no smoothing below mwl, or wave peak could get chopped off
- H = 0
- waterSpeed = self.WT.u(xx, t)
- elif 0 < phi <= self.smoothing:
- # smoothing on half the range of VOF (above wave crest)
- H = smoothedHeaviside(self.smoothing/2., phi - self.smoothing/2.)
- # use max velocity of wave for water
- x_max[0] = x[0]
- x_max[1] = x[1]
- x_max[2] = x[2]
- x_max[self.vert_axis] = x[self.vert_axis] - phi
- waterSpeed = self.WT.u(x_max, t)
- else:
- H = 1.
- waterSpeed = self.zero_vel
- u[0] = H * self.wind_speed[0] + (1 - H) * waterSpeed[0]
- u[1] = H * self.wind_speed[1] + (1 - H) * waterSpeed[1]
- u[2] = H * self.wind_speed[2] + (1 - H) * waterSpeed[2]
- return u
-
- def __cpp_calculate_pressure(self, x, t):
- # This is the normal velocity, based on the outwards boundary
- # orientation b_or
- # needs to be equal to -ux_dirichlet
- ux = self.__cpp_calculate_velocity(x, t)
- b0, b1, b2 = self._b_or[0], self._b_or[1], self._b_or[2]
- u0, u1, u2 = ux[0], ux[1], ux[2]
- return b0 * u0 + b1 * u1 + b2 * u2
-
- def __cpp_calculate_phi(self, x, t):
- cython.declare(xx=cython.double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- level = self.WT.mwl + self.WT.eta(xx, t)
- return x[self.vert_axis] - level
-
- def __cpp_calculate_vof(self, x, t):
- phi = self.__cpp_calculate_phi(x, t)
- H = self.__cpp_calculate_smoothing_H(phi)
- return H
-
- def __cpp_calculate_smoothing_H(self, phi):
- if phi >= self.smoothing:
- H = 1.
- elif self.smoothing > 0 and -self.smoothing < phi < self.smoothing:
- H = smoothedHeaviside(self.smoothing, phi)
- elif phi <= -self.smoothing:
- H = 0.
- return H
-
-
-def __x_to_cpp(x):
- cython.declare(xx=double[3])
- xx[0] = x[0]
- xx[1] = x[1]
- xx[2] = x[2]
- return xx
-
-
-class WallFunctions(AuxiliaryVariables.AV_base):
- """
- Auxiliary variable used to calculate attributes of an associated shape
- class instance acting as a wall.
- """
-
- def __init__(self, turbModel, kWall, Y, Yplus, U0, nu=1.004e-6, Cmu=0.09, K=0.41, B=5.57):
- """
- Sets turbulent boundaries for wall treatment.
- Calculation made on nodes outside the viscous sublayer and based
- on assumption on the velocity profile close to the wall in order to
- impose the wall shear stress.
-
- - k is assumed to be constant in the fully turbulent region close to the wall,
- in this way kv = kp.
- - dissipation is calculated.
-
- Parameters
- ----------
- turbModel: string.
- 'ke' or 'kw', for switching between k-epsilon or k-omega models.
- kWall: object.
- Class kWall object for extracting kappa from the model.
- Y: float.
- size of the nearest element to the boundary.
- Yplus: float.
- size of the nearest element to the boundary in terms of wall unit.
- U0: array_like.
- stream velocity.
- nu: float.
- fluid viscosity.
- Cmu: float.
- turbulent viscosity constant.
- K: float.
- von Karman coefficient.
- B: float.
- roughness coefficient for walls.
- """
- self.turbModel = turbModel
- self.Y = Y
- self.Yplus = Yplus
- self.U0 = U0
- self.nu = nu
- self.Cmu = Cmu
- self.K = K
- self.B = B
- # initialise variables
- self.Ubound = np.zeros(3)
- self.kappa = 1e-10
- self.tau_rho = 0.
- self.utAbs = 1e-10
- self.ut = np.zeros(3)
- self.x = np.zeros(3)
- self.t = 0.
- self.model = None
- self.xi, self.element, self.rank = None, None, None
- self.kWall = kWall
-
- def attachModel(self, model, ar):
- """
- Attaches model to auxiliary variable
- """
- self.model = model
- self.ar = ar
- self.nd = model.levelModelList[0].nSpace_global
- self.Closure_0_model = model.levelModelList[0].coefficients.Closure_0_model
- self.Closure_1_model = model.levelModelList[0].coefficients.Closure_1_model
- return self
-
- def attachAuxiliaryVariables(self, avDict):
- pass
-
- def calculate_init(self):
- pass
-
- def calculate(self):
- pass
-
- def getLocalNearestNode(self, coords, kdtree):
- """
- Finds nearest node to coordinates (local)
- Parameters
- ----------
- coords: array_like
- coordinates from which to find nearest node
- kdtree: scipy.spatial.cKDTree
- instance of scipy kdtree
- Returns
- -------
- node: int
- nearest node index
- distance: float
- distance to nearest node
- """
- # determine local nearest node distance
- distance, node = kdtree.query(coords)
- return node, distance
-
- def getLocalElement(self, femSpace, coords, node):
- """
- Given coordinates and its nearest node, determine if it is on a
- local element.
- Parameters
- ----------
- femSpace: object
- finite element space
- coords: array_like
- coordinates from which to element
- node: int
- nearest node index
- Returns
- -------
- eN: int or None
- local index of element (None if not found)
- """
- patchBoundaryNodes = set()
- checkedElements = []
- # nodeElementOffsets give the indices to get the elements sharing the node
- statem1 = node + 1 < len(femSpace.mesh.nodeElementOffsets)
- for eOffset in range(femSpace.mesh.nodeElementOffsets[node], femSpace.mesh.nodeElementOffsets[node + 1]):
- eN = femSpace.mesh.nodeElementsArray[eOffset]
- checkedElements.append(eN)
- # union of set
- patchBoundaryNodes |= set(femSpace.mesh.elementNodesArray[eN])
- # evaluate the inverse map for element eN (global to local)
- xi = femSpace.elementMaps.getInverseValue(eN, coords)
- #J = femSpace.elementMaps.getJacobianValues(eN, )
- # query whether xi lies within the reference element
- if femSpace.elementMaps.referenceElement.onElement(xi):
- return eN
- # extra loop if case coords is in neighbour element
- for node in patchBoundaryNodes:
- for eOffset in range(femSpace.mesh.nodeElementOffsets[node], femSpace.mesh.nodeElementOffsets[node + 1]):
- eN = femSpace.mesh.nodeElementsArray[eOffset]
- if eN not in checkedElements:
- checkedElements.append(eN)
- # evaluate the inverse map for element eN
- xi = femSpace.elementMaps.getInverseValue(eN, coords)
- # query whether xi lies within the reference element
- if femSpace.elementMaps.referenceElement.onElement(xi):
- return eN
- # no elements found
- return None
-
- def findElementContainingCoords(self, coords):
- """
- Given global coordinates of a point, returns
- local coordinates and the owner of the point.
-
- Parameters
- ----------
- coords: array_like
- global coordinates to look for
- Returns
- -------
- xi:
- local coordinates
- eN: int
- (local) element number
- rank: int
- processor rank containing element
- """
- comm = Comm.get().comm.tompi4py()
- xi = owning_proc = element = rank = None # initialised as None
- self.xi, self.element, self.rank = xi, element, rank
- # get nearest node on each processor
- # comm.barrier()
- self.u = self.model.levelModelList[0].u
- self.femSpace_velocity = self.u[1].femSpace
- nodes_kdtree = spatial.cKDTree(self.model.levelModelList[0].mesh.nodeArray)
- nearest_node, nearest_node_distance = self.getLocalNearestNode(coords, nodes_kdtree)
- # look for element containing coords on each processor (if it exists)
- local_element = self.getLocalElement(self.femSpace_velocity, coords, nearest_node)
- if local_element:
- xi = self.femSpace_velocity.elementMaps.getInverseValue(local_element, coords)
- rank = comm.rank
- else:
- xi = None
- rank = None
- #rank = comm.allreduce(rank, op=MPI.MAX)
- return xi, local_element, rank
-
- def getFluidVelocityLocalCoords(self, xi, element, rank):
- """
- Given local details, returns velocity field at those coordinates.
-
- Parameters
- ----------
- xi:
- local coords in element
- element: int
- element number (local to processor 'rank')
- rank: int
- rank of processor owning the element
- """
- comm = Comm.get().comm.tompi4py()
- if comm.rank == rank:
- u = self.u[1].getValue(element, xi)
- v = self.u[2].getValue(element, xi)
- if self.nd > 2:
- w = self.u[3].getValue(element, xi)
- if self.nd <= 2:
- w = 0.
- else:
- u = v = w = None
- return u, v, w
-
- def setYplusNormalDirection(self, x, t,n, relax=1.0):
- """
- Return the point at y+ distance in normal
- direction from the boundary.
- """
- # near wall point
- if len(n) < 3:
- nP = (relax * self.Y * (-n[:2])) + x[:2]
- else:
- nP = (relax * self.Y * (-n)) + x
- return nP
-
- def extractVelocity(self, x, t, n):
- """
- Extraction of the velocity at y+ distance from the boundary.
- """
- coords = self.setYplusNormalDirection(x, t, n)
- xi, element, rank = self.findElementContainingCoords(coords)
- if rank is not None:
- u, v, w = self.getFluidVelocityLocalCoords(xi, element, rank)
- else:
- relax = 0.5
- while rank is None:
- coords_relax = self.setYplusNormalDirection(x, t, n ,relax)
- xi, element, rank = self.findElementContainingCoords(coords_relax)
- relax *= 0.5
- # just use the element containing the boundary quadrature point to interpolate to the y+ point
- u, v, w = self.getFluidVelocityLocalCoords(self.femSpace_velocity.elementMaps.getInverseValue(element, coords),
- element,
- rank)
- self.xi, self.element, self.rank = xi, element, rank
- return u, v, w
-
- def tangentialVelocity(self, x, t, n, uInit=None):
- """
- Given the velocity, calculates its
- tangential component to the wall.
-
- Parameters
- ----------
- uInit: True/False.
- Switch for initializing the module.
- True only during the first time step.
- """
- n=np.pad(n,(0,3-n.shape[0]),mode='constant',constant_values=0.0)
- if uInit is True or self.model is None:
- u0, u1, u2 = self.U0
- else:
- u0, u1, u2 = self.extractVelocity(x, t, n)
- self.meanV = np.array([u0, u1, u2])
- # projection of u vector over an ortoganal plane to n
- self.tanU = self.meanV - self.meanV * (n**2)
- # tangential unit vector
- self.tV = self.tanU/np.sqrt(np.sum(self.tanU**2))
-
- def getVariables(self, x, t):
- """
- Calculates velocity, gradient of the velocity and
- kappa according with wall functions theory (see
- S. B. Pope pg 442-443).
- """
- comm = Comm.get().comm.tompi4py()
- # Extraction of kappa
- self.kappa = self.kWall.getKappa(x, t, self.xi, self.element, self.rank)
- # Calculation of nominal friction velocity based on kappa
- self.utStar = (self.kappa**0.5) * (self.Cmu**0.25)
- self.Ystar = self.Y * self.utStar / self.nu
- # Absolute value of the extracted velocity at y+ location.
- Up = np.sqrt(np.sum(self.tanU**2))
- # viscous layer
- if self.Ystar < 11.225:
- self.Ustar = self.Ystar
- self.uDir = (self.utStar*self.Ystar) * self.tV
- self.gradU = ( (self.utStar**2)/self.nu ) * self.tV
- # log-law layer
- else:
- # Wall function theory from S.B. Pope, page 442-443
- E = np.exp(self.B * self.K)
- self.Ustar = self.utStar * np.log(E * self.Ystar) / self.K
- self.utAbs = self.utStar * np.sqrt(Up/self.Ustar)
- # Velocity vector and velocity gradient multiplied by the tangential vector unit
- self.gradU = (self.utAbs/(self.K*self.Y)) * self.tV
- # Linear approximation for velocity at the wall (using the gradU of the logLaw)
- self.uDir = self.tanU - (self.gradU * self.Y)
-
- def get_u_dirichlet(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- return self.uDir[0]
-
- def get_v_dirichlet(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- return self.uDir[1]
-
- def get_w_dirichlet(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- return self.uDir[2]
-
- def get_k_dirichlet(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t,n, uInit)
- self.getVariables(x, t)
- return self.kappa
-
- def get_dissipation_dirichlet(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- d = 0.
- if self.turbModel == 'ke':
- d = (self.utStar**3)/(self.K*self.Y)
- elif self.turbModel == 'kw' and self.kappa > 0.:
- d = np.sqrt(self.kappa)/(self.K*self.Y*(self.Cmu**0.25))
- return d
-
- def get_u_diffusive(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- gradU = self.gradU[0]
- return gradU
-
- def get_v_diffusive(self, x, t, n ):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- gradU = self.gradU[1]
- return gradU
-
- def get_w_diffusive(self, x, t, n):
- if t > 0.:
- uInit = False
- else:
- uInit = True
- self.tangentialVelocity(x, t, n, uInit)
- self.getVariables(x, t)
- gradU = self.gradU[2]
- return gradU
-
-
-class kWall(AuxiliaryVariables.AV_base):
- """
- Auxiliary variable used to calculate attributes of an associated shape
- class instance acting as a wall for the k variable.
- """
-
- def __init__(self, Y, Yplus, nu=1.004e-6, Cmu=0.09):
- """
- Sets turbulent boundaries for wall treatment.
- """
- self.kappa = 1e-10
- self.Y = Y
- self.Yplus = Yplus
- self.nu = nu
- self.model = None
- self.Cmu = Cmu
-
- def attachModel(self, model, ar):
- """
- Attaches model to auxiliary variable
- """
- self.model = model
- self.ar = ar
- self.nd = model.levelModelList[0].nSpace_global
- return self
-
- def attachAuxiliaryVariables(self, avDict):
- pass
-
- def calculate_init(self):
- pass
-
- def calculate(self):
- pass
-
- def getFluidKappaLocalCoords(self, xi, element, rank):
- """
-
- Parameters
- ----------
- xi:
- local coords in element
- element: int
- element number (local to processor 'rank')
- rank: int
- rank of processor owning the element
- """
- comm = Comm.get().comm.tompi4py()
- # solution of the selected model
- self.u = self.model.levelModelList[0].u
- #self.femSpace_kappa = self.u[0].femSpace
- if comm.rank == rank:
- kappa = self.u[0].getValue(element, xi)
- else:
- kappa = None
- return kappa
-
- def kappaNearWall(self, xi, element, rank, kInit=None):
- if kInit is True or self.model is None:
- self.ut = self.Yplus * self.nu / self.Y
- self.kappa = (self.ut**2)/np.sqrt(self.Cmu)
- else:
- self.kappa = self.getFluidKappaLocalCoords(xi, element, rank)
-
- def getKappa(self, x, t, xi, element, rank):
- if t > 0.:
- kInit = False
- else:
- kInit = True
- self.kappaNearWall(xi, element, rank, kInit)
- return abs(self.kappa)
\ No newline at end of file
diff --git a/proteus/mprans/SpatialTools.py b/proteus/mprans/SpatialTools.py
deleted file mode 100644
index 5450b61f42..0000000000
--- a/proteus/mprans/SpatialTools.py
+++ /dev/null
@@ -1,2170 +0,0 @@
-"""
-This module adds functionality to proteus.SpatialTools module by enabling
-two-phase flow functionality such as converting shapes to moving rigid bodies,
-or adding wave absorption and generation zones.
-
-
-Example
--------
-from proteus import Domain
-from proteus.mprans import SpatialTools as st
-import numpy as np
-
-domain = Domain.PlanarStraightLineGraphDomain()
-tank = st.Tank2D(domain. dim=[4., 4.])
-tank.setSponge(left=0.4)
-tank.setAbsorptionZones(left=true)
-shape = st.Rectangle(domain, dim=[0.5, 0.5], coords=[1., 1.])
-shape.setRigidBody()
-shape2.rotate(np.pi/3.)
-shape2.BC.left.setNoSlip()
-
-st.assembleDomain(domain)
-"""
-from math import cos, sin, sqrt, atan2, acos, asin
-from itertools import compress
-import csv
-import numbers
-import os
-import numpy as np
-from proteus import AuxiliaryVariables, Archiver, Comm, Profiling, Gauges
-from proteus.Profiling import logEvent
-from proteus.mprans import BoundaryConditions as bc
-from proteus.mprans import BodyDynamics as bd
-from proteus.SpatialTools import (Shape,
- Cuboid,
- Sphere,
- Cylinder,
- Rectangle,
- Circle,
- CustomShape,
- ShapeSTL,
- BCContainer,
- _assembleGeometry,
- _generateMesh)
-
-
-class ShapeRANS(Shape):
- """
- Base/super class of all shapes. Sets the boundary condition class to
- proteus.mprans.BoundaryConditions.BC_RANS.
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- nd: Optional[int]
- Number of dimensions of the shape. If not set, will take the number of
- dimensions of the domain.
- """
-
- def __init__(self, domain, nd):
- super(ShapeRANS, self).__init__(domain, nd, BC_class=bc.BC_RANS)
- self.mass = None
- self.density = None
- self.free_x = (1, 1, 1)
- self.free_r = (1, 1, 1)
- self.record_values = False
- self.zones = {} # for absorption/generation zones
- self.auxiliaryVariables = {} # list of auxvar attached to shape
- self.It = None # inertia tensor
-
- def _attachAuxiliaryVariable(self, key, auxvar=None, gauge=None):
- """
- Attaches an auxiliary variable to the auxiliaryVariables dictionary of
- the shape (used in buildDomain function)
-
- Parameters
- ----------
- key: string
- Dictionary key defining the auxiliaryVariable to attach
- auxvar:
- auxiliaryVariable to associate with key
-
- gauge: Gauges
-
- Notes
- -----
- This function is called automatically when using other functions to set
- auxiliaryVariables and should not be used manually.
- """
- if key not in self.auxiliaryVariables:
- if key == 'RigidBody':
- self.auxiliaryVariables[key] = auxvar
- if self.holes is None:
- self.holes = np.array([self.barycenter[:self.nd]])
- elif key == 'WallFunction':
- self.auxiliaryVariables[key] = auxvar
- elif key == 'kWallFunction':
- self.auxiliaryVariables[key] = auxvar
- elif key == 'RelaxZones':
- self.auxiliaryVariables[key] = self.zones
- elif str(key).startswith('Gauge_'):
- self.auxiliaryVariables[key] = [gauge]
- else:
- logEvent("auxiliaryVariable key: "
- "{key} not recognized.".format(key=str(key)), level=1)
- elif str(key).startswith('Gauge_'):
- if gauge not in self.auxiliaryVariables[key]:
- self.auxiliaryVariables[key] += [gauge]
- else:
- logEvent(
- "Attempted to put identical "
- "gauge at key: {key}".format(key=str(key)), level=1)
- else:
- logEvent("Key {key} is already attached.".format(key=str(key)),
- level=1)
-
- def attachPointGauges(self, model_key, gauges, activeTime=None,
- sampleRate=0,
- fileName='point_gauges.csv'):
- """Attaches Point Gauges (in the Proteus/Gauges.py style) to the shape.
-
- Parameters
- ----------
- model_key: string
- Label of the model to use as a key for selecting particular gauges.
- See proteus Gauges.py PointGauges class for the remaining parameters.
- """
- new_gauges = Gauges.PointGauges(gauges, activeTime, sampleRate,
- fileName)
- self._attachAuxiliaryVariable('Gauge_' + model_key,
- gauge=new_gauges)
-
- def attachLineGauges(self, model_key, gauges, activeTime=None,
- sampleRate=0,
- fileName='line_gauges.csv'):
- """Attaches Line Gauges (in the Proteus/Gauges.py style) to the shape.
-
- Parameters
- ----------
- model_key: string
- Label of the model to use as a key for selecting particular gauges.
- See proteus Gauges.py LineGauges class for the remaining parameters.
- """
- new_gauges = Gauges.LineGauges(gauges, activeTime, sampleRate,
- fileName)
- self._attachAuxiliaryVariable('Gauge_' + model_key,
- gauge=new_gauges)
-
- def attachLineIntegralGauges(self, model_key, gauges, activeTime=None,
- sampleRate=0,
- fileName='line_integral_gauges.csv'):
- """Attaches Line Integral Gauges (in the Proteus/Gauges.py style).
-
- Parameters
- ----------
- model_key: string
- Label of the model to use as a key for selecting particular gauges.
- See proteus Gauges.py LineIntegralGauges class for the remaining parameters.
- """
- new_gauges = Gauges.LineIntegralGauges(gauges, activeTime,
- sampleRate, fileName)
- self._attachAuxiliaryVariable('Gauge_' + model_key,
- gauge=new_gauges)
-
- def setTank(self):
- """
- Sets tank boundary conditions (for moving domain).
- """
- for boundcond in self.BC_list:
- boundcond.setTank()
-
- def setTurbulentWall(self, wall):
- """
- Sets a turbulent wall as an object to be attacched to auxiliaryVariable.
- The objects has to be defined with WallFunction class.
-
- Parameters
- ----------
- wall: list of WallFunction class object
- """
-
- auxvar = wall
- self._attachAuxiliaryVariable('WallFunction', auxvar)
-
- def setTurbulentKWall(self, kWall):
- """
- Sets a turbulent wall as an object to be attacched to auxiliaryVariable.
- The objects has to be defined with WallFunction class.
-
- Parameters
- ----------
- kWall: list of WallFunction class object for kappa
- """
-
- auxvar = kWall
- self._attachAuxiliaryVariable('kWallFunction', auxvar)
-
- def setAbsorptionZones(self, flags, epsFact_porous, center, orientation,
- dragAlpha, vert_axis=None,dragBeta=0.,
- porosity=1.):
- """
- Sets a region (given the local flag) to an absorption zone
-
- Parameters
- ----------
- dragAlpha: Optional
- Relaxation zone coefficient.
- flags: array_like, int
- Local flags of the region. Can be an integer or a list.
- epsFact_porous: float
- Half of absorption zone (region) length (used for blending func).
- center: array_like
- Coordinates of the center of the absorption zone.
- orientation: array_like
- Orientation vector pointing TOWARDS incoming waves.
- vert_axis: Optional[int]
- index of vertical position vector (x:0, y:1, z:2), must always be
- aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- self._attachAuxiliaryVariable('RelaxZones')
- waves = None
- wind_speed = np.array([0., 0., 0.])
- if isinstance(flags, numbers.Integral):
- flags = [int(flags)]
- epsFact_porous = [epsFact_porous]
- center = np.array([center])
- orientation = np.array([orientation])
- dragAlpha = [dragAlpha]
- dragBeta = [dragBeta]
- porosity = [porosity]
- for i, flag in enumerate(flags):
- self._checkNd(center[i])
- self._checkNd(orientation[i])
- ori = get_unit_vector(orientation[i])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=ori,
- center=center[i],
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous[i],
- dragAlpha=dragAlpha[i],
- dragBeta=dragBeta[i],
- porosity=porosity[i],
- vert_axis=vert_axis)
-
- def setGenerationZones(self, flags, epsFact_porous, center, orientation,
- waves, dragAlpha,vert_axis=None,
- wind_speed=(0., 0., 0.), dragBeta=0.,
- porosity=1., smoothing=0.):
- """
- Sets a region (given the local flag) to a generation zone
-
- Parameters
- ----------
- flags: array_like, int
- Local flags of the region. Can be an integer or a list.
- epsFact_porous: float
- Half of absorption zone (region) length (used for blending func).
- center: array_like
- Coordinates of the center of the absorption zone.
- orientation: array_like
- Orientation vector pointing ACCORDING WITH the direction of generated waves.
- waves: proteus.WaveTools
- Class instance of wave generated from proteus.WaveTools.
- dragAlpha: Optional[float]
- Relaxation zone coefficient.
- vert_axis: Optional[int]
- index of vertical position vector (x:0, y:1, z:2), must always be
- aligned with gravity. If not set, will be 1 in 2D (y), 2 in 3D (z).
- wind_speed: Optional[array_like]
- Speed of wind in generation zone (default is (0., 0., 0.))
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- self._attachAuxiliaryVariable('RelaxZones')
- if isinstance(flags, numbers.Integral):
- flags = [int(flags)]
- epsFact_porous = [epsFact_porous]
- center = np.array([center])
- orientation = np.array([orientation])
- waves = [waves]
- wind_speed = np.array([wind_speed])
- dragAlpha = [dragAlpha]
- dragBeta = [dragBeta]
- porosity = [porosity]
- smoothing = [smoothing]
- for i, flag in enumerate(flags):
- self._checkNd(center[i])
- self._checkNd(orientation[i])
- ori = get_unit_vector(orientation[i])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=ori,
- center=center[i],
- waves=waves[i],
- wind_speed=wind_speed[i],
- epsFact_porous=epsFact_porous[i],
- dragAlpha=dragAlpha[i],
- dragBeta=dragBeta[i],
- porosity=porosity[i],
- smoothing=smoothing[i],
- vert_axis=vert_axis)
-
- def setPorousZones(self, flags, dragAlpha, dragBeta,
- porosity):
- """
- Sets a region (given the local flag) to a porous zone
-
- Parameters
- ----------
- flags: array_like, int
- Local flags of the region. Can be an integer or a list.
- dragAlpha: float
- Darcy-type coefficient
- dragBeta: float
- Forchheimer-type coefficient
- porosity: float
- Porosity
- """
- self._attachAuxiliaryVariable('RelaxZones')
- if isinstance(flags, numbers.Integral):
- flags = [int(flags)]
- dragAlpha = [dragAlpha]
- dragBeta = [dragBeta]
- porosity = [porosity]
- for i, flag in enumerate(flags):
- # note for porous zone:
- # epsFact_porous = q_phi_sponge, --> Hs always equal to 1.
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='porous',
- orientation=None,
- center=None,
- waves=None,
- wind_speed=None,
- epsFact_porous=1.,
- dragAlpha=dragAlpha[i],
- dragBeta=dragBeta[i],
- porosity=porosity[i])
-
-# -----------------------------------------------------------------------------
-# ADDING FUNCTIONALITY TO SHAPE FROM proteus.SpatialTools
-# -----------------------------------------------------------------------------
-
-
-# reassigning base/super class to access all functions from ShapeRANS and Shape
-Rectangle.__bases__ = (ShapeRANS,)
-Cuboid.__bases__ = (ShapeRANS,)
-Sphere.__bases__ = (ShapeRANS,)
-Cylinder.__bases__ = (ShapeRANS,)
-CustomShape.__bases__ = (ShapeRANS,)
-ShapeSTL.__bases__ = (ShapeRANS,)
-Circle.__bases__ = (ShapeRANS,)
-
-# adding extra functionality to predefined shapes
-
-
-def _CuboidsetInertiaTensor(self):
- """
- Sets the inertia tensor of the cuboid
- (!) should not be used manually
- """
- L, W, H = self.dim
- self.It = [[(W**2.+H**2.)/12., 0, 0],
- [0, (L**2.+H**2.)/12., 0],
- [0, 0, (W**2.+L**2.)/12.]]
-
-
-Cuboid._setInertiaTensor = _CuboidsetInertiaTensor
-
-
-def _RectanglesetInertiaTensor(self):
- """
- Sets the inertia tensor of the rectangle
- (!) should not be used manually
- """
- L, H = self.dim
- self.It = (L**2+H**2)/12
-
-
-Rectangle._setInertiaTensor = _RectanglesetInertiaTensor
-
-
-# -----------------------------------------------------------------------------
-# DEFINING NEW SHAPES TYPES
-# -----------------------------------------------------------------------------
-
-class Tank3D(ShapeRANS):
- """
- Class to create a 3D tank (cuboidal shape).
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- dim: Optional[array_like]
- Dimensions of the cuboid.
- coords: Optional[array_like]
- Coordinates of the centroid of the shape.
- """
- count = 0
-
- def __init__(self, domain, dim=(0., 0., 0.), coords=None):
- super(Tank3D, self).__init__(domain, nd=3)
- self.__class__.count += 1
- self.name = "tank3d" + repr(self.__class__.count)
- if coords is None:
- self.coords = np.array(dim)/2.
- self.from_0 = True
- else:
- self.coords = coords
- self.from_0 = False
- self.holes = None
- self.boundaryTags = {'z-': 1,
- 'x-': 2,
- 'y+': 3,
- 'x+': 4,
- 'y-': 5,
- 'z+': 6,
- 'sponge': 7,
- 'wall': 8}
- self.b_or = np.array([[0., 0., -1.],
- [-1., 0., 0.],
- [0., 1., 0.],
- [1., 0., 0.],
- [0., -1., 0.],
- [0., 0., 1.]])
- self.BC = {'z-': self.BC_class(shape=self, name='z-',
- b_or=self.b_or, b_i=0),
- 'x-': self.BC_class(shape=self, name='x-',
- b_or=self.b_or, b_i=1),
- 'y+': self.BC_class(shape=self, name='y+',
- b_or=self.b_or, b_i=2),
- 'x+': self.BC_class(shape=self, name='x+',
- b_or=self.b_or, b_i=3),
- 'y-': self.BC_class(shape=self, name='y+',
- b_or=self.b_or, b_i=4),
- 'z+': self.BC_class(shape=self, name='z+',
- b_or=self.b_or, b_i=5),
- 'sponge': self.BC_class(shape=self, name='sponge'),
- 'wall': self.BC_class(shape=self, name='wall')}
- self.BC_list = [self.BC['z-'],
- self.BC['x-'],
- self.BC['y+'],
- self.BC['x+'],
- self.BC['y+'],
- self.BC['z+'],
- self.BC['sponge'],
- self.BC['wall']]
- # self.BC = BCContainer(self.BC_dict)
- for i in range(6):
- self.BC_list[i].setTank()
- self.barycenter = np.array([0., 0., 0.])
- self.spongeLayers = {'y+': None, 'y-': None, 'x+': None, 'x-': None}
- self.setDimensions(dim)
-
- def setSponge(self, x_p=None, x_n=None, y_p=None, y_n=None):
- """
- Set length of sponge layers of the tank (used for wave absorption or
- generation zones).
- (!) Sponge layers expand outwards.
-
- Parameters
- ----------
- x_p: Optional[float]
- length of sponge layer in +x direction.
- x_n: Optional[float]
- length of sponge layer in -x direction.
- y_p: Optional[float]
- length of sponge layer in +y direction.
- y_n: Optional[float]
- length of sponge layer in -y direction.
- """
- self.spongeLayers['x+'] = x_p
- self.spongeLayers['x-'] = x_n
- self.spongeLayers['y+'] = y_p
- self.spongeLayers['y-'] = y_n
- self.setDimensions(self.dim)
-
- def setDimensions(self, dim):
- """
- Set dimension of the tank
- Parameters
- ----------
- dim: array_like
- dimensions of the tank (excluding sponge layers), array of length 3.
- """
- L, W, H = dim
- self.dim = dim
- if self.from_0 is True:
- x, y, z = L/2., W/2., H/2.
- else:
- x, y, z = self.coords
- self.coords = [x, y, z]
- x0, x1 = x - 0.5 * L, x + 0.5 * L
- y0, y1 = y - 0.5 * W, y + 0.5 * W
- z0, z1 = z - 0.5 * H, z + 0.5 * H
- # ---------------------------------------------
- # first add all vecors, facets, regions at the bottom
- # ---------------------------------------------
- bt = self.boundaryTags
- x_p = self.spongeLayers['x+'] or 0.
- x_n = self.spongeLayers['x-'] or 0.
- y_p = self.spongeLayers['y+'] or 0.
- y_n = self.spongeLayers['y-'] or 0.
- vertices = [[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0],
- [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]]
- vertexFlags = [bt['z-'], bt['z-'], bt['z-'], bt['z-'],
- bt['z+'], bt['z+'], bt['z+'], bt['z+']]
- facets = [[[0, 1, 2, 3]], [[4, 5, 6, 7]]]
- segments = []
- segmentFlags = []
- volumes = [[[0, 1]]]
- facetFlags = [bt['z-'], bt['z+']]
- regions = [[(x0+x1)/2., (y0+y1)/2., (z0+z1)/2.]]
- regionFlags = [1]
- self.regionIndice = {'tank': 0}
- v_i = 8 # index of next vector to add
- r_i = 1 # index of next region to add
- f_i = len(facets)
- nb_sponge = 0 # number of sponge layers defined
-
- ymin = y0 - y_n
- ymax = y1 + y_p
- xmin = x0 - x_n
- xmax = x1 + x_p
- corners = False
- # y-
- if y_n:
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- if corners:
- vertices += [[x0, ymin, z0], [x0, ymin, z1],
- [x1, ymin, z0], [x1, ymin, z1]]
- else:
- vertices += [[xmin, ymin, z0], [xmin, ymin, z1],
- [xmax, ymin, z0], [xmax, ymin, z1]]
- vertexFlags += [bt['z-'], bt['z+'],
- bt['z-'], bt['z+']]
- facets += [[[v0, v1, v3, v2]]]
- facetFlags += [bt['y-']]
- volumes[0][0] += [f_i]
- regions += [[(x0+x1)/2., (y0+(ymin))/2., (z0+z1)/2.]]
- self.regionIndice['y-'] = r_i
- regionFlags += [r_i + 1]
- facets += [[[0, 1, v1, v0]],
- [[4, 5, v3, v2]],
- [[0, 1, 5, 4]],
- [[0, v0, v2, 4]],
- [[1, v1, v3, 5]]]
- facetFlags += [bt['z-'],
- bt['z+'],
- bt['sponge']]
- if x_n > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['x-']]
- if x_p > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['x+']]
- volumes[0][0][-1] = f_i + 3 # add to volume
- r_i += 1
- nb_sponge += 1
- volumes += [[[len(facets) - i - 1 for i in range(6)]]]
- x_n_facet_i = len(facets) - 2
- else:
- facets += [[[0, 1, 5, 4]]]
- facetFlags += [bt['y-']]
- volumes[0][0] += [f_i]
- v_i = len(vertices)
- f_i = len(facets)
- # x+
- if x_p:
- if corners:
- vertices += [[xmax, y0, z0], [xmax, y0, z1],
- [xmax, y1, z0], [xmax, y1, z1]]
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- vertexFlags += [bt['z-'], bt['z+'],
- bt['z-'], bt['z+']]
- else:
- v0 = v_i - 2
- v1 = v_i
- v2 = v_i - 1
- v3 = v_i + 1
- if not y_n:
- vertices += [[xmax, ymin, z0], [xmax, ymin, z1]]
- vertexFlags += [bt['z-'], bt['z+']]
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- vertices += [[xmax, ymax, z0], [xmax, ymax, z1]]
- vertexFlags += [bt['z-'], bt['z+']]
- facets += [[[v0, v1, v3, v2]]]
- facetFlags += [bt['x+']]
- volumes[0][0] += [f_i]
- regions += [[(x1+(xmax))/2., (y0+y1)/2., (z0+z1)/2.]]
- self.regionIndice['x+'] = r_i
- regionFlags += [r_i + 1]
- facets += [[[1, 2, v1, v0]],
- [[5, 6, v3, v2]],
- [[1, 2, 6, 5]]]
- facetFlags += [bt['z-'],
- bt['z+'],
- bt['sponge']]
- if corners or not y_n:
- facets += [[[1, v0, v2, 5]]]
- if y_n > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['y-']]
- facets += [[[2, v1, v3, 6]]]
- if y_p > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['y+']]
- volumes[0][0][-1] = f_i + 3 # add to volume
- r_i += 1
- nb_sponge += 1
- volumes += [[[len(facets) - i - 1 for i in range(6)]]]
- else:
- facets += [[[1, 2, 6, 5]]]
- facetFlags += [bt['x+']]
- volumes[0][0] += [f_i]
- v_i = len(vertices)
- f_i = len(facets)
- # y+
- if y_p:
- if corners:
- vertices += [[x1, ymax, z0], [x1, ymax, z1],
- [x0, ymax, z0], [x0, ymax, z1]]
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- vertexFlags += [bt['z-'], bt['z+'],
- bt['z-'], bt['z+']]
- else:
- v0 = v_i - 2
- v1 = v_i
- v2 = v_i - 1
- v3 = v_i + 1
- if not x_p:
- vertices += [[xmax, ymax, z0], [xmax, ymax, z1]]
- vertexFlags += [bt['z-'], bt['z+']]
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- vertices += [[xmin, ymax, z0], [xmin, ymax, z1]]
- vertexFlags += [bt['z-'], bt['z+']]
- facets += [[[v0, v1, v3, v2]]]
- volumes[0][0] += [f_i]
- facetFlags += [bt['y+']]
- regions += [[(x0+x1)/2., (y1+(ymax))/2., (z0+z1)/2.]]
- self.regionIndice['y+'] = r_i
- regionFlags += [r_i + 1]
- facets += [[[2, 3, v1, v0]],
- [[6, 7, v3, v2]],
- [[2, 3, 7, 6]]]
- facetFlags += [bt['z-'],
- bt['z+'],
- bt['sponge']]
- if corners or not x_p:
- facets += [[[2, v0, v2, 6]]]
- if x_p > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['x+']]
- facets += [[[3, v1, v3, 7]]]
- if x_n > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['x-']]
- volumes[0][0][-1] = f_i + 3
- r_i += 1
- nb_sponge += 1
- volumes += [[[len(facets) - i - 1 for i in range(6)]]]
- else:
- facets += [[[3, 2, 6, 7]]]
- facetFlags += [bt['y+']]
- volumes[0][0] += [f_i]
- v_i = len(vertices)
- f_i = len(facets)
- # x-
- if x_n:
- volumes[0][0] += [f_i]
- if corners:
- vertices += [[xmin, y0, z0], [xmin, y0, z1],
- [xmin, y1, z0], [xmin, y1, z1]]
- v0 = v_i
- v1 = v_i + 2
- v2 = v_i + 1
- v3 = v_i + 3
- vertexFlags += [bt['z-'], bt['z+'],
- bt['z-'], bt['z+']]
- else:
- if not y_p:
- vertices += [[xmin, ymax, z0], [xmin, ymax, z1]]
- v0 = v_i - 2
- v1 = v_i
- v2 = v_i - 1
- v3 = v_i + 1
- vertexFlags += [bt['z-'], bt['z+']]
- if not y_n:
- vertices += [[xmin, ymin, z0], [xmin, ymin, z1]]
- if not y_p:
- v0 = v_i + 2
- v1 = v_i
- v2 = v_i + 3
- v3 = v_i + 1
- else:
- v0 = v_i
- v1 = v_i - 2
- v2 = v_i + 1
- v3 = v_i - 1
- vertexFlags += [bt['z-'], bt['z+']]
- else:
- v1 = v_i - 2
- v0 = 8
- v3 = v_i - 1
- v2 = 9
- if not y_p:
- v1 = v_i
- v3 = v_i + 1
- facets += [[[v0, v1, v3, v2]]]
- facetFlags += [bt['x-']]
- regions += [[(x0+(xmin))/2., (y0+y1)/2., (z0+z1)/2.]]
- self.regionIndice['x-'] = r_i
- regionFlags += [r_i + 1]
- facets += [[[0, 3, v1, v0]],
- [[4, 7, v3, v2]],
- [[0, 3, 7, 4]]]
- facetFlags += [bt['z-'],
- bt['z+'],
- bt['sponge']]
- volumes[0][0][-1] = f_i + 3
- if corners or not y_n or not y_p:
- if corners or not y_n:
- facets += [[[0, v0, v2, 4]]]
- if y_n > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['y-']]
- if corners or not y_p:
- facets += [[[3, v1, v3, 7]]]
- if y_p > 0:
- facetFlags += [bt['wall']]
- else:
- facetFlags += [bt['y+']]
- r_i += 1
- nb_sponge += 1
- if corners or not y_n:
- volumes += [[[len(facets) - i - 1 for i in range(6)]]]
- else:
- volumes += [[[len(facets) - i - 1 for i in range(5)] + [x_n_facet_i]]]
- else:
- facets += [[[0, 3, 7, 4]]]
- facetFlags += [bt['x-']]
- volumes[0][0] += [f_i]
- v_i = len(vertices)
- f_i = len(facets)
- self.vertices = np.array(vertices)
- self.vertices = np.dot(self.vertices, self.coords_system)
- self.vertexFlags = np.array(vertexFlags)
- self.segments = np.array(segments)
- self.segmentFlags = np.array(segmentFlags)
- self.facets = np.array(facets)
- self.facetFlags = np.array(facetFlags)
- self.regions = np.array(regions)
- self.regionFlags = np.array(regionFlags)
- self.volumes = volumes
-
- def setAbsorptionZones(self, dragAlpha, allSponge=False,
- y_n=False, y_p=False,
- x_n=False, x_p=False,
- dragBeta=0., porosity=1.):
- """
- Sets regions (x+, x-, y+, y-) to absorption zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient.
- allSponge: bool
- If True, all sponge layers are converted to absorption zones.
- x_p: bool
- If True, x+ region is converted to absorption zone.
- x_n: bool
- If True, x- region is converted to absorption zone.
- y_p: bool
- If True, y+ region is converted to absorption zone.
- y_n: bool
- If True, y- region is converted to absorption zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- self.abs_zones = {'y-': y_n, 'y+': y_p, 'x-': x_n, 'x+': x_p}
- if allSponge is True:
- for key in self.abs_zones:
- self.abs_zones[key] = True
- waves = None
- wind_speed = np.array([0., 0., 0.])
- sl = self.spongeLayers
- for key, value in list(self.abs_zones.items()):
- if value is True:
- self._attachAuxiliaryVariable('RelaxZones')
- ind = self.regionIndice[key]
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers[key]/2.
- center = np.array(self.coords)
- zeros_to_append = 3 - len(center)
- if zeros_to_append:
- for i in range(zeros_to_append):
- center = np.append(center, [0])
- if key == 'x-':
- center[0] += -0.5 * self.dim[0] - 0.5 * sl['x-']
- orientation = np.array([1., 0., 0.])
- elif key == 'x+':
- center[0] += +0.5 * self.dim[0] + 0.5 * sl['x+']
- orientation = np.array([-1., 0., 0.])
- elif key == 'y-':
- center[1] += -0.5 * self.dim[1] - 0.5 * sl['y-']
- orientation = np.array([0., 1., 0.])
- elif key == 'y+':
- center[1] += +0.5 * self.dim[1] + 0.5 * sl['y+']
- orientation = np.array([0., -1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity)
-
- def setGenerationZones(self, dragAlpha, smoothing, waves=None,
- wind_speed=(0., 0., 0.), allSponge=False, y_n=False,
- y_p=False, x_n=False, x_p=False, dragBeta=0.,
- porosity=1.):
- """
- Sets regions (x+, x-, y+, y-) to generation zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient.
- smoothing: float
- Smoothing distance (typically 3.*he)
- waves: proteus.WaveTools
- Class instance of wave generated from proteus.WaveTools.
- wind_speed: Optional[array_like]
- Speed of wind in generation zone (default is (0., 0., 0.))
- allSponge: bool
- If True, all sponge layers are converted to generation zones.
- x_p: bool
- If True, x+ region is converted to generation zone.
- x_n: bool
- If True, x- region is converted to generation zone.
- y_p: bool
- If True, y+ region is converted to generation zone.
- y_n: bool
- If True, y- region is converted to generation zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- self.abs_zones = {'y-': y_n, 'y+': y_p, 'x-': x_n, 'x+': x_p}
- if allSponge is True:
- for key in self.abs_zones:
- self.abs_zones[key] = True
- waves = waves
- wind_speed = np.array(wind_speed)
- sl = self.spongeLayers
- for key, value in list(self.abs_zones.items()):
- if value is True:
- self._attachAuxiliaryVariable('RelaxZones')
- ind = self.regionIndice[key]
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers[key]/2.
- center = np.array(self.coords)
- zeros_to_append = 3 - len(center)
- if zeros_to_append:
- for i in range(zeros_to_append):
- center = np.append(center, [0])
- if key == 'x-':
- center[0] += -0.5 * self.dim[0] - sl['x-']/2.
- orientation = np.array([1., 0., 0.])
- self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- elif key == 'x+':
- center[0] += +0.5 * self.dim[0] + sl['x+']/2.
- orientation = np.array([-1., 0., 0.])
- self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- elif key == 'y-':
- center[1] += -0.5 * self.dim[1] - sl['y-']/2.
- orientation = np.array([0., 1., 0.])
- self.BC['y-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- elif key == 'y+':
- center[1] += +0.5 * self.dim[1] + sl['y+']/2.
- orientation = np.array([0., -1., 0.])
- self.BC['y+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity,
- smoothing=smoothing)
-
-
-class Tank2D(ShapeRANS):
- """
- Class to create a 2D tank (rectangular shape).
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- dim: array_like
- Dimensions of the tank (excluding sponge layers).
- coords: Optional[array_like]
- Coordinates of the centroid of the shape.
- """
- count = 0
-
- def __init__(self, domain, dim, coords=None):
- super(Tank2D, self).__init__(domain, nd=2)
- if coords is None:
- self.coords = np.array(dim)/2.
- self.from_0 = True
- else:
- self.coords = coords
- self.from_0 = False
- self.dim = dim
- self._nameSelf()
- self._setupBCs()
- self.spongeLayers = {'x-': None,
- 'x+': None}
- self.constructShape()
-
- def _nameSelf(self):
- self.__class__.count += 1
- self.name = "tank2D" + repr(self.__class__.count)
-
- def _setupBCs(self):
- self.boundaryTags = {'y-': 1, 'x+': 2, 'y+': 3, 'x-': 4, 'sponge': 5}
- self.b_or = np.array([[0., -1., 0.],
- [1., 0., 0.],
- [0., 1., 0.],
- [-1., 0., 0.]])
- self.BC = {'y-': self.BC_class(shape=self, name='y-',
- b_or=self.b_or, b_i=0),
- 'x+': self.BC_class(shape=self, name='x+',
- b_or=self.b_or, b_i=1),
- 'y+': self.BC_class(shape=self, name='y+',
- b_or=self.b_or, b_i=2),
- 'x-': self.BC_class(shape=self, name='x-',
- b_or=self.b_or, b_i=3),
- 'sponge': self.BC_class(shape=self, name='sponge')}
- self.BC_list = [self.BC['y-'],
- self.BC['x+'],
- self.BC['y+'],
- self.BC['x-'],
- self.BC['sponge']]
- # self.BC = BCContainer(self.BC_dict)
- for i in range(4):
- self.BC_list[i].setTank()
-
- def constructShape(self):
- """
- Construct the geometry of the tank: segments, regions, etc.
-
- Parameters
- ----------
- frame: array_like
- An array of (x,y) coordinates in counterclockwise order to define
- the boundaries of the main (that is, excluding extensions such as
- sponge zones) shape. This can be generated with tank2DFrame or
- subclass specific methods.
- frame_flags: array_like
- A corresponding array of boundary tags associated with each point
- in the frame. This can be generated with tank2DFrame or subclass
- specific methods.
- """
- self._findEdges(self.dim)
- vertices, vertexFlags = self._constructVertices()
- segments, segmentFlags = self._constructSegments(vertices, vertexFlags)
- regions, regionFlags = self._constructRegions(vertices, vertexFlags,
- segments, segmentFlags)
- facets, facetFlags = self._constructFacets()
-
- self.vertices = np.array(vertices)
- self.vertexFlags = np.array(vertexFlags)
- self.segments = np.array(segments)
- self.segmentFlags = np.array(segmentFlags)
- self.regions = np.array(regions)
- self.regionFlags = np.array(regionFlags)
- self.facets = np.array(facets)
- self.facetFlags = np.array(facetFlags)
-
- def _findEdges(self, dim):
-
- coords = self.coords
- from_0 = self.from_0
-
- if from_0:
- self.x0 = 0
- self.x1 = dim[0]
- self.y0 = 0
- self.y1 = dim[1]
- else: # not from_0 and coords is not None
- self.x0 = coords[0] - 0.5 * dim[0]
- self.x1 = coords[0] + 0.5 * dim[0]
- self.y0 = coords[1] - 0.5 * dim[1]
- self.y1 = coords[1] + 0.5 * dim[1]
-
- def _constructVertices(self):
- vertices = [[self.x0, self.y0],
- [self.x1, self.y0],
- [self.x1, self.y1],
- [self.x0, self.y1]]
- vertexFlags = [self.boundaryTags['y-'],
- self.boundaryTags['y-'],
- self.boundaryTags['y+'],
- self.boundaryTags['y+']]
- if self.spongeLayers['x-']:
- vertices += [[self.x0 - self.spongeLayers['x-'], self.y0],
- [self.x0 - self.spongeLayers['x-'], self.y1]]
- vertexFlags += [self.boundaryTags['y-'],
- self.boundaryTags['y+']]
- if self.spongeLayers['x+']:
- vertices += [[self.x1 + self.spongeLayers['x+'], self.y0],
- [self.x1 + self.spongeLayers['x+'], self.y1]]
- vertexFlags += [self.boundaryTags['y-'],
- self.boundaryTags['y+']]
- return vertices, vertexFlags
-
- def _constructSegments(self, vertices, vertexFlags):
- segments = [[0, 1], [1, 2], [2, 3], [3, 0]]
- segmentFlags = [self.boundaryTags['y-'],
- self.boundaryTags['x+'],
- self.boundaryTags['y+'],
- self.boundaryTags['x-']]
- added_vertices = 0
- if self.spongeLayers['x-']:
- segments += [[0, 4 + added_vertices],
- [4 + added_vertices, 5 + added_vertices],
- [5 + added_vertices, 3]]
- segmentFlags += [self.boundaryTags['y-'],
- self.boundaryTags['x-'],
- self.boundaryTags['y+']]
- segmentFlags[3] = self.boundaryTags['sponge']
- added_vertices += 2
- if self.spongeLayers['x+']:
- segments += [[1, 4 + added_vertices],
- [4 + added_vertices, 5 + added_vertices],
- [5 + added_vertices, 2]]
- segmentFlags += [self.boundaryTags['y-'],
- self.boundaryTags['x+'],
- self.boundaryTags['y+']]
- segmentFlags[1] = self.boundaryTags['sponge']
- added_vertices += 2
- return segments, segmentFlags
-
- def _constructFacets(self):
- facets = [[[0, 1, 2, 3]]]
- facetFlags = [1]
- added_vertices = 0
- added_facets = 0
- if self.spongeLayers['x-']:
- facets += [[[3, 0, 4, 5]]]
- facetFlags += [2 + added_facets]
- added_vertices += 2
- added_facets += 1
- if self.spongeLayers['x+']:
- facets += [[[2, 1, added_vertices + 4, added_vertices + 5]]]
- facetFlags += [2 + added_facets]
- return facets, facetFlags
-
- def _constructRegions(self, vertices, vertexFlags, segments, segmentFlags):
- regions = [[self.x0 + 0.01 * (self.x1 - self.x0), 0.5 * (self.y0 + self.y1)], ]
- ind_region = 1
- regionFlags = [ind_region, ]
- self.regionIndice = {'tank': ind_region - 1}
- if self.spongeLayers['x-']:
- regions += [[self.x0 - 0.5 * self.spongeLayers['x-'],
- 0.5 * (self.y0 + self.y1)]]
- ind_region += 1
- regionFlags += [ind_region]
- self.regionIndice['x-'] = ind_region - 1
- if self.spongeLayers['x+']:
- regions += [[self.x1 + 0.5 * self.spongeLayers['x+'],
- 0.5 * (self.y0 + self.y1)]]
- ind_region += 1
- regionFlags += [ind_region]
- self.regionIndice['x+'] = ind_region - 1
- return regions, regionFlags
-
- def setSponge(self, x_n=None, x_p=None):
- """
- Set length of sponge layers of the tank (used for wave absorption or
- generation zones).
- (!) Sponge layers expand outwards.
-
- Parameters
- ----------
- x_p: Optional[float]
- length of sponge layer in +x direction.
- x_n: Optional[float]
- length of sponge layer in -x direction.
- """
- self.spongeLayers['x-'] = x_n
- self.spongeLayers['x+'] = x_p
- self.constructShape()
-
- def setAbsorptionZones(self, dragAlpha, x_n=False, x_p=False,
- dragBeta=0., porosity=1.):
- """
- Sets regions (x+, x-) to absorption zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient.
- allSponge: bool
- If True, all sponge layers are converted to absorption zones.
- x_p: bool
- If True, x+ region is converted to absorption zone.
- x_n: bool
- If True, x- region is converted to absorption zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- waves = None
- wind_speed = np.array([0., 0., 0.])
- if x_n or x_p:
- self._attachAuxiliaryVariable('RelaxZones')
- if x_n is True:
- center = np.array([self.coords[0]-0.5*self.dim[0]-0.5*self.spongeLayers['x-'],
- self.coords[1],
- 0.])
- ind = self.regionIndice['x-']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x-']/2.
- orientation = np.array([1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity)
- if x_p is True:
- center = np.array([self.coords[0]+0.5*self.dim[0]+0.5*self.spongeLayers['x+'],
- self.coords[1],
- 0.])
- ind = self.regionIndice['x+']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x+']/2.
- orientation = np.array([-1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity)
-
- def setGenerationZones(self, dragAlpha, smoothing,
- waves=None, wind_speed=(0., 0., 0.),
- x_n=False, x_p=False,
- dragBeta=0., porosity=1.):
- """
- Sets regions (x+, x-) to generation zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient
- smoothing:
- Smoothing distance
- waves: proteus.WaveTools
- Class instance of wave generated from proteus.WaveTools.
- wind_speed: Optional[array_like]
- Speed of wind in generation zone (default is (0., 0., 0.))
- allSponge: bool
- If True, all sponge layers are converted to generation zones.
- x_p: bool
- If True, x+ region is converted to generation zone.
- x_n: bool
- If True, x- region is converted to generation zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- waves = waves
- wind_speed = np.array(wind_speed)
- if x_n or x_p:
- self._attachAuxiliaryVariable('RelaxZones')
- if x_n is True:
- center = np.array([self.coords[0]-0.5*self.dim[0]-0.5*self.spongeLayers['x-'],
- self.coords[1],
- 0.])
- ind = self.regionIndice['x-']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x-']/2.
- orientation = np.array([1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity,
- smoothing=smoothing)
- self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- if x_p is True:
- center = np.array([self.coords[0]+0.5*self.dim[0]+0.5*self.spongeLayers['x+'],
- self.coords[1],
- 0.])
- ind = self.regionIndice['x+']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x+']/2.
- orientation = np.array([-1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity,
- smoothing=smoothing)
- self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
-
-#[temp] no tests yet!
-
-
-class TankWithObstacles2D(Tank2D):
- """
- Class to create a 2D rectangular tank with obstacles built out of any wall.
-
- An obstacle is defined by a contiguous list of points which start and end
- on the walls or corners of the tank.
-
- This also covers special boundary conditions. To tag a segment with a
- unique boundary tag, add the starting vertex (in the counterclockwise
- format the shape is generated in) of the segment as a value in a dictionary
- element keyed to the name of the boundary tag.
-
- (!) Warning: If each of the four corners of the rectangular tank is inside
- an obstacle or a vertex for an obstacle, then the tank's region is defined
- in a pseudorandom manner, which may make it unreliable when dealing with
- holes caused by other shapes.
- (!) Warning: Obstacle boundary tags are keyed to whichever edge they started
- from. If this is undesirable, it may be manually overriden by applying
- special boundary conditions to affected segments.
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- dim: Optional[array_like]
- Dimensions of the cuboid.
- obstacles: Optional[array_like]
- A list of lists of (x,y) coordinates. Each (x,y) coordinate is a length
- and height relative to the x-,y- corner of the tank. Each list of
- coordinates is an obstacle defined by points connected in the order of
- their index. The list of lists gives all such obstacles in a
- counterclockwise manner of which they should be appended, starting from
- the (x-,y-) corner.
- special_boundaries: Optional[mapping]
- A dictionary of lists of vertices keyed to boundary names. The vertices
- listed will be given the boundary name they are keyed to, overriding
- any other designation they would be given.
- If this is a distinct boundary name, the segment starting from the vertex
- will be assigned the same boundary tag.
- full_circle: Optional[bool]
- A boolean tag to check if the final obstacle ends on the same edge that
- the first obstacle starts on. Default is False.
- coords: Optional[array_like]
- Coordinates of the centroid of the shape.
- hole: Optional[bool]
- If True (default), the obstacle of the tank is just an open hole at the
- bottom of the tank. If False, a segment at the bottom of the obstacle is
- created to close the hole.
- obstacle_regions: Optional[array_like]
- To use only if hole=False.(x,y) coordinates of a point inside the
- obstacle in order to fill the obstacle with what should be inside
- (for example a porous material).
-
- """
-
- def __init__(self, domain, dim=(0., 0.),
- obstacles=None, special_boundaries=None,
- full_circle=False,
- coords=None, hole=True, obstacle_regions=None):
- if obstacles:
- self.obstacles = obstacles
- else:
- self.obstacles = []
-
- self.special_boundaries = []
- self.special_BC_vertices = []
- self.full_circle = full_circle
-
- self.spongeLayers = {'x-': None,
- 'x+': None}
-
- if special_boundaries:
- for key in list(special_boundaries.keys()):
- self.special_boundaries += [key for v in special_boundaries[key]]
- self.special_BC_vertices += special_boundaries[key]
-
- self.corners = {'x-y-': False, 'x+y-': False,
- 'x+y+': False, 'x-y+': False}
-
- self.hole = hole
- self.obstacle_regions = obstacle_regions
- super(TankWithObstacles2D, self).__init__(domain, dim, coords)
-
- def _setupBCs(self):
- super(TankWithObstacles2D, self)._setupBCs()
- for boundary in self.special_boundaries:
- if boundary not in list(self.boundaryTags.keys()):
- self.boundaryTags[boundary] = len(self.boundaryTags) + 1
- self.BC[boundary] = self.BC_class(shape=self, name=boundary)
- self.BC_list += [self.BC[boundary]]
- # add boundaryTags
- self.obstacle_flags = []
- max_flag = 0
- for tag, flag in list(self.boundaryTags.items()):
- if flag > max_flag:
- max_flag = flag
- flag = max_flag + 1
- for i in range(len(self.obstacles)):
- tag = 'obstacle' + repr(i + 1)
- self.boundaryTags[tag] = flag
- self.obstacle_flags += [flag]
- self.BC[tag] = self.BC_class(shape=self, name=tag)
- self.BC_list += [self.BC[tag]]
- flag += 1
- if self.hole is False:
- assert len(self.obstacles) == len(self.obstacle_regions), 'must have same number of regions as obstacles'
-
- def _resetEdgesFromVertices(self, vertices):
- """
- Resets self.x0, self.x1, self.y0, self.y1 based on the actual shape.
-
- In particular, they will form a bounding box form around the shape -
- the furthest points in x and y dimensions, both high and low.
-
- Parameters
- ----------
- vertices: array_like
- """
- sorted_vertices = sorted(vertices, key=lambda vertex: vertex[1])
- self.y0 = sorted_vertices[0][1]
- self.y1 = sorted_vertices[-1][1]
- sorted_vertices = sorted(vertices, key=lambda vertex: vertex[0])
- self.x0 = sorted_vertices[0][0]
- self.x1 = sorted_vertices[-1][0]
-
- def _findSpongeLayerCorners(self, vertices):
- """
- Finds the corners for horizontal (x-, x+) sponge layers.
-
- Parameters
- ----------
- vertices: array_like
- """
- self._resetEdgesFromVertices(vertices)
-
- potential_x_n_corners = [vertex for vertex in vertices
- if np.isclose(vertex[0], self.x0)]
- potential_x_p_corners = [vertex for vertex in vertices
- if np.isclose(vertex[0], self.x1)]
-
- potential_x_n_corners.sort(key=lambda vertex: vertex[1])
- potential_x_p_corners.sort(key=lambda vertex: vertex[1])
-
- self.x0y0 = potential_x_n_corners[0]
- self.x0y1 = potential_x_n_corners[-1]
- self.x1y0 = potential_x_p_corners[0]
- self.x1y1 = potential_x_p_corners[-1]
-
- def _constructVertices(self):
-
- def getClockwiseOrder(first_point):
- clockwise_ordering = ('x-y-', 'y-', 'x+y-', 'x+',
- 'x+y+', 'y+', 'x-y+', 'x-')
- index = clockwise_ordering.index(first_point)
- return clockwise_ordering[index:] + clockwise_ordering[:index]
-
- def findLocation(vertex):
- """
- Given an (x,y) coordinate gives a label associated to corner or edge
- """
- dim = [self.x1 - self.x0, self.y1 - self.y0]
- if np.isclose(vertex[0], 0) and np.isclose(vertex[1], 0):
- return 'x-y-'
- elif np.isclose(vertex[0], dim[0]) and np.isclose(vertex[1], dim[1]):
- return 'x+y+'
- elif np.isclose(vertex[0], 0) and np.isclose(vertex[1], dim[1]):
- return 'x-y+'
- elif np.isclose(vertex[0], dim[0]) and np.isclose(vertex[1], 0):
- return 'x+y-'
- elif np.isclose(vertex[0], 0):
- return 'x-'
- elif np.isclose(vertex[0], dim[0]):
- return 'x+'
- elif np.isclose(vertex[1], 0):
- return 'y-'
- elif np.isclose(vertex[1], dim[1]):
- return 'y+'
- else:
- raise ValueError("Point " + str(vertex) + " does not seem to"
- "be on a tank wall.")
-
- def checkClosure(start_point, end_point):
- if start_point == end_point:
- return True
-
- def addCorner(corner_flag):
- if corner_flag == 'x-y-':
- corner = [[self.x0, self.y0]]
- elif corner_flag == 'x+y-':
- corner = [[self.x1, self.y0]]
- elif corner_flag == 'x+y+':
- corner = [[self.x1, self.y1]]
- elif corner_flag == 'x-y+':
- corner = [[self.x0, self.y1]]
- # vertex flags
- if corner_flag in ['x-y-', 'x+y-']:
- corner_tag = [self.boundaryTags['y-']]
- else:
- corner_tag = [self.boundaryTags['y+']]
-
- return corner, corner_tag
-
- def addIntermediateCorners(first, last):
- """
- Returns corner vertices (and flags) in between two segments
- """
- ordering = getClockwiseOrder(first)
- corners = [x for x in ordering
- if x in list(self.corners.keys())
- and ordering.index(x) < ordering.index(last)
- ]
- corner_vertices = []
- corner_flags = []
-
- for corner in corners:
- self.corners[corner] = True
- vertex, flag = addCorner(corner)
- corner_vertices += vertex
- corner_flags += flag
-
- return corner_vertices, corner_flags
-
- def addRemainingCorners(first, last):
- if first == last:
- if self.full_circle:
- return []
- else:
- return addAllCorners(first)
- else:
- return addIntermediateCorners(first, last)
-
- def addAllCorners(starting_point):
- """
- Returns all corners and flags.
- """
- corner_vertices = []
- corner_flags = []
-
- ordering = getClockwiseOrder(starting_point)
-
- for potential_corner in ordering:
- if potential_corner in list(self.corners.keys()):
- self.corners[potential_corner] = True
- vertex, flag = addCorner(potential_corner)
- corner_vertices += vertex
- corner_flags += flag
-
- return corner_vertices, corner_flags
-
- def addSpongeVertices():
- sponge_vertices = []
- sponge_vertexFlags = []
- if self.spongeLayers['x-']:
- sponge_vertices += [[v[0] - self.spongeLayers['x-'], v[1]]
- for v in [self.x0y0, self.x0y1]]
- sponge_vertexFlags += [self.boundaryTags['y-'],
- self.boundaryTags['y+']]
- if self.spongeLayers['x+']:
- sponge_vertices += [[v[0] + self.spongeLayers['x+'], v[1]]
- for v in [self.x1y0, self.x1y1]]
- sponge_vertexFlags += [self.boundaryTags['y-'],
- self.boundaryTags['y+']]
- return sponge_vertices, sponge_vertexFlags
-
- #--------------------------------------------------------#
- vertices = []
- vertexFlags = []
- former_end = None
- first_start = None
-
- for nb, obstacle in enumerate(self.obstacles):
- start = findLocation(obstacle[0])
- end = findLocation(obstacle[-1])
-
- if start == end and checkClosure(obstacle[0], obstacle[-1]):
- raise ValueError("Obstacles must be open (start and end"
- " vertices must be distinct)")
- if start == former_end and checkClosure(obstacle[0], vertices[-1]):
- vertices.pop()
- vertexFlags.pop()
-
- # ---- In-Between Corner Vertices ---- #
- if former_end is not None:
- new_vertices, new_flags = addIntermediateCorners(former_end, start)
- vertices += new_vertices
- vertexFlags += new_flags
-
- # ---- Obstacle ---- #
- if self.hole is True:
- vertices += obstacle
- vertexFlags += [self.boundaryTags[start]
- for i in range(len(obstacle))]
- elif self.hole is False:
- vertices += obstacle
- vertexFlags += [self.boundaryTags['obstacle' + repr(nb + 1)]
- for i in range(len(obstacle))]
-
- # ---- Paperwork ---- #
- former_end = end
- if first_start is None:
- first_start = start
-
- # ---- Remaining Corner Vertices ---- #
- if first_start is not None:
- new_vertices, new_flags = addRemainingCorners(former_end,
- first_start)
- else:
- new_vertices, new_flags = addAllCorners('x-')
-
- vertices += new_vertices
- vertexFlags += new_flags
-
- # ---- Check for Special Conditions ---- #
- for vertex in self.special_BC_vertices:
- flag_index = vertices.index(vertex)
- boundary_index = self.special_BC_vertices.index(vertex)
- boundary_name = self.special_boundaries[boundary_index]
- vertexFlags[flag_index] = self.boundaryTags[boundary_name]
-
- # ---- Adjustments for Sponge Zones ---- #
- self._findSpongeLayerCorners(vertices=vertices)
-
- # ---- Add Sponge Zone Vertices ---- #
- new_vertices, new_flags = addSpongeVertices()
- vertices += new_vertices
- vertexFlags += new_flags
-
- return vertices, vertexFlags
-
- def _constructSegments(self, vertices, vertexFlags):
- # VertexFlag --> SegmentFlag logic:
- #
- # if EITHER are x+ --> segment is x+
- # UNLESS the other is x- --> y+
- # if EITHER are x- --> segment is x-
- # UNLESS the other is x+ --> y-
- # if it STARTS y- --> segment is y-
- # UNLESS they are vertical --> x+
- # if it STARTS y+ --> segment is y+
- # UNLESS they are vertical --> x-
- # if BOTH are *** --> segment is ***
- # (if two different *** are around, it takes the first)
- segments = []
- segmentFlags = []
-
- on_sponge_edge = {'x-': False, 'x+': False}
- sponge_edges_covered = {'x-': False, 'x+': False}
-
- def checkSpongeStatus(start_index, end_index):
- start_vertex = vertices[start_index]
- if self.spongeLayers['x-']:
- if not on_sponge_edge['x-']:
- if start_vertex in (self.x0y0, self.x0y1):
- on_sponge_edge['x-'] = True
- elif not sponge_edges_covered['x-']:
- if start_vertex in (self.x0y0, self.x0y1):
- on_sponge_edge['x-'] = False
- sponge_edges_covered['x-'] = True
- else:
- vertexFlags[start_index] = self.boundaryTags['sponge']
- else:
- pass
-
- if self.spongeLayers['x+']:
- if not on_sponge_edge['x+']:
- if start_vertex in (self.x1y0, self.x1y1):
- on_sponge_edge['x+'] = True
- elif not sponge_edges_covered['x+']:
- if start_vertex in (self.x1y0, self.x1y1):
- on_sponge_edge['x+'] = False
- sponge_edges_covered['x+'] = True
- else:
- vertexFlags[start_index] = self.boundaryTags['sponge']
- else:
- pass
-
- end_vertex = vertices[end_index]
- if on_sponge_edge['x-']:
- if end_vertex not in (self.x0y0, self.x0y1):
- vertexFlags[end_index] = self.boundaryTags['sponge']
- if on_sponge_edge['x+']:
- if end_vertex not in (self.x1y0, self.x1y1):
- vertexFlags[end_index] = self.boundaryTags['sponge']
-
- def getSegmentFlag(start, end):
- if ((self.spongeLayers['x-'] and not sponge_edges_covered['x-']) or
- (self.spongeLayers['x+'] and not sponge_edges_covered['x+'])):
- checkSpongeStatus(start, end)
-
- if on_sponge_edge['x-'] or on_sponge_edge['x+']:
- return [self.boundaryTags['sponge'], ]
-
- else:
- if vertexFlags[start] in self.obstacle_flags:
- if vertexFlags[end] == vertexFlags[start]:
- return [vertexFlags[start], ]
- else:
- return [self.boundaryTags['y-'], ]
- elif vertexFlags[start] == self.boundaryTags['x+']:
- if vertexFlags[end] == self.boundaryTags['x-']:
- return [self.boundaryTags['y+'], ]
- else:
- return [self.boundaryTags['x+'], ]
-
- elif vertexFlags[start] == self.boundaryTags['x-']:
- if vertexFlags[end] == self.boundaryTags['x+']:
- return [self.boundaryTags['y-'], ]
- else:
- return [self.boundaryTags['x-'], ]
-
- elif vertexFlags[end] == self.boundaryTags['x+']:
- if vertexFlags[start] in [self.boundaryTags['y-'],
- self.boundaryTags['y+']]:
- return [self.boundaryTags['x+'], ]
-
- elif vertexFlags[end] == self.boundaryTags['x-']:
- if vertexFlags[start] in [self.boundaryTags['y-'],
- self.boundaryTags['y+']]:
- return [self.boundaryTags['x-'], ]
-
- elif vertexFlags[start] == self.boundaryTags['y-']:
- if (vertexFlags[end] == self.boundaryTags['y+']
- and np.isclose(vertices[start][0], vertices[end][0])
- ):
- return [self.boundaryTags['x+'], ]
- else:
- return [self.boundaryTags['y-'], ]
-
- elif vertexFlags[start] == self.boundaryTags['y+']:
- if (vertexFlags[end] == self.boundaryTags['y-']
- and np.isclose(vertices[start][0], vertices[end][0])
- ):
- return [self.boundaryTags['x-'], ]
- else:
- return [self.boundaryTags['y+'], ]
-
- else:
- return [vertexFlags[start], ]
-
- # ---- Initial Sponge Logic ---- #
- sponge_vertex_count = 0
-
- if self.spongeLayers['x-']:
- sponge_vertex_count += 2
- if self.spongeLayers['x+']:
- sponge_vertex_count += 2
-
- # ---- Build Main Segments ---- #
- for i in range(len(vertices) - 1 - sponge_vertex_count):
- segments += [[i, i + 1], ]
- segmentFlags += getSegmentFlag(i, i + 1)
- segments += [[len(vertices) - 1 - sponge_vertex_count, 0], ]
- segmentFlags += getSegmentFlag(len(vertices) - 1 - sponge_vertex_count,
- 0)
- if self.hole is False:
- start_vertex_obstacle = 0
- for obstacle in self.obstacles:
- segments += [[start_vertex_obstacle, start_vertex_obstacle + (len(obstacle) - 1)]]
- segmentFlags += [self.boundaryTags['y-']]
- start_vertex_obstacle += len(obstacle)
-
- # ---- Build Sponge Segments ---- #
- if self.spongeLayers['x-']:
- segments += [[vertices.index(self.x0y0),
- len(vertices) - sponge_vertex_count],
- [len(vertices) - sponge_vertex_count,
- len(vertices) - sponge_vertex_count + 1],
- [len(vertices) - sponge_vertex_count + 1,
- vertices.index(self.x0y1)]
- ]
- segmentFlags += [self.boundaryTags['y-'],
- self.boundaryTags['x-'],
- self.boundaryTags['y+']]
- if self.spongeLayers['x+']:
- segments += [[vertices.index(self.x1y0), len(vertices) - 2],
- [len(vertices) - 2, len(vertices) - 1],
- [len(vertices) - 1, vertices.index(self.x1y1)]
- ]
- segmentFlags += [self.boundaryTags['y-'],
- self.boundaryTags['x+'],
- self.boundaryTags['y+']]
-
- return segments, segmentFlags
-
- def _constructRegions(self, vertices, vertexFlags, segments, segmentFlags):
-
- ind_region = 0
- self.regionIndice = {}
- regions = []
- regionFlags = []
-
- if self.hole is False:
- for i, region in enumerate(self.obstacle_regions):
- regions = [[region[0], region[1]]]
- ind_region += 1
- regionFlags = [ind_region, ]
- self.regionIndice['obstacle' + repr(i + 1)] = ind_region - 1
-
- if True in list(self.corners.values()):
- regions += self._getCornerRegion()
- else:
- regions += self._getRandomRegion(vertices, segments)
-
- ind_region += 1
- regionFlags += [ind_region]
- self.regionIndice['tank'] = ind_region - 1
-
- sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
- sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
- sponge_x0 = self.x0y0[0]
- sponge_x1 = self.x1y0[0]
-
- if self.spongeLayers['x-']:
- regions += [[sponge_x0 - 0.5 * self.spongeLayers['x-'],
- sponge_half_height_x0]]
- ind_region += 1
- regionFlags += [ind_region]
- self.regionIndice['x-'] = ind_region - 1
- if self.spongeLayers['x+']:
- regions += [[sponge_x1 + 0.5 * self.spongeLayers['x+'],
- sponge_half_height_x1]]
- ind_region += 1
- regionFlags += [ind_region]
- self.regionIndice['x+'] = ind_region - 1
-
- return regions, regionFlags
-
- def _findExtrema(self, points):
- """
- Return the extrema of a series of points in n dimensions in the form:
- max(x1), max(x2), ... , max(xn), min(x1), ... , min(xn)
- """
- points = np.array(points)
- return np.max(points, 0).tolist() + np.min(points, 0).tolist()
-
- def _getCornerRegion(self):
- eps = np.finfo(float).eps
- if self.corners['x-y-']:
- return [[self.x0 + eps, self.y0 + eps], ]
- elif self.corners['x+y-']:
- return [[self.x1 - eps, self.y0 + eps], ]
- elif self.corners['x+y+']:
- return [[self.x1 - eps, self.y1 - eps], ]
- elif self.corners['x-y+']:
- return [[self.x0 + eps, self.y1 - eps], ]
-
- def _getRandomRegion(self, vertices, segments):
- x_p, y_p, x_n, y_n = self._findExtrema(vertices)
- if self.spongeLayers['x-']:
- x_n += self.spongeLayers['x-']
- if self.spongeLayers['x+']:
- x_p -= self.spongeLayers['x+']
-
- count = 0
- allowed_tries = 100
-
- while True:
- count += 1
- vertical_line = np.random.uniform(x_n, x_p)
- if True in [np.isclose(vertical_line, vertex[0]) for vertex in
- vertices]:
- continue
-
- lowest_intersect = second_intersect = y_p
-
- for segment in segments:
- line_x0 = vertices[segment[0]][0]
- line_y0 = vertices[segment[0]][1]
- line_x1 = vertices[segment[1]][0]
- line_y1 = vertices[segment[1]][1]
- if (line_x0 < vertical_line < line_x1
- or line_x0 > vertical_line > line_x1):
- # (due to the strict inequality check and
- # our selection of vertical_line - x1 > x0 should be sure)
- intersection_height = line_y0 + (
- (line_y1 - line_y0)
- * (vertical_line - line_x0)
- / (line_x1 - line_x0)
- )
- if intersection_height < lowest_intersect:
- second_intersect = lowest_intersect
- lowest_intersect = intersection_height
- elif intersection_height < second_intersect:
- second_intersect = intersection_height
-
- interior_point = 0.5 * (lowest_intersect + second_intersect)
-
- if lowest_intersect < interior_point < second_intersect:
- break
- if count > allowed_tries:
- ValueError(
- "Cannot find a proper interior point of the defined "
- "shape after " + str(count) + " tries.")
-
- return [[vertical_line, interior_point], ]
-
- def setAbsorptionZones(self, dragAlpha, x_n=False, x_p=False,
- dragBeta=0., porosity=1.):
- """
- Sets regions (x+, x-) to absorption zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient
- allSponge: bool
- If True, all sponge layers are converted to absorption zones.
- x_p: bool
- If True, x+ region is converted to absorption zone.
- x_n: bool
- If True, x- region is converted to absorption zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
- sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
- sponge_x0 = self.x0y0[0]
- sponge_x1 = self.x1y0[0]
-
- waves = None
- wind_speed = np.array([0., 0., 0.])
- if x_n or x_p:
- self._attachAuxiliaryVariable('RelaxZones')
- if x_n is True:
- center = np.array([sponge_x0 - 0.5 * self.spongeLayers['x-'],
- sponge_half_height_x0, 0.])
- ind = self.regionIndice['x-']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x-']/2.
- orientation = np.array([1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity)
- if x_p is True:
- center = np.array([sponge_x1 + 0.5 * self.spongeLayers['x+'],
- sponge_half_height_x1, 0.])
- ind = self.regionIndice['x+']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x+']/2.
- orientation = np.array([-1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='absorption',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity)
-
- def setGenerationZones(self, dragAlpha, smoothing, waves=None,
- wind_speed=(0., 0., 0.), x_n=False, x_p=False,
- dragBeta=0., porosity=1.):
- """
- Sets regions (x+, x-) to generation zones
-
- Parameters
- ----------
- dragAlpha: float
- Relaxation zone coefficient.
- smoothing: float
- Smoothing distance (typically 3*he)
- waves: proteus.WaveTools
- Class instance of wave generated from proteus.WaveTools.
- wind_speed: Optional[array_like]
- Speed of wind in generation zone (default is (0., 0., 0.))
- allSponge: bool
- If True, all sponge layers are converted to generation zones.
- x_p: bool
- If True, x+ region is converted to generation zone.
- x_n: bool
- If True, x- region is converted to generation zone.
- dragBeta: Optional[float]
- Relaxation zone coefficient.
- porosity: Optional[float]
- Relaxation zone coefficient.
- """
- sponge_half_height_x0 = 0.5 * (self.x0y0[1] + self.x0y1[1])
- sponge_half_height_x1 = 0.5 * (self.x1y0[1] + self.x1y1[1])
- sponge_x0 = self.x0y0[0]
- sponge_x1 = self.x1y0[0]
-
- waves = waves
- wind_speed = np.array(wind_speed)
- if x_n or x_p:
- self._attachAuxiliaryVariable('RelaxZones')
- if x_n is True:
-
- center = np.array([sponge_x0 - 0.5 * self.spongeLayers['x-'],
- sponge_half_height_x0, 0.])
- ind = self.regionIndice['x-']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x-']/2.
- orientation = np.array([1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity,
- smoothing=smoothing)
- self.BC['x-'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
- if x_p is True:
-
- center = np.array([sponge_x1 + 0.5 * self.spongeLayers['x+'],
- sponge_half_height_x1, 0.])
- ind = self.regionIndice['x+']
- flag = self.regionFlags[ind]
- epsFact_porous = self.spongeLayers['x+']/2.
- orientation = np.array([-1., 0.])
- self.zones[flag] = bc.RelaxationZone(shape=self,
- zone_type='generation',
- orientation=orientation,
- center=center,
- waves=waves,
- wind_speed=wind_speed,
- epsFact_porous=epsFact_porous,
- dragAlpha=dragAlpha,
- dragBeta=dragBeta,
- porosity=porosity,
- smoothing=smoothing)
- self.BC['x+'].setUnsteadyTwoPhaseVelocityInlet(wave=waves,
- wind_speed=wind_speed,
- smoothing=smoothing)
-
-
-def assembleDomain(domain):
- """
- This function sets up everything needed for the domain, meshing, and
- AuxiliaryVariables calculations (if any).
- It should always be called after defining and manipulating all the shapes
- to be attached to the domain.
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
- """
- _assembleGeometry(domain, BC_class=bc.BC_RANS)
- domain.BCbyFlag[0].setNonMaterial() # set BC for boundary between processors
- assembleAuxiliaryVariables(domain)
- if(domain.name != "PUMIDomain"):
- _generateMesh(domain)
-
-
-def assembleAuxiliaryVariables(domain):
- """
- Adds the auxiliary variables to the domain.
-
- Parameters
- ----------
- domain: proteus.Domain.D_base
- Domain class instance that hold all the geometrical informations and
- boundary conditions of the shape.
-
- Notes
- -----
- Should be called after assembleGeometry
- """
-
- domain.auxiliaryVariables = {
- 'dissipation': [],
- 'kappa': [],
- 'ls': [],
- 'ls_consrv': [],
- 'moveMesh': [],
- 'redist': [],
- 'twp': [],
- 'vof': [],
- 'thp': [],
- 'vos': [],
- 'SWFlow' :[]
- }
-
- zones_global = {}
- start_region = 0
- start_rflag = 0
- start_flag = 0
- for shape in domain.shape_list:
- aux = domain.auxiliaryVariables
- # ----------------------------
- # RIGID BODIES
- if 'RigidBody' in list(shape.auxiliaryVariables.keys()):
- body = shape.auxiliaryVariables['RigidBody']
- aux['twp'] += [body]
- # fixing mesh on rigid body
- for boundcond in shape.BC_list:
- boundcond.setRigidBodyMoveMesh(body)
- # update the indice for force/moment calculations
- body.i_start = start_flag + 1
- body.i_end = start_flag + 1 + len(shape.BC_list)
- if 'ChRigidBody' in list(shape.auxiliaryVariables.keys()):
- body = shape.auxiliaryVariables['ChRigidBody']
- for boundcond in shape.BC_list:
- boundcond.setChMoveMesh(body)
- if body.boundaryFlags.size == 0:
- flags = []
- for tag, flag in shape.boundaryTags.items():
- flags += [start_flag+flag]
- body.setBoundaryFlags(flags)
- if 'WallFunction' in list(shape.auxiliaryVariables.keys()):
- wall = shape.auxiliaryVariables['WallFunction']
- for ii in range(len(wall)):
- aux['twp'] += [wall[ii]]
- logEvent('WALL ATTACHED TO AUXVAR --> %s' % wall[ii])
- if 'kWallFunction' in list(shape.auxiliaryVariables.keys()):
- kWall = shape.auxiliaryVariables['kWallFunction']
- for ii in range(len(kWall)):
- aux['kappa'] += [kWall[ii]]
- logEvent('kWALL ATTACHED TO AUXVAR --> %s' % kWall[ii])
- # ----------------------------
- # ABSORPTION/GENERATION ZONES
-
- if 'RelaxZones' in list(shape.auxiliaryVariables.keys()):
- if not zones_global:
- aux['twp'] += [bc.RelaxationZoneWaveGenerator(zones_global,
- domain.nd)]
- # add relaxation zones to SWFlow AuxiliaryVariables
- aux['SWFlow'] += [bc.RelaxationZoneWaveGenerator(zones_global,
- domain.nd)]
- if not hasattr(domain, 'porosityTypes'):
- # create arrays of default values
- domain.porosityTypes = np.ones(len(domain.regionFlags) + 1)
- domain.dragAlphaTypes = np.zeros(len(domain.regionFlags) + 1)
- domain.dragBetaTypes = np.zeros(len(domain.regionFlags) + 1)
- domain.epsFact_porous = np.zeros(len(domain.regionFlags) + 1)
- i0 = start_region + 1
- for flag, zone in list(shape.zones.items()):
- ind = [i for i, f in enumerate(shape.regionFlags) if f == flag]
- for i1 in ind:
- domain.porosityTypes[i0 + i1] = zone.porosity
- domain.dragAlphaTypes[i0 + i1] = zone.dragAlpha
- domain.dragBetaTypes[i0 + i1] = zone.dragBeta
- domain.epsFact_porous[i0 + i1] = zone.epsFact_porous
- # update dict with global key instead of local key
- key = flag + start_rflag
- zones_global[key] = zone
- start_flag += len(shape.BC_list)
- # ----------------------------
- # GAUGES
- gauge_dict = {key: shape.auxiliaryVariables.get(key, [])
- for key in list(shape.auxiliaryVariables.keys())
- if str(key).startswith('Gauge_')}
- for key in list(gauge_dict.keys()):
- key_name = key.split('_', 1)[1] # Cutting off "Gauge_" prefix
- if key_name not in aux:
- # It is probably too dangerous to simply put "aux[key_name] = []"
- # as this system is fragile to typos. Instead, we throw an error.
- raise ValueError('ERROR: Gauge key ',
- key_name,
- ' is not a recognized model by SpatialTools.',
- ' The known models in our dictionary are ',
- str(list(aux.keys()))
- )
- else:
- aux[key_name] += gauge_dict[key]
- if shape.regions is not None:
- start_region += len(shape.regions)
- start_rflag = max(domain.regionFlags[0:start_region])
-
-
-def get_unit_vector(vector):
- return np.array(vector)/np.linalg.norm(vector)
\ No newline at end of file
diff --git a/proteus/mprans/__init__.py b/proteus/mprans/__init__.py
index 4c9c876dfa..28e5226f2a 100644
--- a/proteus/mprans/__init__.py
+++ b/proteus/mprans/__init__.py
@@ -1,35 +1,9 @@
-"""
-Modules for simulating free surface incompressible flow and fluid/structure interaction
-"""
+"""Deprecated: the free surface flow kernels are in proteus.kernels (C49 R1); see proteus._kernel_aliases."""
+from proteus import _kernel_aliases
-__all__ = ["AddedMass",
- "BodyDynamics",
- "BoundaryConditions",
- "Dissipation",
- "Kappa",
- "MoveMeshMonitor",
- "NCLS",
- "Pres",
- "RANS3PF",
- "SpatialTools",
- "VOF3P",
- "ArchiveBeams",
- "BoundaryConditions",
- "GN_SW2DCV",
- "MCorr3P",
- "MoveMesh",
- "PresInc",
- "RANS2P_IB",
- "RANS3PSed",
- "SW2DCV",
- "VOF",
- "beamFEM",
- "CLSVOF",
- "MCorr",
- "NCLS3P",
- "PresInit",
- "RANS2P",
- "RDLS",
- "SW2D",
- "VOS3P",
- "TADR"]
+_kernel_aliases.install(__name__)
+
+__all__ = ["AddedMass", "ArchiveBeams", "BodyDynamics", "BoundaryConditions", "CLSVOF", "Dissipation", "GN_SW2DCV",
+ "Kappa", "MCorr", "MCorr3P", "MoveMesh", "MoveMeshMonitor", "NCLS", "NCLS3P", "Pres", "PresInc", "PresInit",
+ "RANS2P", "RANS2P_IB", "RANS3PF", "RANS3PSed", "RDLS", "SW2D", "SW2DCV", "SpatialTools", "TADR", "VOF", "VOF3P",
+ "VOS3P", "beamFEM"]
diff --git a/proteus/pskRelations.h b/proteus/pskRelations.h
index ac0555db01..60ba5866e6 100644
--- a/proteus/pskRelations.h
+++ b/proteus/pskRelations.h
@@ -783,7 +783,7 @@ class PskSpline: public PskRelation
/** \file
\brief Richards free-function PSK closures (moved here from
- proteus/richards/psk_models.h).
+ proteus/kernels/psk_models.h).
The class hierarchy above (VGM/VGB/BCM/BCB/...) exposes the same
constitutive models through a stateful calc(Sw) interface. The routines
diff --git a/proteus/richards/ADR.h b/proteus/richards/ADR.h
deleted file mode 100644
index d2836d2a6d..0000000000
--- a/proteus/richards/ADR.h
+++ /dev/null
@@ -1,653 +0,0 @@
-#ifndef ADR_H
-#define ADR_H
-#include
-#include
-#include
-#include "CompKernel.h"
-#include "ModelFactory.h"
-#include "../mprans/ArgumentsDict.h"
-#include "pyarray.h"
-#define nnz nSpace
-
-namespace py = pybind11;
-#define POWER_SMOOTHNESS_INDICATOR 2
-#define IS_BETAij_ONE 0
-#define GLOBAL_FCT 0
-
-namespace proteus
-{
-namespace richards
-{
- class ADR_base
- {
- //The base class defining the interface
- public:
- virtual ~ADR_base(){}
- virtual void calculateResidual(arguments_dict& args)=0;
- virtual void calculateJacobian(arguments_dict& args)=0;
- };
-
- template
-
- class ADR : public ADR_base
- {
- public:
- const int nDOF_test_X_trial_element;
- CompKernelType ck;
- ADR():
- nDOF_test_X_trial_element(nDOF_test_element*nDOF_trial_element),
- ck()
- {}
-
- inline
-
- void evaluateCoefficients(const proteus_csr_index_t rowptr[nSpace],
- const proteus_csr_index_t colind[nnz],
- const double rho,
- const double beta,
- const double gravity[nSpace],
- const double alpha,
- const double n_vg,
- const double thetaR,
- const double thetaSR,
- const double KWs[nnz],
- const double& u,
- double& m,
- double& dm,
- double f[nSpace],
- double df[nSpace],
- double a[nnz],
- double da[nnz],
- double as[nnz],
- double& kr,
- double& dkr)
- {
- const int nSpace2 = nSpace * nSpace;
- double psiC;
- double pcBar;
- double pcBar_n;
- double pcBar_nM1;
- double pcBar_nM2;
- double onePlus_pcBar_n;
- double sBar;
- double sqrt_sBar;
- double DsBar_DpsiC;
- double thetaW;
- double DthetaW_DpsiC;
- double vBar;
- double vBar2;
- double DvBar_DpsiC;
- double KWr;
- double DKWr_DpsiC;
- double rho2 = rho * rho;
- double thetaS;
- double rhom;
- double drhom;
- double m_vg;
- double pcBarStar;
- double sqrt_sBarStar;
- m = u; //rhom*thetaW; //u
- dm = 1.0; //-rhom*DthetaW_DpsiC+drhom*thetaW;// 1.0;//
- for (int I=0;I& mesh_trial_ref = args.array("mesh_trial_ref");
- proteus::pyarray& mesh_grad_trial_ref = args.array("mesh_grad_trial_ref");
- proteus::pyarray& mesh_dof = args.array("mesh_dof");
- proteus::pyarray& mesh_velocity_dof = args.array("mesh_velocity_dof");
- double MOVING_DOMAIN = args.scalar("MOVING_DOMAIN");
- proteus::pyarray& mesh_l2g = args.array("mesh_l2g");
- proteus::pyarray& dV_ref = args.array("dV_ref");
- proteus::pyarray& u_trial_ref = args.array("u_trial_ref");
- proteus::pyarray& u_grad_trial_ref = args.array("u_grad_trial_ref");
- proteus::pyarray& u_test_ref = args.array("u_test_ref");
- proteus::pyarray& u_grad_test_ref = args.array("u_grad_test_ref");
- proteus::pyarray& mesh_trial_trace_ref = args.array("mesh_trial_trace_ref");
- proteus::pyarray& mesh_grad_trial_trace_ref = args.array("mesh_grad_trial_trace_ref");
- proteus::pyarray& dS_ref = args.array("dS_ref");
- proteus::pyarray& u_trial_trace_ref = args.array("u_trial_trace_ref");
- proteus::pyarray& u_grad_trial_trace_ref = args.array("u_grad_trial_trace_ref");
- proteus::pyarray& u_test_trace_ref = args.array("u_test_trace_ref");
- proteus::pyarray& u_grad_test_trace_ref = args.array("u_grad_test_trace_ref");
- proteus::pyarray& normal_ref = args.array("normal_ref");
- proteus::pyarray& boundaryJac_ref = args.array("boundaryJac_ref");
- proteus_index_t nElements_global = args.scalar("nElements_global");
- proteus::pyarray& ebqe_penalty_ext = args.array("ebqe_penalty_ext");
- proteus::pyarray& elementMaterialTypes = args.array("elementMaterialTypes");
- proteus::pyarray& isSeepageFace = args.array("isSeepageFace");
- proteus::pyarray& a_rowptr = args.array("a_rowptr");
- proteus::pyarray& a_colind = args.array("a_colind");
- double rho = args.scalar("rho");
- double beta = args.scalar("beta");
- proteus::pyarray& gravity = args.array("gravity");
- proteus::pyarray& alpha = args.array("alpha");
- proteus::pyarray& n = args.array("n");
- proteus::pyarray& thetaR = args.array("thetaR");
- proteus::pyarray& thetaSR = args.array("thetaSR");
- proteus::pyarray& KWs = args.array("KWs");
- double useMetrics = args.scalar("useMetrics");
- double alphaBDF = args.scalar("alphaBDF");
- int lag_shockCapturing = args.scalar("lag_shockCapturing");
- double shockCapturingDiffusion = args.scalar("shockCapturingDiffusion");
- double sc_uref = args.scalar("sc_uref");
- double sc_alpha = args.scalar("sc_alpha");
- proteus::pyarray& u_l2g = args.array("u_l2g");
- proteus::pyarray& elementDiameter = args.array("elementDiameter");
- proteus::pyarray& u_dof = args.array("u_dof");
- proteus::pyarray& u_dof_old = args.array("u_dof_old");
- proteus::pyarray& velocity = args.array("velocity");
- proteus::pyarray& q_m = args.array("q_m");
- proteus::pyarray& q_u = args.array("q_u");
- proteus::pyarray& q_dV = args.array("q_dV");
- proteus::pyarray& q_m_betaBDF = args.array("q_m_betaBDF");
- proteus::pyarray& cfl = args.array("cfl");
- proteus::pyarray& q_numDiff_u = args.array("q_numDiff_u");
- proteus::pyarray& q_numDiff_u_last = args.array("q_numDiff_u_last");
- proteus_index_t offset_u = args.scalar("offset_u");
- proteus_index_t stride_u = args.scalar("stride_u");
- proteus::pyarray& globalResidual = args.array("globalResidual");
- proteus_index_t nExteriorElementBoundaries_global = args.scalar("nExteriorElementBoundaries_global");
- proteus::pyarray& exteriorElementBoundariesArray = args.array("exteriorElementBoundariesArray");
- proteus::pyarray& elementBoundaryElementsArray = args.array("elementBoundaryElementsArray");
- proteus::pyarray& elementBoundaryLocalElementBoundariesArray = args.array("elementBoundaryLocalElementBoundariesArray");
- proteus::pyarray& ebqe_velocity_ext = args.array("ebqe_velocity_ext");
- proteus::pyarray& isDOFBoundary_u = args.array("isDOFBoundary_u");
- proteus::pyarray& ebqe_bc_u_ext = args.array("ebqe_bc_u_ext");
- proteus::pyarray& isFluxBoundary_u = args.array("isFluxBoundary_u");
- proteus::pyarray& ebqe_bc_flux_ext = args.array("ebqe_bc_flux_ext");
- proteus::pyarray& ebqe_phi = args.array("ebqe_phi");
- double epsFact = args.scalar("epsFact");
- proteus::pyarray& ebqe_u = args.array("ebqe_u");
- proteus::pyarray& ebqe_flux = args.array("ebqe_flux");
- // PARAMETERS FOR EDGE BASED STABILIZATION
- double cE = args.scalar("cE");
- double cK = args.scalar("cK");
- // PARAMETERS FOR LOG BASED ENTROPY FUNCTION
- double uL = args.scalar("uL");
- double uR = args.scalar("uR");
- // PARAMETERS FOR EDGE VISCOSITY
- proteus_index_t numDOFs = args.scalar("numDOFs");
- proteus_csr_index_t NNZ = args.scalar("NNZ");
- proteus::pyarray& csrRowIndeces_DofLoops = args.array("csrRowIndeces_DofLoops");
- proteus::pyarray& csrColumnOffsets_DofLoops = args.array("csrColumnOffsets_DofLoops");
- proteus::pyarray& csrRowIndeces_CellLoops = args.array("csrRowIndeces_CellLoops");
- proteus::pyarray& csrColumnOffsets_CellLoops = args.array("csrColumnOffsets_CellLoops");
- proteus::pyarray& csrColumnOffsets_eb_CellLoops = args.array("csrColumnOffsets_eb_CellLoops");
- // C matrices
- proteus::pyarray& Cx = args.array("Cx");
- proteus::pyarray& Cy = args.array("Cy");
- proteus::pyarray& Cz = args.array("Cz");
- proteus::pyarray& CTx = args.array("CTx");
- proteus::pyarray& CTy = args.array("CTy");
- proteus::pyarray& CTz = args.array("CTz");
- proteus::pyarray& ML = args.array("ML");
- proteus::pyarray& delta_x_ij = args.array("delta_x_ij");
- // PARAMETERS FOR 1st or 2nd ORDER MPP METHOD
- int LUMPED_MASS_MATRIX = args.scalar("LUMPED_MASS_MATRIX");
- int STABILIZATION_TYPE = args.scalar("STABILIZATION_TYPE");
- int ENTROPY_TYPE = args.scalar("ENTROPY_TYPE");
- // FOR FCT
- proteus::pyarray& dLow = args.array("dLow");
- proteus::pyarray& fluxMatrix = args.array("fluxMatrix");
- proteus::pyarray& uDotLow = args.array("uDotLow");
- proteus::pyarray& uLow = args.array("uLow");
- proteus::pyarray& dt_times_fH_minus_fL = args.array("dt_times_fH_minus_fL");
- proteus::pyarray& min_s_bc = args.array("min_s_bc");
- proteus::pyarray& max_s_bc = args.array("max_s_bc");
- // AUX QUANTITIES OF INTEREST
- proteus::pyarray& quantDOFs = args.array("quantDOFs");
- proteus::pyarray& sLow = args.array("sLow");
- proteus::pyarray& sn = args.array("sn");
-
- assert(a_rowptr.data()[nSpace] == nnz);
- assert(a_rowptr.data()[nSpace] == nSpace);
- //cek should this be read in?
- double Ct_sge = 4.0;
- // if (LUMPED_MASS_MATRIX ==1)
- // {
- // mass_lumping(nElements_global, nDOF_test_element, nQuadraturePoints_element, u_test_ref, dV_ref, ML, u_l2g);
- // }
-
- //loop over elements to compute volume integrals and load them into element and global residual
- //
- //eN is the element index
- //eN_k is the quadrature point index for a scalar
- //eN_k_nSpace is the quadrature point index for a vector
- //eN_i is the element test function index
- //eN_j is the element trial function index
- //eN_k_j is the quadrature point index for a trial function
- //eN_k_i is the quadrature point index for a trial function
- for(proteus_index_t eN=0;eN& mesh_trial_ref = args.array("mesh_trial_ref");
- proteus::pyarray& mesh_grad_trial_ref = args.array("mesh_grad_trial_ref");
- proteus::pyarray& mesh_dof = args.array("mesh_dof");
- proteus::pyarray& mesh_velocity_dof = args.array("mesh_velocity_dof");
- double MOVING_DOMAIN = args.scalar("MOVING_DOMAIN");
- proteus::pyarray& mesh_l2g = args.array("mesh_l2g");
- proteus::pyarray& dV_ref = args.array("dV_ref");
- proteus::pyarray& u_trial_ref = args.array("u_trial_ref");
- proteus::pyarray& u_grad_trial_ref = args.array("u_grad_trial_ref");
- proteus::pyarray& u_test_ref = args.array("u_test_ref");
- proteus::pyarray& u_grad_test_ref = args.array("u_grad_test_ref");
- proteus::pyarray& mesh_trial_trace_ref = args.array("mesh_trial_trace_ref");
- proteus::pyarray& mesh_grad_trial_trace_ref = args.array("mesh_grad_trial_trace_ref");
- proteus::pyarray& dS_ref = args.array("dS_ref");
- proteus::pyarray& u_trial_trace_ref = args.array("u_trial_trace_ref");
- proteus::pyarray& u_grad_trial_trace_ref = args.array("u_grad_trial_trace_ref");
- proteus::pyarray& u_test_trace_ref = args.array("u_test_trace_ref");
- proteus::pyarray& u_grad_test_trace_ref = args.array("u_grad_test_trace_ref");
- proteus::pyarray& normal_ref = args.array("normal_ref");
- proteus::pyarray& boundaryJac_ref = args.array("boundaryJac_ref");
- proteus_index_t nElements_global = args.scalar("nElements_global");
- proteus::pyarray& ebqe_penalty_ext = args.array("ebqe_penalty_ext");
- proteus::pyarray& elementMaterialTypes = args.array("elementMaterialTypes");
- proteus::pyarray& isSeepageFace = args.array("isSeepageFace");
- proteus::pyarray& a_rowptr = args.array("a_rowptr");
- proteus::pyarray& a_colind = args.array("a_colind");
- double rho = args.scalar("rho");
- double beta = args.scalar("beta");
- proteus::pyarray& gravity = args.array("gravity");
- proteus::pyarray& alpha = args.array("alpha");
- proteus::pyarray& n = args.array("n");
- proteus::pyarray& thetaR = args.array("thetaR");
- proteus::pyarray& thetaSR = args.array("thetaSR");
- proteus::pyarray& KWs = args.array("KWs");
- double useMetrics = args.scalar("useMetrics");
- double alphaBDF = args.scalar("alphaBDF");
- int lag_shockCapturing = args.scalar("lag_shockCapturing");
- double shockCapturingDiffusion = args.scalar("shockCapturingDiffusion");
- proteus::pyarray& u_l2g = args.array("u_l2g");
- proteus::pyarray