Compare commits

..
Author SHA1 Message Date
camierjs f2a424720b Merge branch 'main' into hpcftools/flowSolver-gpu 2025-06-30 11:17:56 -07:00
camierjs e5fad8067c Merge branch 'master' into hpcftools/flowSolver-gpu 2025-06-30 11:17:45 -07:00
camierjs 0b5bb52996 miniapps/navier/incompressible_navier_dfem 2025-06-30 11:17:11 -07:00
camierjs 563bfe9514 Merge branch 'master' 2025-06-30 08:43:14 -07:00
Veselin Dobrev c53a016d06 Merge pull request #4818 from mfem/mesh-transform-dev
Adding an affine transformation to mesh-explorer
2025-06-28 07:58:55 -07:00
Veselin Dobrev ea2b42c49d Merge pull request #4903 from mfem/fix-umpire-introspection-off
better umpire device deallocation
2025-06-28 07:57:55 -07:00
John Camier c7e066a0d3 Merge branch 'master' into fix-umpire-introspection-off 2025-06-28 06:26:17 -07:00
Veselin Dobrev 0a5730eac3 Merge pull request #4769 from mfem/dev/abs-diag-smoothers
Abs-Val-Jacobi-type of preconditions/smoothers for PA operators
2025-06-26 09:36:30 -07:00
Veselin Dobrev 477c475c1a Merge pull request #4893 from mfem/gpu-omp
Use device priorities for vector dot, min and max
2025-06-24 12:33:16 -07:00
Veselin Dobrev 34fdcddb8d Merge pull request #4810 from mfem/plbound
Bounding high-order FEM functions
2025-06-24 12:31:47 -07:00
Veselin Dobrev 91fa9936ef Merge pull request #4835 from mfem/fix-nurbsext-constructor
NURBSExtension Constructor and edge_to_knot mapping
2025-06-24 12:29:14 -07:00
Veselin Dobrev d95e6e0adc Merge pull request #4854 from mfem/pref-mixed-serial
Restore p-refinement on serial mixed meshes
2025-06-24 12:27:52 -07:00
John Camier 82d3b8b92e Merge branch 'master' into gpu-omp 2025-06-23 16:11:10 -07:00
Veselin Dobrev e9782cf437 Merge pull request #4667 from mfem/hughcars/array-back-inserter
Allow std::back_inserter with Array<T>
2025-06-23 10:20:26 -07:00
John Camier 9a9f64d8bb Merge branch 'master' into hughcars/array-back-inserter 2025-06-22 20:26:26 -07:00
John Camier 9c90e3830a Merge branch 'master' into gpu-omp 2025-06-22 20:25:27 -07:00
John Camier a8e83d2f0d Merge branch 'master' into fix-umpire-introspection-off 2025-06-22 20:23:40 -07:00
Gabriel Pinochet-Soto 288657ebbd Use SLI + Mass integrator as example 2025-06-21 13:11:25 -07:00
Gabriel Pinochet-Soto 5a26bd936c Merge branch 'master' of github.com:mfem/mfem into dev/abs-diag-smoothers 2025-06-21 13:05:49 -07:00
Veselin Dobrev 0eb3001197 Merge pull request #4902 from mfem/doftrans-fix
Fix bug relating to DofTransformation
2025-06-20 23:32:07 -07:00
Gabriel Pinochet-Soto 05034b8917 Correct examples; vis is true 2025-06-20 16:58:45 -07:00
Tom Stitt 32aea6ed2d deallocate via the allocator instead of the resource manager. fixes use of device allocators with introspection off 2025-06-20 14:15:31 -07:00
Gabriel Pinochet-Soto 9407050e6a Revert "Update to use maps->Abs"
This reverts commit 0515209ffd.
2025-06-18 23:09:29 -07:00
Gabriel Pinochet-Soto 0515209ffd Update to use maps->Abs 2025-06-18 20:05:11 -07:00
Gabriel Pinochet-Soto 3446b46420 Merge branch 'master' of github.com:mfem/mfem into dev/abs-diag-smoothers 2025-06-18 19:37:54 -07:00
Gabriel Pinochet-Soto f8f18f8722 Remove warning 2025-06-18 19:33:37 -07:00
Gabriel Pinochet-Soto e7eabeb5e2 Remove TODOs bilinearform_ext.cpp 2025-06-18 18:55:22 -07:00
Will Pazner 71f25f5e16 Fix bug relating to DofTransformation
In FiniteElementSpace::GetElementDofs and related functions, set the
DofTransformation object to identity if no transformation is needed.
2025-06-18 16:53:32 -07:00
John Camier 57b5d23e4b Merge branch 'master' into gpu-omp 2025-06-18 10:21:40 -07:00
Veselin Dobrev 43c50376eb Merge pull request #4857 from mfem/hughcars/ho-make-simplicial-dev
Add higher order support to `MakeSimplicial`
2025-06-17 21:13:07 -07:00
Veselin Dobrev e4a066edf4 Merge branch 'master' into hughcars/ho-make-simplicial-dev 2025-06-17 20:17:51 -07:00
Veselin Dobrev 886a4c89e4 Merge pull request #4850 from mfem/bugfix/l2pos_p0_pyramid
Adding p=0 special case to L2Pos_PyramidElement
2025-06-17 20:13:26 -07:00
Veselin Dobrev b36ed0e9e9 Merge pull request #4897 from mfem/deterministic-output
Deterministic miniapp output
2025-06-17 20:12:03 -07:00
John Camier 4f3c73b3eb Merge branch 'master' into gpu-omp 2025-06-17 17:01:31 -07:00
Mittal, Ketan 8be13975b0 Merge branch 'plbound' of https://github.com/mfem/mfem into plbound 2025-06-17 11:49:40 -07:00
Mittal, Ketan 7fce328f12 fix spacing before sample run 2025-06-17 11:43:42 -07:00
Tzanio Kolev e72ed572c4 Merge pull request #4877 from mfem/doftrans-three-arg
Avoid using internal DofTransformation object
2025-06-17 08:10:04 -07:00
Tzanio Kolev bfa68b0b18 Merge pull request #4889 from mfem/device-doxygen-fix
Fix the doxygen formatting of Device::Configure
2025-06-17 08:08:53 -07:00
Veselin Dobrev 56b1a1715a Use DofToQuad::Abs in a few places. Remove unused methods AddAbsMult*.
Small doxygen tweaks.
2025-06-17 01:16:34 -07:00
Veselin Dobrev 3514c0f0d4 Merge branch 'master' into dev/abs-diag-smoothers
Resolved conflicts:
   CHANGELOG
   makefile
   miniapps/CMakeLists.txt
2025-06-16 22:14:00 -07:00
Will Pazner 1181253c61 Disable LOR device sample runs
Results can be non-determinstic on device because of atomics in the matrix
assembly algorithm.
2025-06-16 12:12:52 -07:00
Dylan Copeland d379628b54 Deterministic error output for phpref miniapp. 2025-06-16 11:10:33 -07:00
John Camier ec45731607 Merge branch 'master' into hughcars/array-back-inserter 2025-06-16 08:40:13 -07:00
John Camier 19b57a28b7 Merge branch 'master' into device-doxygen-fix 2025-06-16 08:33:30 -07:00
camierjs 5791aa4629 Merge branch 'master' into gpu-omp 2025-06-13 13:43:40 -07:00
Tzanio Kolev 46627b8655 Merge pull request #4804 from mfem/dfem-phase1-dev
dFEM Phase 1
2025-06-13 12:58:02 -07:00
camierjs 18cff41dac Merge branch 'master' into gpu-omp 2025-06-13 11:51:56 -07:00
Tzanio Kolev b5366e3ad3 Merge branch 'master' into dev/abs-diag-smoothers 2025-06-13 10:56:52 -07:00
Tzanio Kolev 0fe2887b1c Merge branch 'master' into dfem-phase1-dev 2025-06-13 10:50:41 -07:00
Tzanio Kolev 03ad5fbae5 Merge pull request #4878 from mfem/minor-clean-pfindpts
Minor cleanups to `pfindpts.cpp` [minor-clean-pfindpts]
2025-06-13 10:50:30 -07:00
John Camier a018c66a9e Merge branch 'master' into device-doxygen-fix 2025-06-13 08:47:30 -07:00
camierjs fb9449c47d Adjust use_dev code path, make style & const 2025-06-13 08:31:55 -07:00
Veselin Dobrev 14be9236bc Small formatting edits in dfem-minimal-surface.cpp 2025-06-12 17:39:41 -07:00
Veselin Dobrev 45d38fd1ba Add fem/dfem to doxygen and fix the doxygen warnings there 2025-06-12 16:06:18 -07:00
camierjs 1555bfe3a5 Move reduction internals to reducers header 2025-06-12 11:56:50 -07:00
camierjs a3b12b6f97 Use device priorities for vector dot, min and max 2025-06-12 11:27:06 -07:00
Tzanio Kolev 734ae021f0 Merge branch 'master' into dfem-phase1-dev 2025-06-12 07:47:38 -07:00
Julian Andrej 2c23f5b0bd fixing UB 2025-06-11 20:57:54 -07:00
Tzanio Kolev c82d9bd8a0 Merge branch 'master' into dev/abs-diag-smoothers 2025-06-11 20:09:17 -07:00
Tzanio Kolev a17fb5b587 Merge pull request #4891 from mfem/lor-fixes
LOR bug fixes
2025-06-11 17:32:45 -07:00
Julian Andrej bc404c0f85 more compiler warnings 2025-06-11 14:02:23 -07:00
Tzanio Kolev 1e6ee60790 Merge branch 'master' into dev/abs-diag-smoothers 2025-06-11 10:14:46 -07:00
Will Pazner 8e59709ab8 Explicitly compare against nullptr 2025-06-11 09:30:31 -07:00
Will Pazner f4d0cef65c Compute PtAP when needed in batched LOR assembly
In serial on AMR meshes, the P matrix will not be identity.
2025-06-11 09:24:06 -07:00
Will Pazner 1bef281b45 Fix bug in LORBase::AddIntegratorsAndMarkers
Was previously potentially dereferencing null pointer
2025-06-11 09:21:38 -07:00
Veselin Dobrev 95a86d2bd8 Merge pull request #4869 from mfem/fix-sample-runs
Fix sample runs
2025-06-10 22:13:30 -07:00
Veselin Dobrev ccfee841cb Fix the doxygen formatting of Device::Configure 2025-06-10 17:43:38 -07:00
Julian Andrej 7f9cba0daa address warnings 2025-06-10 13:25:05 -07:00
Veselin Dobrev 1ae0d6bef6 Adjust the sample runs in miniapps/electromagnetics/maxwell.cpp 2025-06-10 12:36:06 -07:00
Veselin Dobrev b7ff8749a3 Fix out-of-source testing with GNU make.
Adjust a tolerance in miniapps/nurbs/nurbs_solenoidal.cpp for macOS.

Fix typos in the miniapps/nurbs/makefile in the nurbs_solenoidal tests.

Re-formatting some long lines.
2025-06-09 18:19:09 -07:00
Joseph SignorelliandTzanio Kolev 6031b7b2a3 Update miniapps/gslib/pfindpts.cpp
Co-authored-by: Tzanio Kolev <tzanio@llnl.gov>
2025-06-09 09:32:22 -07:00
Joseph SignorelliandTzanio Kolev 3efda06ca8 Update miniapps/gslib/pfindpts.cpp
Co-authored-by: Tzanio Kolev <tzanio@llnl.gov>
2025-06-09 09:32:08 -07:00
Julian Andrej 55c7f5821e Merge branch 'dfem-phase1-dev' of github.com:mfem/mfem into dfem-phase1-dev 2025-06-09 07:58:41 -07:00
Julian Andrej 4ffa0434f7 Revert "forall dispatch fix"
This reverts commit 3f097ae869.
2025-06-09 07:58:20 -07:00
Veselin Dobrev 2a30ba157f Fix a bug introduced in the last commit 2025-06-08 22:46:07 -07:00
Veselin Dobrev 1d1a33b365 Attempt to fix warnings from the intel-classic compiler 2025-06-08 22:17:28 -07:00
Veselin Dobrev 6c8349dbbe Add to GNU make the hypre dependency to cusolver when built with CUDA 2025-06-08 17:55:33 -10:00
Julian Andrej e4b760a30b exclude hip runs for autotest 2025-06-08 13:36:20 -07:00
Julian Andrej 18ca7ab2c9 collect norm for v in fdjacobian 2025-06-07 13:43:23 -07:00
Julian Andrej 3f097ae869 forall dispatch fix 2025-06-07 11:59:33 -07:00
Julian Andrej f912b347a2 Merge branch 'dfem-phase1-dev' of github.com:mfem/mfem into dfem-phase1-dev 2025-06-07 09:03:51 -07:00
Julian Andrej 90a6dc7c99 collect norm in parallel for fd 2025-06-07 09:03:39 -07:00
Julian AndrejandTom Stitt 17455e7b08 Update INSTALL
Co-authored-by: Tom Stitt <stitt4@llnl.gov>
2025-06-06 11:03:43 -07:00
Joseph Signorelli 81f209953e Clarifications + formatting fixes to -h 2025-06-06 10:27:21 -07:00
Joseph Signorelli b3d4579618 Fix searched total points 2025-06-06 10:27:11 -07:00
Andrew Ho 47855ff8cf fix base case for not compiling with cuda 2025-06-05 12:31:19 -07:00
Andrew Ho 115a11bf79 Merge remote-tracking branch 'base/dfem-phase1-dev' into dfem-phase1-dev 2025-06-05 11:34:52 -07:00
Andrew Ho b81cce6f45 new hypre links to cusolver by default now 2025-06-05 11:33:20 -07:00
Andrew Ho 550ca6b702 rename beta to beta_
something is conflicting with beta, possibly std::beta imported into the global namespace?
2025-06-05 11:32:35 -07:00
Andrew Ho 5be6c032db fix for old nvcc 2025-06-05 11:32:06 -07:00
Julian Andrej 1eafad0af9 make it easier for old compilers 2025-06-05 09:58:40 -07:00
Julian Andrej e61ac08b8d make ancient compilers happy 2025-06-05 09:09:00 -07:00
Julian Andrej 37b22e4e48 specifically add array header 2025-06-05 08:15:10 -07:00
Julian Andrej 767f4bde18 remove fallback return 2025-06-04 20:36:32 -07:00
Julian Andrej e09d02ff2f missing const 2025-06-04 17:54:55 -07:00
Julian Andrej da9a797b46 make objects all std::function 2025-06-04 17:36:33 -07:00
Julian Andrej 92d8e7f46b try different return types 2025-06-04 17:10:40 -07:00
Julian Andrej a147b61e98 maybe fix tuple 2025-06-04 16:00:27 -07:00
Julian Andrej 14323a6da5 really fix tuple 2025-06-04 15:14:26 -07:00
Julian Andrej b30809a663 tuple fixes 2025-06-04 15:10:03 -07:00
Julian Andrej e68e96cd00 Merge branch 'dfem-phase1-dev' of github.com:mfem/mfem into dfem-phase1-dev 2025-06-04 14:43:47 -07:00
Julian Andrej d9e7737354 address nvcc warnings 2025-06-04 14:43:37 -07:00
Hugh Carson 01479824f5 Address MR feedback
- Remove static_cast to void, rely on future usage of [[nodiscard]] for dangerous discards
- Restore explicit to prevent implicit conversion of initializer_list
2025-06-04 16:16:02 -04:00
Joseph SignorelliandKetan Mittal 389f1ef5ce Update miniapps/gslib/pfindpts.cpp
Co-authored-by: Ketan Mittal <ketan.mittal@gmail.com>
2025-06-04 12:30:01 -07:00
Ketan Mittalandtarikdzanic a72d85fa6c Update fem/bounds.cpp
Co-authored-by: tarikdzanic <41964501+tarikdzanic@users.noreply.github.com>
2025-06-03 16:47:49 -07:00
Mittal, Ketan 0fd9dcceb3 change some raw ptrs to unique ptrs 2025-06-03 12:55:04 -07:00
Andrew Ho 346f5b28c9 Added --expt-relaxed-constexpr for cmake 2025-06-03 10:07:12 -07:00
Andrew Ho 3867b49d3b qfunction lambda needs MFEM_HOST_DEVICE for nvcc
C++17 lambdas are supposed to be automatically constexpr if possible,
but nvcc doesn't appear to do this
2025-06-03 10:00:43 -07:00
Joseph Signorelli e4a32db1dc style 2025-06-03 06:50:52 -07:00
Joseph Signorelli 84cb244bc2 Remove unused code + clarify points are random, not equidistant 2025-06-03 06:44:13 -07:00
Will Pazner 11b878612b Use three-argument version of GetElementDofs…
…and related functions that return a pointer to an internal DofTransformation
object that may be invalidated unexpectedly.
2025-06-02 21:04:31 -07:00
Mittal, Ketan b66d56ee9b Merge branch 'plbound' of https://github.com/mfem/mfem into plbound 2025-06-02 10:35:55 -07:00
Mittal, Ketan 9852e93449 reviewer comment 2025-06-02 10:35:46 -07:00
Julian Andrej dc45953e0d change return statement position 2025-06-02 08:17:39 -07:00
camierjs b4ebf12ff8 Adjust dFEM diffusion tests default q1d 2025-06-01 19:39:57 -07:00
camierjs f9cc9c6c15 Clarify unused input when not in 'solutions' 2025-06-01 19:27:34 -07:00
Julian Andrej 28094ba952 Revert "higher order diffusion integration rule"
This reverts commit 72c7405b08.
2025-06-01 15:22:01 -07:00
Julian Andrej 72c7405b08 higher order diffusion integration rule 2025-06-01 14:56:05 -07:00
Julian Andrej 2ce3063b2c fix for internal tests 2025-06-01 14:29:03 -07:00
Julian Andrej dbd90b50cb fix divergence test 2025-06-01 14:25:25 -07:00
camierjs b640cbe587 [dFEM] Add VectorDiffusion tests, Wip VectorDivergence 2025-06-01 10:58:13 -07:00
Tzanio Kolev 5a4ba178bb minor 2025-05-30 17:44:38 -07:00
Tzanio Kolev f4c44a86bc more fixes 2025-05-30 17:18:56 -07:00
Tzanio Kolev a2e780d18d minor 2025-05-30 17:11:15 -07:00
Tzanio Kolev 2855a6daa3 Updated INSTALL for Enzyme on RHEL9. Renamed dfem-minimal-surface.cpp 2025-05-30 16:55:09 -07:00
Julian Andrej 490026763d change miniapp target name 2025-05-30 16:29:02 -07:00
Julian Andrej 087a87bf40 build fixes 2025-05-30 14:57:00 -07:00
Andrew Ho 43c5a04aae update minimal_surface example run samples documentation 2025-05-30 14:54:01 -07:00
Julian Andrej cda6ee0580 Update INSTALL 2025-05-30 14:13:34 -07:00
Tzanio Kolev a3639fe70c Merge branch 'dfem-phase1-dev' of github.com:mfem/mfem into dfem-phase1-dev 2025-05-30 13:35:28 -07:00
Tzanio Kolev 78c5f51309 Moved dFEM's minimal surface to a miniapp 2025-05-30 13:34:41 -07:00
Julian Andrej 3880a48af5 make the dfem example unambiguous 2025-05-30 12:34:33 -07:00
Tzanio Kolev 9f7f84defb Updated dFEM description in CHANGELOG 2025-05-30 10:24:40 -07:00
ce5fd63d0a dfem phase 1 changes
Co-authored-by: camierjs <camierjs@gmail.com>
Co-authored-by: Veselin Dobrev <dobrev@llnl.gov>
2025-05-29 13:02:23 -07:00
Ketan Mittal 27db3a4121 Merge branch 'master' into plbound 2025-05-29 10:49:30 -07:00
Hugh Carson e3c45310b0 Merge branch 'master' into hughcars/array-back-inserter 2025-05-29 13:24:09 -04:00
Gabriel Pinochet-Soto a35ef68c2a Style correction... 2025-05-28 11:35:12 -07:00
Gabriel Pinochet-Soto 2fca844393 Implement L(p,q) elementwise, update CHANGELOG 2025-05-28 11:32:50 -07:00
Gabriel Pinochet-Soto 698183a8db Correct examples 2025-05-28 10:42:20 -07:00
Gabriel Pinochet-Soto fa61508248 Merge branch 'master' of github.com:mfem/mfem into dev/abs-diag-smoothers 2025-05-27 22:44:20 -07:00
Gabriel Pinochet-Soto d2baadad26 Update descriptions, add --device cuda example 2025-05-27 17:30:03 -07:00
Hugh Carson fdec992469 Merge branch 'master' into hughcars/ho-make-simplicial-dev 2025-05-27 17:40:43 -04:00
Mittal, Ketan 0aa68f431f Merge branch 'master' of https://github.com/mfem/mfem into plbound 2025-05-27 11:58:58 -07:00
Mittal, Ketan d2288ef6fd another reviewer comment 2025-05-27 11:58:34 -07:00
Ketan MittalandWill Pazner 6f882ed87e Update fem/pgridfunc.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-27 11:23:26 -07:00
Mittal, Ketan 813a7de323 reviewer comments 2025-05-27 11:18:28 -07:00
Justin Laughlin cc4f5625e2 Merge branch 'master' into fix-nurbsext-constructor 2025-05-27 09:27:59 -07:00
Mittal, Ketan f4baef8b5d fix shadow declaration 2025-05-26 17:06:59 -07:00
Mittal, Ketan 0e4b0f7bda minor 2025-05-26 16:44:40 -07:00
Mittal, Ketan 7317d4d139 minor 2025-05-26 16:44:28 -07:00
Mittal, Ketan e9e684599f Merge branch 'plbound' of https://github.com/mfem/mfem into plbound 2025-05-26 14:12:44 -07:00
Mittal, Ketan 6c994fea99 minor 2025-05-26 14:12:31 -07:00
Gabriel Pinochet-Soto 3b05995fd1 Update some tests 2025-05-26 08:36:18 -07:00
Gabriel Pinochet-Soto 5e99ffc9a3 Relabel PC enum, other typos 2025-05-24 22:23:44 -07:00
Gabriel Pinochet-Soto bcbb24dce0 Remove redundant LEGACYFULL option 2025-05-24 19:06:51 -07:00
Gabriel Pinochet-Soto 797113ff71 Remove MG for HCurl 2025-05-24 18:53:44 -07:00
Gabriel Pinochet-Soto 41af83b10c Remove elast from miniapp 2025-05-24 18:42:22 -07:00
Gabriel Pinochet-Soto 4da2ea6f08 Remove abs elasticity integrators from source code 2025-05-24 18:41:43 -07:00
Gabriel Pinochet-Soto 9eb0f5c0c3 Merge branch 'master' of github.com:mfem/mfem into dev/abs-diag-smoothers 2025-05-24 16:06:51 -07:00
Ketan Mittal 4a1a5dfa55 Merge branch 'master' into plbound 2025-05-23 15:58:16 -07:00
Mittal, Ketan 59edd7255c separate out PLBound from gridfunc.hpp 2025-05-23 15:56:46 -07:00
Mittal, Ketan 6d01e152de reviewer comments 2025-05-23 12:26:06 -07:00
Vladimir Z Tomov 3e23785a13 Removed -vis from shifted/diffusion sample runs. 2025-05-23 11:50:28 -07:00
Will Pazner 52a0337f5e Adjust LOR miniapp sample runs 2025-05-23 10:56:24 -07:00
Will Pazner 0e22b182a6 Rename MultUnsigned to AbsMult in restriction classes
Deprecate 'MultUnsigned' and related functions
2025-05-22 10:49:28 -07:00
dylan-copeland f021091e9e Update guidelines on miniapp sample run testing. 2025-05-22 10:43:48 -07:00
dylan-copeland 21b592778a Remove device sample runs for nurbs_ex24. 2025-05-22 10:27:12 -07:00
dylan-copeland c3233944ad Exclude device sample runs for nurbs_ex24. 2025-05-22 09:52:36 -07:00
Justin Laughlin 49eb2715ba typos 2025-05-21 18:26:38 -07:00
dylan-copeland dd097f2cf5 Clean up output file. 2025-05-21 18:06:53 -07:00
dylan-copeland a8eba4053f Speed up sample runs for nurbs_ex24. 2025-05-21 18:05:30 -07:00
Justin Laughlin 5d3be16590 Fix check for empty nodes/weights 2025-05-21 17:05:17 -07:00
dylan-copeland 2df1b13811 Fixing some miniapp sample runs. 2025-05-21 17:04:00 -07:00
Justin Laughlin 899a2fc7cb Fix typos, improve documentation of new nurbs meshes, add size != 0 check in unit test 2025-05-21 13:55:03 -07:00
Ketan MittalandWill Pazner bd0fa51539 Update fem/pgridfunc.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-21 13:40:59 -07:00
Ketan MittalandWill Pazner b151c909f3 Update miniapps/tools/gridfunction-bounds.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-21 13:40:29 -07:00
Ketan MittalandWill Pazner ce7f94ec1f Update miniapps/tools/gridfunction-bounds.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-21 13:40:18 -07:00
Ketan MittalandWill Pazner ee6b9fdc2f Update miniapps/meshing/mesh-bounding-boxes.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-21 13:40:06 -07:00
Justin Laughlin c418868c83 Fix typo 2025-05-21 11:24:24 -07:00
Mark L. Stowell 7a0344a6bb Merge branch 'master' into mesh-transform-dev 2025-05-21 10:19:18 -07:00
Hugh Carson 1d28cfe699 Address Feedback
- Use IsDGSpace()
- Rewrap comments at 80 characters
2025-05-21 11:18:32 -04:00
Justin Laughlin 51812480bd Merge branch 'master' into fix-nurbsext-constructor 2025-05-20 15:36:39 -07:00
Justin Laughlin 61cc19ca22 One final cleanup 2025-05-20 15:34:57 -07:00
Justin Laughlin 5e48080f3d Minor cleanup/comments 2025-05-20 15:24:42 -07:00
Justin Laughlin af73851cb2 Comment 2025-05-20 15:13:28 -07:00
Justin Laughlin 338e4288ca Add some comments and update nurbs getters 2025-05-20 15:04:58 -07:00
Justin Laughlin dca4cd510a Add inverse map rpkv_to_ukv for efficiency 2025-05-20 13:16:25 -07:00
Justin Laughlin 2b23f35ec7 Copy miniapps/nurbs/meshes with cmake 2025-05-20 12:48:26 -07:00
Justin Laughlin ea569c5806 Add documentation and fix name 2025-05-20 11:20:34 -07:00
Hugh Carson 5957053d85 Update CHANGELOG 2025-05-20 12:11:31 -04:00
Hugh Carson 4ba8a2e148 Move Nodes construction into separate helper method, to allow building communication pattern first in ParMesh
- Silence unused variable warning in non-debug builds
2025-05-20 12:11:31 -04:00
Hugh Carson e494dc8255 Fix warning about missing (void*) 2025-05-20 12:11:31 -04:00
Hugh Carson 9fec24c86c Simplify linear algebra and add support for byNODES ordering of the Nodes vector 2025-05-20 12:11:31 -04:00
Hugh Carson 664d0a543a Add no-op tests, and fall through 2025-05-20 12:11:31 -04:00
Hugh Carson 20c3c30c87 Clean up printing, and generate quadratic and cubic tests 2025-05-20 12:11:31 -04:00
Hugh Carson 083c4845db Fix bug where origin of reference coordinates was being assumed as (0,0,0) 2025-05-20 12:11:31 -04:00
Hugh Carson a23c634e37 Map point_matrix back into ordering of Nodes() 2025-05-20 12:11:31 -04:00
Hugh Carson 556f6d72f5 Exploit that the map between reference spaces is always linear to assmble PointMatrix 2025-05-20 12:11:31 -04:00
Tzanio Kolev e2efc259b6 Merge branch 'master' into pref-mixed-serial 2025-05-19 16:51:16 -07:00
Tzanio Kolev 3ebb7a7b65 Merge branch 'master' into bugfix/l2pos_p0_pyramid 2025-05-19 16:51:07 -07:00
Veselin Dobrev 02136f8f5b In the unit test test_fe_pos.cpp, add a check for positivity of the
basis functions.
2025-05-19 12:25:21 -07:00
Tzanio Kolev b1468c14fd Merge pull request #4862 from mfem/dev/abs-diag-smoothers-mods
Additional proposed modification for PR #4769 (`dev/abs-diag-smoothers`)
2025-05-18 10:32:17 -07:00
Justin Laughlin d3281a8a86 Address some comments from Dylan - update path on nurbs test 2025-05-16 22:12:17 -07:00
Justin Laughlin a7d59d35e0 Fix pkv_map in GetEdgeToUniqueKnotvector 2025-05-16 21:39:50 -07:00
Justin Laughlin 70680d6187 Add more nurbs meshes to test with 2025-05-16 20:04:01 -07:00
Justin Laughlin 948462da6e minor cleanup 2025-05-16 18:07:12 -07:00
Justin Laughlin fddefa7838 Update GetEdgeToUniqueKnotvector - should handle edge cases better 2025-05-16 18:04:21 -07:00
Veselin Dobrev 62a01ee670 Re-format the sample runs in miniapps/diag-smoothers so that they follow the
formatting used in other places.
2025-05-16 16:54:53 -07:00
Veselin Dobrev e23768f5f7 Additional proposed modification for PR #4769 (dev/abs-diag-smoothers) 2025-05-16 16:13:36 -07:00
Justin Laughlin 53d4f78fdb Merge branch 'master' into fix-nurbsext-constructor 2025-05-14 18:57:40 -07:00
Justin Laughlin eeb71eee37 Add test 2025-05-14 18:10:30 -07:00
Justin Laughlin 3630a8f8a1 Add getters for testing; minor fix/formatting 2025-05-14 17:01:03 -07:00
Justin Laughlin 048904b731 Cleanup/formatting + implement Dylan's comments 2025-05-14 14:31:26 -07:00
Justin Laughlin 2496b33699 Fix Mesh::GetEdgeToUniqueKnotvector so it works for 1d 2025-05-14 11:39:04 -07:00
Dylan Copeland 1ff8b6811d Empty line 2025-05-09 11:03:09 -07:00
Dylan Copeland cf269700a8 Enable and add sample runs for p-refinement on serial mixed meshes. 2025-05-09 10:56:46 -07:00
Stowell, Mark L. 37adfbc405 Fixing memory leaks in positive basis unit tests 2025-05-07 14:14:29 -07:00
Mark L. Stowell cb0c205bd1 Merge branch 'master' into mesh-transform-dev 2025-05-07 13:58:59 -07:00
Stowell, Mark L. 2ed6fdc85a Cleaning up compiler warnings 2025-05-07 13:12:53 -07:00
Stowell, Mark L. 0a142864e9 Merge branch 'bugfix/l2pos_p0_pyramid' of github.com:mfem/mfem into bugfix/l2pos_p0_pyramid 2025-05-07 12:54:12 -07:00
Stowell, Mark L. f975c36e49 Adding new unit test to CMakeList.txt 2025-05-07 12:53:55 -07:00
Mark L. Stowell 471bc1f10d Merge branch 'master' into bugfix/l2pos_p0_pyramid 2025-05-07 11:46:56 -07:00
Stowell, Mark L. 8f52418e5c Adding basic unit tests for positive basis functions 2025-05-07 11:46:14 -07:00
Stowell, Mark L. 41a095e972 Fixing typo in unit test comment 2025-05-07 11:45:09 -07:00
Stowell, Mark L. effc07cdbf Fixing basis function computations for order=0 2025-05-07 11:44:45 -07:00
Justin Laughlin 15b35a01ba Merge branch 'master' into fix-nurbsext-constructor 2025-05-06 10:45:29 -07:00
Stowell, Mark L. 46ac9d937f Adding p=0 special case to L2Pos_PyramidElement 2025-05-05 18:02:28 -07:00
Justin Laughlin ff746a8af6 Remove some getters that are unnecessary for this PR 2025-05-05 14:47:13 -07:00
Tzanio Kolev 41ea219782 Merge branch 'master' into plbound 2025-05-03 13:41:55 -07:00
Veselin Dobrev b54ee3537f In a few places, use std::fabs instead of std::abs or just abs 2025-05-02 10:21:04 -07:00
camierjs 9afef578d5 Merge branch 'master' into hpcftools/flowSolver-gpu 2025-05-02 09:59:44 -07:00
Gabriel Pinochet-Soto d46b421417 !!useAbs 2025-05-01 17:28:39 -07:00
Gabriel Pinochet-Soto 1d7029c5d6 Add Abs to DofToQuad, needs testing 2025-05-01 17:12:14 -07:00
Gabriel Pinochet-Soto 5596d38532 Docstring AbsPhyDer 2025-05-01 17:05:14 -07:00
Gabriel Pinochet-Soto 389580efef Replace mfem_error with MFEM_ABORT 2025-05-01 16:53:12 -07:00
Gabriel Pinochet-SotoandWill Pazner 2029636109 Update fem/bilinearform_ext.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-01 16:52:22 -07:00
Gabriel Pinochet-SotoandWill Pazner 1ca38f826c Update fem/bilinearform_ext.cpp
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-01 16:49:46 -07:00
Gabriel Pinochet-SotoandWill Pazner 4745e062f2 Docstring Array<T>::Abs
Co-authored-by: Will Pazner <11493037+pazner@users.noreply.github.com>
2025-05-01 09:56:57 -07:00
Tzanio Kolev a631ab7e77 Merge branch 'master' into dev/abs-diag-smoothers 2025-05-01 09:46:00 -07:00
Tzanio Kolev 30f3e42232 Merge branch 'master' into fix-nurbsext-constructor 2025-04-30 10:49:45 -07:00
Justin Laughlin 4d92694fc5 Update GetNURBSPatches 2025-04-29 13:41:11 -07:00
Justin Laughlin a4214d22f4 fix typo 2025-04-28 18:40:02 -07:00
Justin Laughlin ce1576411c Cleanup demo script 2025-04-28 18:31:22 -07:00
Justin Laughlin 1c4f617fd5 Cleaup 2025-04-28 18:30:14 -07:00
Justin Laughlin b234475774 minor cleanup 2025-04-28 18:25:18 -07:00
Justin Laughlin 5da1d7ddf3 Update edge_to_knot (renamed edge_to_ukv) generator so it maps to unique knotvector indices 2025-04-28 18:18:18 -07:00
Justin Laughlin cff3c6cb6f Cleanup Mesh::LoadPatchTopo and Mesh::GetEdgeToKnotMapping 2025-04-28 16:32:56 -07:00
Justin Laughlin 7ef863b731 Add new algorithm to compute edge_to_knot map 2025-04-28 15:42:27 -07:00
Tzanio Kolev 09b31f0526 Merge branch 'master' into plbound 2025-04-26 12:32:38 -07:00
Gabriel Pinochet-Soto 5044d9cd45 Remove *Abs* functions in operator.xpp and related 2025-04-25 12:35:02 -07:00
Gabriel Pinochet-Soto 2edddb700e Remove unused functions in bilininteg.xpp 2025-04-25 12:21:08 -07:00
Gabriel Pinochet-Soto 1d79ab00ba Remove todo; cf. 3b49d70 2025-04-25 12:03:21 -07:00
Gabriel Pinochet-Soto 85e08b67a0 Update CHANGELOG 2025-04-25 11:55:04 -07:00
Gabriel Pinochet-Soto c513bb1276 Merge branch 'master' of github.com:mfem/mfem into dev/abs-diag-smoothers 2025-04-25 11:00:03 -07:00
Justin Laughlin 7559524573 separate GetEdgeToKnotMapping. Updating constructor WIP 2025-04-24 22:46:33 -07:00
Justin Laughlin 7ac34aab22 More testing - turns out mapping is more complicated because it is edges to unique knotvectors 2025-04-24 21:30:55 -07:00
Justin Laughlin 17edacb630 Fix orientation in edge_to_knot map of NURBSExtension constructor 2025-04-24 18:36:50 -07:00
Justin Laughlin 703ba47151 demo 2025-04-24 18:06:42 -07:00
Justin Laughlin 57caab145a Getters for NURBS patch data 2025-04-24 17:08:54 -07:00
Veselin Dobrev b294248b06 Update .gitignore 2025-04-22 13:08:44 -07:00
Stowell, Mark L. 83ca977d71 Adding an affine transformation option to mesh-explorer 2025-04-21 16:38:16 -07:00
Stowell, Mark L. 6739574668 Adding an affine mesh transformation coefficient 2025-04-21 16:37:54 -07:00
Ketan Mittal 9f153f9fcb Merge branch 'master' into plbound 2025-04-20 18:59:08 +12:00
Veselin Dobrev 00d35316b9 Merge branch 'master' into dev/abs-diag-smoothers 2025-04-18 13:43:42 -07:00
Mittal, Ketan 84a3fe000b fix gitignore 2025-04-18 13:32:57 -07:00
Stowell, Mark L. 7354e1ce6c Adding option to increase the space dimension of the mesh 2025-04-18 12:00:58 -07:00
Mittal, Ketan d5089996cc fix AddVertex usage 2025-04-18 11:55:13 -07:00
Mittal, Ketan 9787ad0d3b minor 2025-04-18 11:37:31 -07:00
Mittal, Ketan 26fb49960e add miniapp description 2025-04-18 11:12:32 -07:00
Mittal, Ketan 5cb2c82d59 fix makefile 2025-04-18 11:03:33 -07:00
Mittal, Ketan 9e7f8ce838 minor 2025-04-17 15:38:39 -07:00
Veselin Dobrev 41e4360d2e Fix the CUDA build and the out-of-source build with GNU make 2025-04-17 13:43:37 -07:00
Mittal, Ketan 263dd0f019 fix make clean 2025-04-17 12:11:02 -07:00
Mittal, Ketan 433f9a4c51 minor 2025-04-17 11:36:37 -07:00
Mittal, Ketan 08856158ce fix for some static constexpr definitions in hpp 2025-04-17 11:18:20 -07:00
Veselin Dobrev b21bf9a2d9 Merge branch 'master' into dev/abs-diag-smoothers 2025-04-16 22:22:56 -07:00
Veselin Dobrev 8d705f4230 Various formatting edits and other small tweaks 2025-04-16 22:21:33 -07:00
Mittal, Ketan 0a6c72c52d doxygen fix 2025-04-16 16:12:36 -07:00
Mittal, Ketan 8cefee8799 fix ParFESpace definition 2025-04-16 13:52:40 -07:00
Mittal, Ketan e9b631116f fix typo 2025-04-16 13:41:00 -07:00
Mittal, Ketan 6468880b2a minor 2025-04-16 12:58:07 -07:00
Mittal, Ketan 89a0e08f29 remove some unused methods 2025-04-16 12:57:50 -07:00
Mittal, Ketan 7471a22505 resolve conflicts 2025-04-16 12:56:40 -07:00
Mittal, Ketan 779ce337f4 miniapps 2025-04-16 12:45:55 -07:00
Mittal, Ketan 54b24da610 missing files 2025-04-16 12:45:30 -07:00
Mittal, Ketan 1a332939a0 initial capability 2025-04-16 12:45:11 -07:00
Hugh Carson 2af3577482 Merge branch 'master' into hughcars/array-back-inserter 2025-04-16 11:09:26 -04:00
Veselin Dobrev bbd26e1835 In miniapps/diag-smoothers, fix the CMake tests and adjust mesh refinements 2025-04-14 16:41:24 -07:00
Veselin Dobrev e8842c506a Fix the build in miniapps/smoothers 2025-04-14 14:54:25 -07:00
Veselin Dobrev 214313291b Merge branch 'master' into dev/abs-diag-smoothers
Fixed conflicts:
  CHANGELOG
  fem/bilinearform_ext.cpp
  fem/bilinearform_ext.hpp
2025-04-14 13:56:38 -07:00
Gabriel Pinochet-Soto cfbaf5a6bf Header renaming 2025-03-29 11:02:27 -07:00
Gabriel Pinochet-Soto 2e2b8faba5 Modify abort msg in MMA::MMASubSvanberg 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto bf9ce2c6a4 Update gitignore and CHANGELOG 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 9f858378ca Add Examples 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto c2b948a036 AbsMult for Mass Integrs 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 0771f904c0 AbsMult for Diffusion 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 3b49d70f35 AbsMult for ElasticityInteg 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 7c077e656d CurlCurl kernels AbsApply 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto b9f146b46f Add AbsMult to QuadInterp 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 07438814ce Add interface in pfespace.hpp 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 328c914481 Add AbsMult for restriction operators; address code duplication comment 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 1766007d8a Add AbsMult interface to Integrators 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 6311548ac6 Use constexpr on (Abs)Mult cases 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 9d84c17e0b Add AbsMult to base class Operator 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 23c1fc6452 Add Hypre AbsMult 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 3117d0e8ab Implement Mult/AbsMult for DenseMatrix 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto a9b720b79d Update Mult Kernels
- Observation: This could be replaced with a lambda function of the
type `useAbs ? [](TA a) { return std::abs(a); } : ...`
2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 3fe878efaa Ommisions...
- Ommit hypre_parcsr.xpp implementation of L(p,q)
- Ommit solvers.xpp implementation of L(p,q)
- Ommit tests implementation of L(p,q)
2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 4c0def024c Monitor SLI (akin to CG) 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto bf7c26ebf9 Vector::Abs 2025-03-28 22:13:22 -07:00
Gabriel Pinochet-Soto 73014e34c5 Add Array<T>::Abs()
- static assert of arithmetic type of T
2025-03-28 22:13:22 -07:00
Hugh Carson fb5e610ca5 Add support and test for back_inserter along with some more stl-style interactions 2025-02-24 10:40:07 -05:00
camierjs 9ecc414c62 dot reduced tests 2024-12-04 18:25:05 -08:00
camierjs 263b9d32c1 Merge branch 'hpcftools/flowSolver' 2024-12-04 11:59:05 -08:00
Mathias Rainer Schmidt 74e4ad3e2c - updated flow solver
- added comments to Blf and Lf contributions
- split setup and step into vel, auxiliary and pressure part
2024-11-25 11:04:30 -08:00
camierjs 79039e0f6f Switched to PA 2024-11-21 10:52:39 -08:00
Mathias Rainer Schmidt cf9fcd8dde Merge remote-tracking branch 'origin/master' into hpcftools/flowSolver 2024-11-14 13:52:27 -08:00
camierjs c857fde13b Merge branch 'hpcftools/flowSolver' 2024-11-01 15:59:50 -07:00
Mathias Rainer Schmidt fa8617ada3 - added partial assembly option 2024-11-01 13:20:29 -07:00
camierjs c06cbb69d5 Setup and cleanup 2024-10-30 11:37:00 -07:00
Mathias Rainer Schmidt f7e5db2cea - added ortho solver to phi field 2024-10-24 16:06:37 -07:00
Mathias Rainer Schmidt 60c11776b6 - added executable 2024-10-21 15:57:23 -07:00
Mathias Rainer Schmidt 6238f8ca76 - update solution 2024-10-16 16:00:08 -07:00
Mathias Rainer Schmidt 6a256db9aa - added linear solvers to step 2024-10-16 15:56:46 -07:00
Mathias Rainer Schmidt e0fb9658ca - added linear form integrators 2024-10-15 17:30:09 -07:00
Mathias Rainer Schmidt a1089efac3 - added BilinearForms 2024-10-15 13:46:36 -07:00
Mathias Rainer Schmidt 83f7f769dc - inital flow solver commit 2024-10-15 12:44:25 -07:00
176 changed files with 16809 additions and 1897 deletions
+42 -6
View File
@@ -58,6 +58,7 @@ jobs:
build-system: [make, cmake]
hypre-target: [int32]
precision: [fp64]
enzyme: [false]
exclude:
- os: ubuntu-latest
build-system: cmake
@@ -80,15 +81,17 @@ jobs:
codecov: YES
- os: ubuntu-latest
target: dbg
config-opts: 'CPPFLAGS+=-Og'
config-opts: "CPPFLAGS+=-Og"
- os: macos-latest
codecov: NO
- os: windows-latest
codecov: NO
# config-opts: '-G "Ninja Multi-Config"'
- os: windows-latest
target: opt
mpi: par
config-opts: '-DBUILD_SHARED_LIBS=ON'
config-opts: "-DBUILD_SHARED_LIBS=ON"
# config-opts: '-DBUILD_SHARED_LIBS=ON -G "Ninja Multi-Config"'
- os: ubuntu-latest
target: opt
codecov: NO
@@ -96,7 +99,7 @@ jobs:
build-system: cmake
hypre-target: int32
precision: fp64
config-opts: '-DCMAKE_INSTALL_PREFIX=../cmake-install'
config-opts: "-DCMAKE_INSTALL_PREFIX=../cmake-install"
# This option can be set to pass additional configuration options to
# the MFEM configuration command.
# config-opts: '-DCMAKE_VERBOSE_MAKEFILE=ON'
@@ -121,7 +124,17 @@ jobs:
build-system: make
hypre-target: int32
precision: fp32
name: ${{ matrix.os }}-${{ matrix.build-system }}-${{ matrix.target }}-${{ matrix.mpi }}-${{ matrix.hypre-target }}-${{ matrix.precision }}
- os: macos-latest
target: opt
codecov: NO
mpi: par
build-system: make
hypre-target: int32
precision: fp64
enzyme: true
config-opts: MFEM_USE_ENZYME=YES ENZYME_DIR=$(brew --prefix enzyme)
name: ${{ matrix.os }}-${{ matrix.build-system }}-${{ matrix.target }}-${{ matrix.mpi }}-${{ matrix.hypre-target }}-${{ matrix.precision }}${{ matrix.enzyme && '-enzyme' || '' }}
runs-on: ${{ matrix.os }}
@@ -131,8 +144,8 @@ jobs:
if: matrix.os == 'ubuntu-latest'
uses: easimon/maximize-build-space@v8
with:
overprovision-lvm: 'true'
remove-android: 'true'
overprovision-lvm: "true"
remove-android: "true"
# Checkout MFEM in "mfem" subdirectory. Final path:
# /home/runner/work/mfem/mfem/mfem
@@ -144,6 +157,17 @@ jobs:
# Fetch the complete history for codecov to access commits ID
fetch-depth: 0
- name: Windows environment - PowerShell [debug]
if: matrix.os == 'windows-latest'
run: |
ls env: | fl
- name: Windows environment - Bash [debug]
if: matrix.os == 'windows-latest'
run: |
env
shell: bash
- name: Xcode version setup (MacOS)
if: matrix.os == 'macos-latest'
run: |
@@ -258,6 +282,18 @@ jobs:
run: |
vcpkg install metis-mfem --triplet=x64-windows-static --overlay-ports=${{ env.MFEM_TOP_DIR }}/config/vcpkg/ports
# It's usually fine to build the above TPLs with a different compiler.
#
- name: install Enzyme (macOS w/ Enzyme)
if: matrix.enzyme && matrix.os == 'macos-latest'
run: |
export HOMEBREW_NO_INSTALL_CLEANUP=1
brew update
brew install llvm@19 enzyme
echo "LLVM_PREFIX=$(brew --prefix llvm@19)" >> $GITHUB_ENV
echo "OMPI_CC=$(brew --prefix llvm@19)/bin/clang" >> $GITHUB_ENV
echo "OMPI_CXX=$(brew --prefix llvm@19)/bin/clang++" >> $GITHUB_ENV
# MFEM build and test
- name: build
uses: mfem/github-actions/build-mfem@v2.5
+1 -1
View File
@@ -49,7 +49,7 @@ jobs:
library-only: false
config-options:
CXX="clang++-18"
CXXFLAGS="-g -O1 -std=c++11
CXXFLAGS="-g -O1 -std=c++17
-fsanitize=address
-fno-omit-frame-pointer
-fsanitize-address-use-after-scope"
+13
View File
@@ -19,6 +19,9 @@ CMakeFiles/
# Clangd server cache
*.cache*
# VSCode configuration
/.vscode/
# Backup files
*~
@@ -201,6 +204,9 @@ examples/superlu/sol.*
miniapps/adjoint/cvsRoberts_ASAi_dns
miniapps/adjoint/adjoint_advection_diffusion
miniapps/dfem/dfem-minimal-surface
miniapps/dfem/dfem-minimal-surface-output
miniapps/electromagnetics/volta
miniapps/electromagnetics/tesla
miniapps/electromagnetics/maxwell
@@ -229,6 +235,7 @@ miniapps/meshing/fit-node-position
miniapps/meshing/trimmer
miniapps/meshing/reflector
miniapps/meshing/ref321
miniapps/meshing/mesh-bounding-boxes
miniapps/meshing/mesh-optimizer
miniapps/meshing/pmesh-optimizer
miniapps/meshing/pmesh-fitting
@@ -259,6 +266,8 @@ miniapps/meshing/mesh.*
miniapps/meshing/order.*
miniapps/meshing/sol.*
miniapps/meshing/refined.mesh
miniapps/meshing/bounding-box*
miniapps/meshing/jacobian-determinant*
miniapps/mtop/parheat
miniapps/mtop/ParHeat*
@@ -333,6 +342,7 @@ miniapps/shifted/lsf_integral
miniapps/tools/display-basis
miniapps/tools/load-dc
miniapps/tools/convert-dc
miniapps/tools/gridfunction-bounds
miniapps/tools/lor-transfer
miniapps/tools/plor-transfer
miniapps/tools/get-values
@@ -399,6 +409,9 @@ miniapps/spde/ParaView
miniapps/tribol/contact-patch-test
miniapps/diag-smoothers/abs-l1-jacobi
miniapps/diag-smoothers/mg-abs-l1-jacobi
# Unit test binary and outputs
tests/unit/output_meshes
tests/unit/unit_tests
+39 -2
View File
@@ -10,15 +10,52 @@
Version 4.8.1 (development)
===========================
- Added support for variational resampling of H1 vector fields to ParMoonolith
integration.
Starting with this version, MFEM requires a C++17 compiler.
Discretization improvements
---------------------------
- Introduced dFEM: a new MFEM capability for Automatic Differentiation (AD) of
nonlinear finite element operators, based on Enzyme or dual numbers AD at
quadrature points. These features are part of the new mfem::future namespace
and some of the API can change in the future. See the new dFEM minimal surface
miniapp in the miniapps/dfem/ directory for illustration of dFEM's use.
- Using Enzyme for AD in MFEM is tested with clang v19 and requires clang/LLVM
built with plugin support. See INSTALL for more details.
- In the ParMoonolith integration, added support for variational resampling of
H1 vector fields.
Meshing improvements
--------------------
- Added support for higher order meshes in Mesh::MakeSimplicial and
ParMesh::MakeSimplicial.
GPU computing
-------------
- The function Vector::SetSubVector(const Array<int> &, const real_t) now
executes on device if either the vector or the array have the device flag
set. This is most often used for setting constant essential boundary
conditions. A new function Vector::SetSubVectorHost has been added in cases
where host execution is always needed (e.g. when the DOFs array is small).
New and updated examples and miniapps
-------------------------------------
- Added miniapps to demonstrate an implementation of the absolute-value
L(1)-Jacobi preconditioners in partially assembled operators. This includes
Multigrid wrapper to demonstrate the effectiveness of these Jacobi-type
operators as smoothers.
These miniapps can be found in `miniapps/diag-smoothers`.
API changes:
-----------
- mfem::internal::tensor and mfem::internal::dual have been moved to
mfem::future::tensor and mfem::future::dual.
- API addition: in class `Operator`, added virtual functions: `AbsMult`, and
`AbsMultTranspose`; in class `Vector`, added `Abs` and `Pow`.
Version 4.8, released on Apr 9, 2025
====================================
+27 -6
View File
@@ -18,8 +18,8 @@ message(STATUS "CMake version: ${CMAKE_VERSION}")
set(USER_CONFIG "${CMAKE_CURRENT_SOURCE_DIR}/config/user.cmake" CACHE PATH
"Path to optional user configuration file.")
# Require C++11 and disable compiler-specific extensions
set(CMAKE_CXX_STANDARD 11 CACHE STRING "C++ standard to use.")
# Require C++17 and disable compiler-specific extensions
set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard to use.")
set(CMAKE_CXX_STANDARD_REQUIRED ON CACHE BOOL
"Force the use of the chosen C++ standard.")
set(CMAKE_CXX_EXTENSIONS OFF CACHE BOOL "Enable C++ standard extensions.")
@@ -133,7 +133,6 @@ if (MFEM_USE_CUDA)
if (NOT CMAKE_CUDA_HOST_COMPILER)
set(CMAKE_CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
endif()
set(CUDA_FLAGS "--expt-extended-lambda")
if (CMAKE_VERSION VERSION_LESS 3.18.0)
set(CUDA_FLAGS "-arch=${CUDA_ARCH} ${CUDA_FLAGS}")
elseif (NOT CMAKE_CUDA_ARCHITECTURES)
@@ -148,6 +147,20 @@ if (MFEM_USE_CUDA)
endif()
message(STATUS "Using CUDA architecture: ${CUDA_ARCH}")
enable_language(CUDA)
if (CMAKE_VERSION VERSION_LESS 3.18.0)
# backup try to detect if this is clang or nvcc
if(CMAKE_CUDA_COMPILER MATCHES "nvcc$")
# nvcc
set(MFEM_CUDA_COMPILER_IS_NVCC ON)
set(CUDA_FLAGS "${CUDA_FLAGS} --expt-extended-lambda --expt-relaxed-constexpr")
endif()
else()
if (CMAKE_CUDA_COMPILER_ID STREQUAL "NVIDIA")
# nvcc
set(MFEM_CUDA_COMPILER_IS_NVCC ON)
set(CUDA_FLAGS "${CUDA_FLAGS} --expt-extended-lambda --expt-relaxed-constexpr")
endif()
endif()
set(CMAKE_CUDA_STANDARD ${CMAKE_CXX_STANDARD} CACHE STRING
"CUDA standard to use.")
set(CMAKE_CUDA_STANDARD_REQUIRED ON CACHE BOOL
@@ -256,7 +269,11 @@ if (MFEM_USE_OPENMP OR MFEM_USE_LEGACY_OPENMP)
if (OPENMP_FOUND)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
if (MFEM_USE_CUDA)
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Xcompiler=${OpenMP_CXX_FLAGS}")
if(MFEM_CUDA_COMPILER_IS_NVCC)
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Xcompiler=${OpenMP_CXX_FLAGS}")
else()
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
endif()
endif()
endif()
@@ -532,9 +549,10 @@ if (MFEM_USE_TRIBOL)
endif()
endif()
# Enzyme
if (MFEM_USE_ENZYME)
find_package(ENZYME REQUIRED)
find_package(Enzyme REQUIRED HINTS ${ENZYME_DIR})
message(STATUS "Enzyme found in ${ENZYME_DIR}.")
set(ENZYME_INCLUDE_DIRS ${ENZYME_DIR}/include)
endif()
# MFEM_TIMER_TYPE
@@ -686,6 +704,9 @@ if (MFEM_USE_MPI)
target_link_libraries(mfem PUBLIC ${MPI_CXX_LINK_FLAGS})
endif()
endif()
if (MFEM_USE_ENZYME)
target_link_libraries(mfem PUBLIC ClangEnzymeFlags)
endif()
set_target_properties(mfem PROPERTIES VERSION "${mfem_VERSION}")
set_target_properties(mfem PROPERTIES SOVERSION "${mfem_VERSION}")
+5 -1
View File
@@ -120,6 +120,7 @@ The MFEM source code has the following structure:
| └── superlu
├── fem
│ ├── ceed
│ ├── dfem
│ ├── eltrans
│ ├── fe
│ ├── gslib
@@ -138,6 +139,7 @@ The MFEM source code has the following structure:
│ ├── adjoint
│ ├── autodiff
│ ├── common
│ ├── dfem
│ ├── dpg
│ ├── electromagnetics
│ ├── gslib
@@ -549,6 +551,8 @@ Before a PR can be merged, it should satisfy the following:
- [ ] Add a short description of the example in the "Extensive Examples" section of `features.md`.
- [ ] New miniapps:
- [ ] All sample runs at the top of the miniapp source file work.
- [ ] Add to internal testing repo, if sample runs should be included in nightly tests [internally](#tests-at-llnl).
- [ ] Exclude long sample runs from automated testing, with `* ` (one space) before the command.
- [ ] Update top-level `makefile` and `makefile` in corresponding miniapp directory.
- [ ] Add the miniapp binary and any files generated by it to the top-level `.gitignore` file.
- [ ] Update CMake build system:
@@ -743,7 +747,7 @@ and debug build is performed with a simple run of `ex1` to verify the executable
- We mirror the `master` and `next` branches internally (to `gh-master` and
`gh-next`) and run longer nightly tests via cron. On the weekends, a more
extensive test is run which extracts and executes all the different sample
runs from each example.
runs from each example and most miniapps.
- We also mirror PRs on the LLNL GitLab instance. PR mirroring can only be
triggered by _LLNL developers_, but test status is publicly available. Only
+79 -8
View File
@@ -263,7 +263,7 @@ See the configuration file config/defaults.mk for the default settings.
Compilers:
CXX - C++ compiler, serial build
MPICXX - MPI C++ compiler, parallel build
CUDA_CXX - The CUDA compiler, 'nvcc'
CUDA_CXX - The CUDA compiler, 'nvcc' or 'clang++'
Compiler options:
OPTIM_FLAGS - Options for optimized build
@@ -608,11 +608,12 @@ MFEM_USE_TRIBOL = YES/NO
MFEM_USE_ENZYME = YES/NO
Enables automatic differentiation support through the LLVM plugin Enzyme.
This requires the compiler to be set to clang (>=14.0.0). We also advise to
use the link time optimization (LTO) plugin, to enable functions that you
define over multiple files (compilation units) and want to be differentiated
automatically, to work. This requires to also use LLVM/LLD for linking.
Recommended options are in config/defaults.mk.
This requires the compiler to be set to clang (>=14.0.0). We also advise the
use of the link time optimization (LTO) plugin, so functions defined over
multiple files (compilation units) can be differentiated automatically. This
requires to also use LLVM/LLD for linking. The recommended options are in
config/defaults.mk. For more detailed instructions, see the section "Specific
options for Enzyme" below.
MFEM_BUILD_TAG = (any value)
An optional tag to characterize the build. Exported to config/config.mk.
@@ -835,7 +836,7 @@ The specific libraries and their options are:
- CUDA (optional), used when MFEM_USE_CUDA = YES.
URL: https://developer.nvidia.com/cuda-toolkit
Options: CUDA_CXX, CUDA_ARCH, CUDA_OPT, CUDA_LIB.
Options: CUDA_CXX, CUDA_ARCH, CUDA_OPT, CUDA_LIB, CUDA_DIR (when CUDA_CXX=clang++).
Versions: CUDA >= 10.1.168.
- HIP (optional), used when MFEM_USE_HIP = YES.
@@ -911,7 +912,7 @@ The specific libraries and their options are:
- Enzyme, used when MFEM_USE_ENZYME = YES. Requires LLVM/Clang >= 14.0.0.
URL: https://github.com/EnzymeAD/Enzyme
Options: ENZYME_DIR, ENZYME_OPT, ENZYME_LIB.
Versions: Enzyme >= v0.0.33.
Versions: Enzyme >= v0.0.176.
Building with CMake
@@ -1190,3 +1191,73 @@ the older HIP C++ library build/linkage. To ensure proper build and linkage
check that `CMAKE_CXX_COMPILER` and `CMAKE_HIP_COMPILER` are set to the same
compiler. This is especially important when using an MPI compiler (for example
crayCC) where some linker flags may get dropped if these two are not identical.
Specific options for Enzyme
===========================
To work properly, MFEM and Enzyme need to use the same LLVM/Clang configuration.
For example, on macOS this can be done by using Homebrew: first install Enzyme,
which in turn installs LLVM as a dependency (as of May 2025, this is LLVM 19):
brew install enzyme
In order to ensure the correct compiler choice for the MFEM makefile build, set
CXX = $(shell brew --prefix llvm@19)/bin/clang++
in the user.mk file (adapted from config/defaults.mk, see the section "Building
with GNU make" above). With MPI, it is convenient to set
MPICXX = OMPI_CXX=$(CXX) mpicxx
for OpenMPI and
MPICXX = MPICH_CXX=$(CXX) mpicxx
for MPICH.
Additionally, the Enzyme directory needs to be set in user.mk as follows:
ENZYME_DIR = $(shell brew --prefix enzyme)
Specifically, a full build on a Mac can be tested by adding the following
user.mk file in the config/ directory
MFEM_USE_ENZYME = YES
ENZYME_DIR = $(shell brew --prefix enzyme)
LLVM_DIR = $(shell brew --prefix llvm@19)
CXX = $(LLVM_DIR)/bin/clang++
MFEM_USE_MPI = YES
MPICXX = OMPI_CXX=$(CXX) mpicxx
and running
make config
make -j
cd miniapps/dfem
make
./dfem-minimal-surface
On Linux systems, for example Ubuntu 24.04, use the package manager to install
the Enzyme dependencies
sudo apt install libclang-dev libzstd-dev llvm-dev clang
and then clone and build Enzyme
cd $HOME
git clone https://github.com/EnzymeAD/Enzyme.git
cd Enzyme/enzyme && mkdir build && cd build
CC=clang CXX=clang++ cmake .. -DLLVM_DIR=/usr/lib/llvm-18/lib/cmake -DCMAKE_INSTALL_PREFIX=$HOME/Enzyme/enzyme/build
make -j
make install
From here, one can proceed in the same way using the following user.mk settings
MFEM_USE_ENZYME = YES
ENZYME_DIR = $(HOME)/Enzyme/enzyme/build
CXX = clang++
MFEM_USE_MPI = YES
MPICXX = OMPI_CXX=$(CXX) mpicxx
On other Linux systems the LLVM packages may have different names, for example
on RHEL9, one needs to "sudo yum install llvm-devel libzstd clang-devel".
-27
View File
@@ -1,27 +0,0 @@
# Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
# at the Lawrence Livermore National Laboratory. All Rights reserved. See files
# LICENSE and NOTICE for details. LLNL-CODE-806117.
#
# This file is part of the MFEM library. For more information and source code
# availability visit https://mfem.org.
#
# MFEM is free software; you can redistribute it and/or modify it under the
# terms of the BSD-3 license. We welcome feedback and contributions, see file
# CONTRIBUTING.md for details.
message(STATUS "Looking for ENZYME ...")
message(STATUS " in ENZYME_DIR = ${ENZYME_DIR}")
# Make sure the directory and version combination works. Do nothing otherwise.
if(EXISTS "${ENZYME_DIR}/ClangEnzyme-${ENZYME_VERSION}.so")
message(STATUS "Found ENZYME: ${ENZYME_DIR}/ClangEnzyme-${ENZYME_VERSION}.so")
# Set ENZYME_FOUND
set(ENZYME_FOUND TRUE CACHE BOOL "ENZYME was found." FORCE)
# Set CXX flags to accommodate the Enzyme Clang plugin
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Xclang -load -Xclang ${ENZYME_DIR}/ClangEnzyme-${ENZYME_VERSION}.so -mllvm -enzyme-loose-types=1")
set(MFEM_USE_ENZYME YES)
else()
endif()
+2 -1
View File
@@ -86,8 +86,9 @@ if (HYPRE_FOUND AND HYPRE_USING_CUDA)
mfem_culib_set_libraries(CUSPARSE cusparse)
mfem_culib_set_libraries(CURAND curand)
mfem_culib_set_libraries(CUBLAS cublas)
mfem_culib_set_libraries(CUSOLVER cusolver)
list(APPEND HYPRE_LIBRARIES ${CUSPARSE_LIBRARIES} ${CURAND_LIBRARIES}
${CUBLAS_LIBRARIES})
${CUBLAS_LIBRARIES} ${CUSOLVER_LIBRARIES})
set(HYPRE_LIBRARIES ${HYPRE_LIBRARIES} CACHE STRING
"HYPRE libraries + dependencies." FORCE)
message(STATUS "Updated HYPRE_LIBRARIES: ${HYPRE_LIBRARIES}")
@@ -125,7 +125,9 @@ macro(add_mfem_miniapp MFEM_EXE_NAME)
if (MFEM_USE_CUDA)
set_source_files_properties(${MAIN_LIST} ${EXTRA_SOURCES_LIST}
PROPERTIES LANGUAGE CUDA)
list(TRANSFORM EXTRA_OPTIONS_LIST PREPEND "-Xcompiler=")
if (MFEM_CUDA_COMPILER_IS_NVCC)
list(TRANSFORM EXTRA_OPTIONS_LIST PREPEND "-Xcompiler=")
endif()
endif()
# Actually add the executable
+1 -1
View File
@@ -98,7 +98,7 @@ MFEM_MPIEXEC_NP = @MFEM_MPIEXEC_NP@
MFEM_MPI_NP = @MFEM_MPI_NP@
# The NVCC compiler cannot link with -x=cu
MFEM_LINK_FLAGS := $(filter-out -x=cu -xhip, $(MFEM_FLAGS))
MFEM_LINK_FLAGS := $(filter-out -x=cu -xcuda -xhip, $(MFEM_FLAGS))
# Optional extra configuration
@MFEM_CONFIG_EXTRA@
+2
View File
@@ -268,6 +268,8 @@ set(TRIBOL_DIR "${MFEM_DIR}/../tribol" CACHE PATH "Path to Tribol")
set(Tribol_REQUIRED_PACKAGES "Axom/core/mint/slam/slic" CACHE STRING
"Additional packages required by Tribol")
set(ENZYME_DIR "${MFEM_DIR}/../enzyme" CACHE PATH "Path to Enzyme")
set(BLAS_INCLUDE_DIRS "" CACHE STRING "Path to BLAS headers.")
set(BLAS_LIBRARIES "" CACHE STRING "The BLAS library.")
set(LAPACK_INCLUDE_DIRS "" CACHE STRING "Path to LAPACK headers.")
+34 -29
View File
@@ -24,7 +24,7 @@ EGREP_BIN = $(shell command -v egrep 2> /dev/null)
CXX = g++
MPICXX = mpicxx
BASE_FLAGS = -std=c++11
BASE_FLAGS = -std=c++17
OPTIM_FLAGS = -O3 $(BASE_FLAGS)
DEBUG_FLAGS = -g $(XCOMPILER)-Wall $(BASE_FLAGS)
@@ -43,12 +43,23 @@ SHARED = NO
# CUDA configuration options
#
# If you set MFEM_USE_ENZYME=YES, CUDA_CXX has to be configured to use cuda with
# clang as its host compiler.
# If you set MFEM_USE_ENZYME=YES, must use CUDA_CXX=clang++
CUDA_CXX = nvcc
CUDA_ARCH = sm_60
CUDA_FLAGS = -x=cu --expt-extended-lambda -arch=$(CUDA_ARCH)
# Prefixes for passing flags to the host compiler and linker when using CUDA_CXX
# Base CUDA install directory, only needed if building with clang+cuda:
# The default setting is:
# 1. If CUDA_HOME is defined and non-empty, use that.
# 2. If nvcc is in the path, use the directory two levels up from that.
# 3. Use /usr/local/cuda
CUDA_DIR = $(or $(CUDA_HOME),$(patsubst %/,%,$(dir \
$(patsubst %/,%,$(dir $(shell command -v nvcc))))),/usr/local/cuda)
# flags for clang+cuda
CLANG_CUDA_FLAGS = -xcuda --cuda-path=$(CUDA_DIR) --cuda-gpu-arch=$(CUDA_ARCH)
# flags for nvcc
NVCC_FLAGS = -x=cu --expt-extended-lambda --expt-relaxed-constexpr \
-arch=$(CUDA_ARCH)
# Prefixes for passing flags to the host compiler and linker when using
# CUDA_CXX=nvcc
CUDA_XCOMPILER = -Xcompiler=
CUDA_XLINKER = -Xlinker=
@@ -227,7 +238,7 @@ HYPRE_OPT = -I$(HYPRE_DIR)/include
HYPRE_LIB = -L$(HYPRE_DIR)/lib -lHYPRE
ifeq (YES,$(MFEM_USE_CUDA))
# This is only necessary when hypre is built with cuda:
HYPRE_LIB += -lcusparse -lcurand -lcublas
HYPRE_LIB += -lcusolver -lcusparse -lcurand -lcublas
endif
ifeq (YES,$(MFEM_USE_HIP))
# This is only necessary when hypre is built with hip:
@@ -242,7 +253,7 @@ ifeq ($(MFEM_USE_SUPERLU)$(MFEM_USE_STRUMPACK)$(MFEM_USE_MUMPS),NONONO)
METIS_OPT =
METIS_LIB = -L$(METIS_DIR) -lmetis
else
METIS_DIR = @MFEM_DIR@/../metis-5.0
METIS_DIR = @MFEM_DIR@/../metis-5.1.0
METIS_OPT = -I$(METIS_DIR)/include
METIS_LIB = -L$(METIS_DIR)/lib -lmetis
endif
@@ -511,6 +522,9 @@ GSLIB_LIB = -L$(GSLIB_DIR)/lib -lgs
# CUDA library configuration
CUDA_OPT =
CUDA_LIB = -lcusparse -lcublas
CLANG_CUDA_LIB = -L$(CUDA_DIR)/lib64 -L$(CUDA_DIR)/lib \
$(XLINKER)-rpath,$(CUDA_DIR)/lib64,-rpath,$(CUDA_DIR)/lib \
-lcudart -ldl -lrt -pthread
# HIP library configuration
HIP_OPT =
@@ -610,29 +624,20 @@ TRIBOL_LIB = -L$(TRIBOL_DIR)/lib -ltribol -lredecomp -L$(AXOM_DIR)/lib -laxom_mi
-laxom_slam -laxom_slic -laxom_core
# Enzyme configuration
# If you want to enable automatic differentiation at compile time, use the
# options below, adapted to your configuration. To be more flexible, we
# recommend using the Enzyme plugin during link time optimization. One option is
# to add your options to the global compiler/linker flags like
#
# BASE_FLAGS += -flto
# CXX_XLINKER += -fuse-ld=lld -Wl,--lto-legacy-pass-manager\
# -Wl,-mllvm=-load=$(ENZYME_DIR)/LLDEnzyme-$(ENZYME_VERSION).so -Wl,
#
ENZYME_DIR ?= @MFEM_DIR@/../enzyme
ENZYME_VERSION ?= 14
ENZYME_OPT = -fno-experimental-new-pass-manager -Xclang -load -Xclang $(ENZYME_DIR)/ClangEnzyme-$(ENZYME_VERSION).so
ENZYME_LIB = ""
# Google Benchmark, SUNDIALS >= 6.4.0, STRUMPACK, RAJA, UMPIRE, and Tribol require C++14:
ifneq ($(filter YES,$(MFEM_USE_BENCHMARK) $(MFEM_USE_SUNDIALS) $(MFEM_USE_STRUMPACK) $(MFEM_USE_RAJA) $(MFEM_USE_UMPIRE) $(MFEM_USE_TRIBOL)),)
BASE_FLAGS = -std=c++14
endif
# Ginkgo requires C++17:
ifeq ($(MFEM_USE_GINKGO),YES)
BASE_FLAGS = -std=c++17
ENZYME_DIR = @MFEM_DIR@/../enzyme
ENZYME_PLUGIN = $(abspath $(wildcard $(subst \
@MFEM_DIR@,$(MFEM_DIR),$(ENZYME_DIR))/lib/ClangEnzyme-*.$(SO_EXT)))
ifeq ($(MAKECMDGOALS)-$(MFEM_USE_ENZYME),config-YES)
ifeq ($(ENZYME_PLUGIN),)
$(error Unable to find the Enzyme pluging! Please set ENZYME_DIR)
endif
ifneq ($(words $(ENZYME_PLUGIN)),1)
$(error Multiple versions of the Enzyme pluging found! \
Please set ENZYME_PLUGIN directly)
endif
endif
ENZYME_OPT = -fplugin=$(ENZYME_PLUGIN)
ENZYME_LIB =
# If YES, enable some informational messages
VERBOSE = NO
+1 -1
View File
@@ -115,7 +115,7 @@ vertices
nodes
FiniteElementSpace
FiniteElementCollection: Quadratic
FiniteElementCollection: H1_3D_P2
VDim: 3
Ordering: 0
+1 -1
View File
@@ -56,7 +56,7 @@ vertices
nodes
FiniteElementSpace
FiniteElementCollection: Quadratic
FiniteElementCollection: H1_3D_P2
VDim: 3
Ordering: 0
+1 -1
View File
@@ -227,7 +227,7 @@ vertices
nodes
FiniteElementSpace
FiniteElementCollection: Quadratic
FiniteElementCollection: H1_2D_P2
VDim: 2
Ordering: 0
+1 -1
View File
@@ -65,7 +65,7 @@ vertices
nodes
FiniteElementSpace
FiniteElementCollection: Quadratic
FiniteElementCollection: H1_2D_P2
VDim: 2
Ordering: 0
+2
View File
@@ -951,6 +951,7 @@ INPUT = @MFEM_SOURCE_DIR@/doc/CodeDocumentation.dox \
@MFEM_SOURCE_DIR@/fem/ceed/integrators/nlconvection \
@MFEM_SOURCE_DIR@/fem/ceed/interface \
@MFEM_SOURCE_DIR@/fem/ceed/solvers \
@MFEM_SOURCE_DIR@/fem/dfem \
@MFEM_SOURCE_DIR@/fem/eltrans \
@MFEM_SOURCE_DIR@/fem/fe \
@MFEM_SOURCE_DIR@/fem/gslib \
@@ -972,6 +973,7 @@ INPUT = @MFEM_SOURCE_DIR@/doc/CodeDocumentation.dox \
@MFEM_SOURCE_DIR@/miniapps/adjoint \
@MFEM_SOURCE_DIR@/miniapps/autodiff \
@MFEM_SOURCE_DIR@/miniapps/common \
@MFEM_SOURCE_DIR@/miniapps/dfem \
@MFEM_SOURCE_DIR@/miniapps/dpg \
@MFEM_SOURCE_DIR@/miniapps/dpg/util \
@MFEM_SOURCE_DIR@/miniapps/electromagnetics \
+11
View File
@@ -64,6 +64,7 @@ set(SRCS
datacollection.cpp
dgmassinv.cpp
doftrans.cpp
dfem/doperator.cpp
eltrans.cpp
batchitrans.cpp
estimators.cpp
@@ -161,6 +162,7 @@ set(SRCS
transfer.cpp
hyperbolic.cpp
integrator.cpp
bounds.cpp
)
set(HDRS
@@ -180,6 +182,14 @@ set(HDRS
dgmassinv.hpp
dgmassinv_kernels.hpp
doftrans.hpp
dfem/doperator.hpp
dfem/fieldoperator.hpp
dfem/integrate.hpp
dfem/parameterspace.hpp
dfem/qfunction_apply.hpp
dfem/qfunction_transform.hpp
dfem/tuple.hpp
dfem/util.hpp
eltrans.hpp
estimators.hpp
fe.hpp
@@ -263,6 +273,7 @@ set(HDRS
transfer.hpp
hyperbolic.hpp
integrator.hpp
bounds.hpp
)
if (MFEM_USE_SIDRE)
+19 -33
View File
@@ -466,7 +466,6 @@ void BilinearForm::Assemble(int skip_zeros)
}
ElementTransformation *eltrans;
DofTransformation * doftrans;
Mesh *mesh = fes -> GetMesh();
DenseMatrix elmat, *elmat_p;
@@ -503,13 +502,14 @@ void BilinearForm::Assemble(int skip_zeros)
}
}
DofTransformation doftrans;
// Element-wise integration
for (int i = 0; i < fes -> GetNE(); i++)
{
// Set both doftrans (potentially needed to assemble the element
// matrix) and vdofs, which is also needed when the element matrices
// are pre-assembled.
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
if (element_matrices)
{
elmat_p = &(*element_matrices)(i);
@@ -547,10 +547,7 @@ void BilinearForm::Assemble(int skip_zeros)
{
elmat_p = &elmat;
}
if (doftrans)
{
doftrans->TransformDual(elmat);
}
doftrans.TransformDual(elmat);
elmat_p = &elmat;
}
if (static_cond)
@@ -628,13 +625,14 @@ void BilinearForm::Assemble(int skip_zeros)
}
}
DofTransformation doftrans;
for (int i = 0; i < fes -> GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
const FiniteElement &be = *fes->GetBE(i);
doftrans = fes -> GetBdrElementVDofs (i, vdofs);
fes -> GetBdrElementVDofs (i, vdofs, doftrans);
eltrans = fes -> GetBdrElementTransformation (i);
int k = 0;
for (; k < boundary_integs.Size(); k++)
@@ -654,10 +652,7 @@ void BilinearForm::Assemble(int skip_zeros)
boundary_integs[k]->AssembleElementMatrix(be, *eltrans, elemmat);
elmat += elemmat;
}
if (doftrans)
{
doftrans->TransformDual(elmat);
}
doftrans.TransformDual(elmat);
elmat_p = &elmat;
if (!static_cond)
{
@@ -1530,8 +1525,6 @@ void MixedBilinearForm::Assemble(int skip_zeros)
}
ElementTransformation *eltrans;
DofTransformation * dom_dof_trans;
DofTransformation * ran_dof_trans;
DenseMatrix elmat;
Mesh *mesh = test_fes -> GetMesh();
@@ -1554,11 +1547,12 @@ void MixedBilinearForm::Assemble(int skip_zeros)
}
}
DofTransformation dom_dof_trans, ran_dof_trans;
for (int i = 0; i < test_fes -> GetNE(); i++)
{
const int elem_attr = mesh->GetAttribute(i);
dom_dof_trans = trial_fes -> GetElementVDofs (i, trial_vdofs);
ran_dof_trans = test_fes -> GetElementVDofs (i, test_vdofs);
trial_fes->GetElementVDofs (i, trial_vdofs, dom_dof_trans);
test_fes->GetElementVDofs (i, test_vdofs, ran_dof_trans);
eltrans = test_fes -> GetElementTransformation (i);
elmat.SetSize(test_vdofs.Size(), trial_vdofs.Size());
@@ -1574,10 +1568,7 @@ void MixedBilinearForm::Assemble(int skip_zeros)
elmat += elemmat;
}
}
if (ran_dof_trans || dom_dof_trans)
{
TransformDual(ran_dof_trans, dom_dof_trans, elmat);
}
TransformDual(ran_dof_trans, dom_dof_trans, elmat);
mat -> AddSubMatrix (test_vdofs, trial_vdofs, elmat, skip_zeros);
}
}
@@ -1605,13 +1596,14 @@ void MixedBilinearForm::Assemble(int skip_zeros)
}
}
DofTransformation dom_dof_trans, ran_dof_trans;
for (int i = 0; i < test_fes -> GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
dom_dof_trans = trial_fes -> GetBdrElementVDofs (i, trial_vdofs);
ran_dof_trans = test_fes -> GetBdrElementVDofs (i, test_vdofs);
trial_fes->GetBdrElementVDofs (i, trial_vdofs, dom_dof_trans);
test_fes->GetBdrElementVDofs (i, test_vdofs, ran_dof_trans);
eltrans = test_fes -> GetBdrElementTransformation (i);
elmat.SetSize(test_vdofs.Size(), trial_vdofs.Size());
@@ -1626,10 +1618,7 @@ void MixedBilinearForm::Assemble(int skip_zeros)
*eltrans, elemmat);
elmat += elemmat;
}
if (ran_dof_trans || dom_dof_trans)
{
TransformDual(ran_dof_trans, dom_dof_trans, elmat);
}
TransformDual(ran_dof_trans, dom_dof_trans, elmat);
mat -> AddSubMatrix (test_vdofs, trial_vdofs, elmat, skip_zeros);
}
}
@@ -2407,8 +2396,6 @@ void DiscreteLinearOperator::Assemble(int skip_zeros)
}
ElementTransformation *eltrans;
DofTransformation * dom_dof_trans;
DofTransformation * ran_dof_trans;
DenseMatrix elmat;
Mesh *mesh = test_fes->GetMesh();
@@ -2431,11 +2418,13 @@ void DiscreteLinearOperator::Assemble(int skip_zeros)
}
}
DofTransformation dom_dof_trans;
DofTransformation ran_dof_trans;
for (int i = 0; i < test_fes->GetNE(); i++)
{
const int elem_attr = mesh->GetAttribute(i);
dom_dof_trans = trial_fes->GetElementVDofs(i, trial_vdofs);
ran_dof_trans = test_fes->GetElementVDofs(i, test_vdofs);
trial_fes->GetElementVDofs(i, trial_vdofs, dom_dof_trans);
test_fes->GetElementVDofs(i, test_vdofs, ran_dof_trans);
eltrans = test_fes->GetElementTransformation(i);
elmat.SetSize(test_vdofs.Size(), trial_vdofs.Size());
@@ -2451,10 +2440,7 @@ void DiscreteLinearOperator::Assemble(int skip_zeros)
elmat += elemmat;
}
}
if (ran_dof_trans || dom_dof_trans)
{
TransformPrimal(ran_dof_trans, dom_dof_trans, elemmat);
}
TransformPrimal(ran_dof_trans, dom_dof_trans, elemmat);
mat->SetSubMatrix(test_vdofs, trial_vdofs, elemmat, skip_zeros);
}
}
+208 -170
View File
@@ -78,7 +78,7 @@ void MFBilinearFormExtension::AssembleDiagonal(Vector &y) const
dynamic_cast<const ElementRestriction*>(elem_restrict);
if (H1elem_restrict)
{
H1elem_restrict->MultTransposeUnsigned(localY, y);
H1elem_restrict->AbsMultTranspose(localY, y);
}
else
{
@@ -456,7 +456,7 @@ void PABilinearFormExtension::AssembleDiagonal(Vector &y) const
dynamic_cast<const ElementRestriction*>(elem_restrict);
if (H1elem_restrict)
{
H1elem_restrict->MultTransposeUnsigned(localY, y);
H1elem_restrict->AbsMultTranspose(localY, y);
}
else
{
@@ -491,7 +491,7 @@ void PABilinearFormExtension::AssembleDiagonal(Vector &y) const
assemble_diagonal_with_markers(*bdr_integs[i], bdr_markers[i],
bdr_attributes, bdr_face_Y);
}
bdr_face_restrict_lex->AddMultTransposeUnsigned(bdr_face_Y, y);
bdr_face_restrict_lex->AddAbsMultTranspose(bdr_face_Y, y);
}
}
@@ -526,7 +526,8 @@ void PABilinearFormExtension::FormLinearSystem(const Array<int> &ess_tdof_list,
A.Reset(oper); // A will own oper
}
void PABilinearFormExtension::Mult(const Vector &x, Vector &y) const
void PABilinearFormExtension::MultInternal(const Vector &x, Vector &y,
const bool useAbs) const
{
Array<BilinearFormIntegrator*> &integrators = *a->GetDBFI();
@@ -558,11 +559,13 @@ void PABilinearFormExtension::Mult(const Vector &x, Vector &y) const
{
if (integrators[i]->Patchwise())
{
MFEM_ASSERT(!useAbs, "AbsMult not implemented with NURBS!")
integrators[i]->AddMultNURBSPA(x, y);
}
else
{
integrators[i]->AddMultPA(x, y);
if (useAbs) { integrators[i]->AddAbsMultPA(x, y); }
else { integrators[i]->AddMultPA(x, y); }
}
}
}
@@ -571,14 +574,30 @@ void PABilinearFormExtension::Mult(const Vector &x, Vector &y) const
if (iSz)
{
Array<Array<int>*> &elem_markers = *a->GetDBFI_Marker();
elem_restrict->Mult(x, localX);
auto H1elem_restrict =
dynamic_cast<const ElementRestriction*>(elem_restrict);
if (H1elem_restrict && useAbs)
{
H1elem_restrict->AbsMult(x, localX);
}
else
{
elem_restrict->Mult(x, localX);
}
localY = 0.0;
for (int i = 0; i < iSz; ++i)
{
AddMultWithMarkers(*integrators[i], localX, elem_markers[i],
elem_attributes, false, localY);
elem_attributes, false, localY, useAbs);
}
if (H1elem_restrict && useAbs)
{
H1elem_restrict->AbsMultTranspose(localY, y);
}
else
{
elem_restrict->MultTranspose(localY, y);
}
elem_restrict->MultTranspose(localY, y);
}
else
{
@@ -590,6 +609,7 @@ void PABilinearFormExtension::Mult(const Vector &x, Vector &y) const
const int iFISz = intFaceIntegrators.Size();
if (int_face_restrict_lex && iFISz>0)
{
MFEM_ASSERT(!useAbs, "AbsMult not implemented for face integrators!")
// When assembling interior face integrators for DG spaces, we need to
// exchange the face-neighbor information. This happens inside member
// functions of the 'int_face_restrict_lex'. To avoid repeated calls to
@@ -651,6 +671,7 @@ void PABilinearFormExtension::Mult(const Vector &x, Vector &y) const
const bool has_bdr_integs = (n_bdr_face_integs > 0 || n_bdr_integs > 0);
if (bdr_face_restrict_lex && has_bdr_integs)
{
MFEM_ASSERT(!useAbs, "AbsMult not implemented for bdr integrators!")
Array<Array<int>*> &bdr_markers = *a->GetBBFI_Marker();
Array<Array<int>*> &bdr_face_markers = *a->GetBFBFI_Marker();
bdr_face_restrict_lex->Mult(x, bdr_face_X);
@@ -828,22 +849,39 @@ void PABilinearFormExtension::AddMultWithMarkers(
const Array<int> *markers,
const Array<int> &attributes,
const bool transpose,
Vector &y) const
Vector &y,
const bool useAbs) const
{
if (markers)
{
tmp_evec.SetSize(y.Size());
tmp_evec = 0.0;
if (transpose) { integ.AddMultTransposePA(x, tmp_evec); }
else { integ.AddMultPA(x, tmp_evec); }
if (useAbs)
{
if (transpose) { integ.AddAbsMultTransposePA(x, tmp_evec); }
else { integ.AddAbsMultPA(x, tmp_evec); }
}
else
{
if (transpose) { integ.AddMultTransposePA(x, tmp_evec); }
else { integ.AddMultPA(x, tmp_evec); }
}
const int ne = attributes.Size();
const int nd = x.Size() / ne;
AddWithMarkers_(ne, nd, tmp_evec, *markers, attributes, y);
}
else
{
if (transpose) { integ.AddMultTransposePA(x, y); }
else { integ.AddMultPA(x, y); }
if (useAbs)
{
if (transpose) { integ.AddAbsMultTransposePA(x, y); }
else { integ.AddAbsMultPA(x, y); }
}
else
{
if (transpose) { integ.AddMultTransposePA(x, y); }
else { integ.AddMultPA(x, y); }
}
}
}
@@ -1010,8 +1048,13 @@ void EABilinearFormExtension::Assemble()
}
}
void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
void EABilinearFormExtension::MultInternal(const Vector &x, Vector &y,
const bool useTranspose,
const bool useAbs) const
{
auto elemRest = dynamic_cast<const ElementRestriction*>(elem_restrict);
MFEM_ASSERT(useAbs?(elemRest!=nullptr):true,
"elem_restrict is not ElementRestriction*!")
// Apply the Element Restriction
const bool useRestrict = !DeviceCanUseCeed() && elem_restrict;
if (!useRestrict)
@@ -1019,6 +1062,11 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
y.UseDevice(true); // typically this is a large vector, so store on device
y = 0.0;
}
else if (useAbs)
{
elemRest->AbsMult(x, localX);
localY = 0.0;
}
else
{
elem_restrict->Mult(x, localX);
@@ -1026,25 +1074,55 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
}
// Apply the Element Matrices
{
Vector abs_ea_data;
if (useAbs)
{
abs_ea_data = ea_data;
abs_ea_data.Abs();
}
const int NDOFS = elemDofs;
auto X = Reshape(useRestrict?localX.Read():x.Read(), NDOFS, ne);
auto Y = Reshape(useRestrict?localY.ReadWrite():y.ReadWrite(), NDOFS, ne);
auto A = Reshape(ea_data.Read(), NDOFS, NDOFS, ne);
mfem::forall(ne*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
auto A = Reshape(useAbs?abs_ea_data.Read():ea_data.Read(), NDOFS, NDOFS, ne);
if (!useTranspose)
{
const int e = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
mfem::forall(ne*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
res += A(i, j, e)*X(i, e);
}
Y(j, e) += res;
});
const int e = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A(i, j, e)*X(i, e);
}
Y(j, e) += res;
});
}
else
{
mfem::forall(ne*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int e = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A(j, i, e)*X(i, e);
}
Y(j, e) += res;
});
}
// Apply the Element Restriction transposed
if (useRestrict)
{
elem_restrict->MultTranspose(localY, y);
if (useAbs)
{
elemRest->AbsMultTranspose(localY, y);
}
else
{
elem_restrict->MultTranspose(localY, y);
}
}
}
@@ -1053,6 +1131,7 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
const int iFISz = intFaceIntegrators.Size();
if (int_face_restrict_lex && iFISz>0)
{
MFEM_VERIFY(!useAbs, "AbsMult not implemented with Face integrators!")
// Apply the Interior Face Restriction
int_face_restrict_lex->Mult(x, int_face_X);
if (int_face_X.Size()>0)
@@ -1064,7 +1143,65 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
auto Y = Reshape(int_face_Y.ReadWrite(), NDOFS, 2, nf_int);
if (!factorize_face_terms)
{
auto A_int = Reshape(ea_data_int.Read(), NDOFS, NDOFS, 2, nf_int);
Vector abs_ea_data_int(ea_data_int.Size());
if (useAbs)
{
abs_ea_data_int = ea_data_int;
abs_ea_data_int.Abs();
}
auto A_int = Reshape(useAbs?abs_ea_data_int.Read():ea_data_int.Read(),
NDOFS, NDOFS, 2, nf_int);
if (!useTranspose)
{
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(i, j, 0, f)*X(i, 0, f);
}
Y(j, 0, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(i, j, 1, f)*X(i, 1, f);
}
Y(j, 1, f) += res;
});
}
else
{
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(j, i, 0, f)*X(i, 0, f);
}
Y(j, 0, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(j, i, 1, f)*X(i, 1, f);
}
Y(j, 1, f) += res;
});
}
}
Vector abs_ea_data_ext(ea_data_ext.Size());
if (useAbs)
{
abs_ea_data_ext = ea_data_ext;
abs_ea_data_ext.Abs();
}
auto A_ext = Reshape(useAbs?abs_ea_data_ext.Read():ea_data_ext.Read(),
NDOFS, NDOFS, 2, nf_int);
if (!useTranspose)
{
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
@@ -1072,35 +1209,37 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(i, j, 0, f)*X(i, 0, f);
res += A_ext(i, j, 0, f)*X(i, 0, f);
}
Y(j, 0, f) += res;
Y(j, 1, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(i, j, 1, f)*X(i, 1, f);
res += A_ext(i, j, 1, f)*X(i, 1, f);
}
Y(j, 1, f) += res;
Y(j, 0, f) += res;
});
}
auto A_ext = Reshape(ea_data_ext.Read(), NDOFS, NDOFS, 2, nf_int);
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
else
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
res += A_ext(i, j, 0, f)*X(i, 0, f);
}
Y(j, 1, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_ext(i, j, 1, f)*X(i, 1, f);
}
Y(j, 0, f) += res;
});
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_ext(j, i, 1, f)*X(i, 0, f);
}
Y(j, 1, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_ext(j, i, 0, f)*X(i, 1, f);
}
Y(j, 0, f) += res;
});
}
// Apply the Interior Face Restriction transposed
int_face_restrict_lex->AddMultTransposeInPlace(int_face_Y, y);
}
@@ -1109,7 +1248,9 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
// Treatment of boundary faces
if (!factorize_face_terms && bdr_face_restrict_lex && ea_data_bdr.Size() > 0)
{
MFEM_ASSERT(!useAbs, "AbsMult not implemented with Face integrators!")
// Apply the Boundary Face Restriction
// TODO: AbsMult if needed
bdr_face_restrict_lex->Mult(x, bdr_face_X);
bdr_face_Y = 0.0;
// Apply the boundary face matrices
@@ -1117,141 +1258,38 @@ void EABilinearFormExtension::Mult(const Vector &x, Vector &y) const
auto X = Reshape(bdr_face_X.Read(), NDOFS, nf_bdr);
auto Y = Reshape(bdr_face_Y.ReadWrite(), NDOFS, nf_bdr);
auto A = Reshape(ea_data_bdr.Read(), NDOFS, NDOFS, nf_bdr);
mfem::forall(nf_bdr*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
if (!useTranspose)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A(i, j, f)*X(i, f);
}
Y(j, f) += res;
});
// Apply the Boundary Face Restriction transposed
bdr_face_restrict_lex->AddMultTransposeInPlace(bdr_face_Y, y);
}
}
void EABilinearFormExtension::MultTranspose(const Vector &x, Vector &y) const
{
// Apply the Element Restriction
const bool useRestrict = !DeviceCanUseCeed() && elem_restrict;
if (!useRestrict)
{
y.UseDevice(true); // typically this is a large vector, so store on device
y = 0.0;
}
else
{
elem_restrict->Mult(x, localX);
localY = 0.0;
}
// Apply the Element Matrices transposed
{
const int NDOFS = elemDofs;
auto X = Reshape(useRestrict?localX.Read():x.Read(), NDOFS, ne);
auto Y = Reshape(useRestrict?localY.ReadWrite():y.ReadWrite(), NDOFS, ne);
auto A = Reshape(ea_data.Read(), NDOFS, NDOFS, ne);
mfem::forall(ne*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int e = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A(j, i, e)*X(i, e);
}
Y(j, e) += res;
});
// Apply the Element Restriction transposed
if (useRestrict)
{
elem_restrict->MultTranspose(localY, y);
}
}
// Treatment of interior faces
Array<BilinearFormIntegrator*> &intFaceIntegrators = *a->GetFBFI();
const int iFISz = intFaceIntegrators.Size();
if (int_face_restrict_lex && iFISz>0)
{
// Apply the Interior Face Restriction
int_face_restrict_lex->Mult(x, int_face_X);
if (int_face_X.Size()>0)
{
int_face_Y = 0.0;
// Apply the interior face matrices transposed
const int NDOFS = faceDofs;
auto X = Reshape(int_face_X.Read(), NDOFS, 2, nf_int);
auto Y = Reshape(int_face_Y.ReadWrite(), NDOFS, 2, nf_int);
if (!factorize_face_terms)
{
auto A_int = Reshape(ea_data_int.Read(), NDOFS, NDOFS, 2, nf_int);
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(j, i, 0, f)*X(i, 0, f);
}
Y(j, 0, f) += res;
res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_int(j, i, 1, f)*X(i, 1, f);
}
Y(j, 1, f) += res;
});
}
auto A_ext = Reshape(ea_data_ext.Read(), NDOFS, NDOFS, 2, nf_int);
mfem::forall(nf_int*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
// TODO: useAbs
mfem::forall(nf_bdr*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_ext(j, i, 1, f)*X(i, 0, f);
res += A(i, j, f)*X(i, f);
}
Y(j, 1, f) += res;
res = 0.0;
Y(j, f) += res;
});
}
else
{
// TODO: useAbs
mfem::forall(nf_bdr*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A_ext(j, i, 0, f)*X(i, 1, f);
res += A(j, i, f)*X(i, f);
}
Y(j, 0, f) += res;
Y(j, f) += res;
});
// Apply the Interior Face Restriction transposed
int_face_restrict_lex->AddMultTransposeInPlace(int_face_Y, y);
}
}
// Treatment of boundary faces
if (!factorize_face_terms && bdr_face_restrict_lex && ea_data_bdr.Size() > 0)
{
// Apply the Boundary Face Restriction
bdr_face_restrict_lex->Mult(x, bdr_face_X);
bdr_face_Y = 0.0;
// Apply the boundary face matrices transposed
const int NDOFS = faceDofs;
auto X = Reshape(bdr_face_X.Read(), NDOFS, nf_bdr);
auto Y = Reshape(bdr_face_Y.ReadWrite(), NDOFS, nf_bdr);
auto A = Reshape(ea_data_bdr.Read(), NDOFS, NDOFS, nf_bdr);
mfem::forall(nf_bdr*NDOFS, [=] MFEM_HOST_DEVICE (int glob_j)
{
const int f = glob_j/NDOFS;
const int j = glob_j%NDOFS;
real_t res = 0.0;
for (int i = 0; i < NDOFS; i++)
{
res += A(j, i, f)*X(i, f);
}
Y(j, f) += res;
});
// Apply the Boundary Face Restriction transposed
// TODO: AbsMultTranspose if needed
bdr_face_restrict_lex->AddMultTransposeInPlace(bdr_face_Y, y);
}
}
@@ -1911,7 +1949,7 @@ void PAMixedBilinearFormExtension::AssembleDiagonal_ADAt(const Vector &D,
dynamic_cast<const ElementRestriction*>(elem_restrict_trial);
if (H1elem_restrict_trial)
{
H1elem_restrict_trial->MultUnsigned(D, localTrial);
H1elem_restrict_trial->AbsMult(D, localTrial);
}
else
{
@@ -1937,7 +1975,7 @@ void PAMixedBilinearFormExtension::AssembleDiagonal_ADAt(const Vector &D,
dynamic_cast<const ElementRestriction*>(elem_restrict_test);
if (H1elem_restrict_test)
{
H1elem_restrict_test->MultTransposeUnsigned(localTest, diag);
H1elem_restrict_test->AbsMultTranspose(localTest, diag);
}
else
{
@@ -1993,7 +2031,7 @@ void PADiscreteLinearOperatorExtension::Assemble()
dynamic_cast<const ElementRestriction*>(elem_restrict_test);
if (elem_restrict)
{
elem_restrict->MultTransposeUnsigned(ones, test_multiplicity);
elem_restrict->AbsMultTranspose(ones, test_multiplicity);
}
else
{
+22 -4
View File
@@ -91,12 +91,17 @@ public:
Vector &x, Vector &b,
OperatorHandle &A, Vector &X, Vector &B,
int copy_interior = 0) override;
void Mult(const Vector &x, Vector &y) const override;
void Mult(const Vector &x, Vector &y) const override
{ MultInternal(x,y); }
void AbsMult(const Vector &x, Vector &y) const override
{ MultInternal(x,y, true); }
void MultTranspose(const Vector &x, Vector &y) const override;
void Update() override;
protected:
void SetupRestrictionOperators(const L2FaceValues m);
void MultInternal(const Vector &x, Vector &y,
const bool useAbs = false) const;
/// @brief Accumulate the action (or transpose) of the integrator on @a x
/// into @a y, taking into account the (possibly null) @a markers array.
@@ -110,12 +115,14 @@ protected:
/// @param attributes Array of element or boundary element attributes.
/// @param transpose Compute the action or transpose of the integrator .
/// @param y Output E-vector
/// @param useAbs Apply absolute-value operator
void AddMultWithMarkers(const BilinearFormIntegrator &integ,
const Vector &x,
const Array<int> *markers,
const Array<int> &attributes,
const bool transpose,
Vector &y) const;
Vector &y,
const bool useAbs = false) const;
/// @brief Performs the same function as AddMultWithMarkers, but takes as
/// input and output face normal derivatives.
@@ -152,8 +159,15 @@ public:
EABilinearFormExtension(BilinearForm *form);
void Assemble() override;
void Mult(const Vector &x, Vector &y) const override;
void MultTranspose(const Vector &x, Vector &y) const override;
void Mult(const Vector &x, Vector &y) const override
{ MultInternal(x, y, false); }
void AbsMult(const Vector &x, Vector &y) const override
{ MultInternal(x, y, false, true); }
void MultTranspose(const Vector &x, Vector &y) const override
{ MultInternal(x, y, true); }
void AbsMultTranspose(const Vector &x, Vector &y) const override
{ MultInternal(x, y, true, true); }
/// @brief Populates @a element_matrices with the element matrices.
///
@@ -165,6 +179,10 @@ public:
void GetElementMatrices(DenseTensor &element_matrices,
ElementDofOrdering ordering,
bool add_bdr);
// This method needs to be public due to 'nvcc' restriction.
void MultInternal(const Vector &x, Vector &y, const bool useTranspose,
const bool useAbs = false) const;
};
/// Data and methods for fully-assembled bilinear forms
+29
View File
@@ -121,6 +121,12 @@ void BilinearFormIntegrator::AddMultPA(const Vector &, Vector &) const
" is not implemented for this class.");
}
void BilinearFormIntegrator::AddAbsMultPA(const Vector &, Vector &) const
{
MFEM_ABORT("BilinearFormIntegrator:AddAbsMultPA:(...)\n"
" is not implemented for this class.");
}
void BilinearFormIntegrator::AddMultNURBSPA(const Vector &, Vector &) const
{
MFEM_ABORT("BilinearFormIntegrator::AddMultNURBSPA(...)\n"
@@ -133,6 +139,13 @@ void BilinearFormIntegrator::AddMultTransposePA(const Vector &, Vector &) const
" is not implemented for this class.");
}
void BilinearFormIntegrator::AddAbsMultTransposePA(const Vector &,
Vector &) const
{
MFEM_ABORT("BilinearFormIntegrator::AddAbsMultTransposePA(...)\n"
" is not implemented for this class.");
}
void BilinearFormIntegrator::AssembleMF(const FiniteElementSpace &fes)
{
MFEM_ABORT("BilinearFormIntegrator::AssembleMF(...)\n"
@@ -418,6 +431,14 @@ void SumIntegrator::AddMultPA(const Vector& x, Vector& y) const
}
}
void SumIntegrator::AddAbsMultPA(const Vector& x, Vector& y) const
{
for (int i = 0; i < integrators.Size(); i++)
{
integrators[i]->AddAbsMultPA(x, y);
}
}
void SumIntegrator::AddMultTransposePA(const Vector &x, Vector &y) const
{
for (int i = 0; i < integrators.Size(); i++)
@@ -426,6 +447,14 @@ void SumIntegrator::AddMultTransposePA(const Vector &x, Vector &y) const
}
}
void SumIntegrator::AddAbsMultTransposePA(const Vector &x, Vector &y) const
{
for (int i = 0; i < integrators.Size(); i++)
{
integrators[i]->AddAbsMultTransposePA(x, y);
}
}
void SumIntegrator::AssembleMF(const FiniteElementSpace &fes)
{
for (int i = 0; i < integrators.Size(); i++)
+18
View File
@@ -78,6 +78,8 @@ public:
called. */
void AddMultPA(const Vector &x, Vector &y) const override;
virtual void AddAbsMultPA(const Vector &x, Vector &y) const;
/// Method for partially assembled action on NURBS patches.
virtual void AddMultNURBSPA(const Vector&x, Vector&y) const;
@@ -90,6 +92,8 @@ public:
called. */
virtual void AddMultTransposePA(const Vector &x, Vector &y) const;
virtual void AddAbsMultTransposePA(const Vector &x, Vector &y) const;
/// Method defining element assembly.
/** The result of the element assembly is added to the @a emat Vector if
@a add is true. Otherwise, if @a add is false, we set @a emat. */
@@ -496,8 +500,12 @@ public:
void AddMultTransposePA(const Vector &x, Vector &y) const override;
void AddAbsMultTransposePA(const Vector &x, Vector &y) const override;
void AddMultPA(const Vector& x, Vector& y) const override;
void AddAbsMultPA(const Vector& x, Vector& y) const override;
void AssembleMF(const FiniteElementSpace &fes) override;
void AddMultMF(const Vector &x, Vector &y) const override;
@@ -2320,8 +2328,12 @@ public:
void AddMultPA(const Vector&, Vector&) const override;
void AddAbsMultPA(const Vector&, Vector&) const override;
void AddMultTransposePA(const Vector&, Vector&) const override;
void AddAbsMultTransposePA(const Vector&, Vector&) const override;
void AddMultNURBSPA(const Vector&, Vector&) const override;
void AddMultPatchPA(const int patch, const Vector &x, Vector &y) const;
@@ -2419,8 +2431,12 @@ public:
void AddMultPA(const Vector&, Vector&) const override;
void AddAbsMultPA(const Vector&, Vector&) const override;
void AddMultTransposePA(const Vector&, Vector&) const override;
void AddAbsMultTransposePA(const Vector&, Vector&) const override;
static const IntegrationRule &GetRule(const FiniteElement &trial_fe,
const FiniteElement &test_fe,
const ElementTransformation &Trans);
@@ -2816,6 +2832,7 @@ public:
using BilinearFormIntegrator::AssemblePA;
void AssemblePA(const FiniteElementSpace &fes) override;
void AddMultPA(const Vector &x, Vector &y) const override;
void AddAbsMultPA(const Vector &x, Vector &y) const override;
void AssembleDiagonalPA(Vector& diag) override;
const Coefficient *GetCoefficient() const { return Q; }
@@ -2933,6 +2950,7 @@ public:
void AssemblePA(const FiniteElementSpace &trial_fes,
const FiniteElementSpace &test_fes) override;
void AddMultPA(const Vector &x, Vector &y) const override;
void AddAbsMultPA(const Vector &x, Vector &y) const override;
void AddMultTransposePA(const Vector &x, Vector &y) const override;
void AssembleDiagonalPA(Vector& diag) override;
void AssembleEA(const FiniteElementSpace &fes, Vector &emat,
+715
View File
@@ -0,0 +1,715 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// Implementation of bounds
#include "bounds.hpp"
#include <limits>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
namespace mfem
{
using namespace std;
void PLBound::Setup(const int nb_i, const int ncp_i,
const int b_type_i, const int cp_type_i,
const real_t tol_i)
{
MFEM_VERIFY(b_type_i >= 0 && b_type_i <= 2, "Bases not supported. "
"Please read class description to see supported types.");
MFEM_VERIFY(cp_type_i == 0 || cp_type_i == 1,
"Control point type not supported. Please read class "
"description to see supported types.");
nb = nb_i;
ncp = ncp_i;
b_type = b_type_i;
cp_type = cp_type_i;
tol = tol_i;
lbound.SetSize(nb, ncp);
ubound.SetSize(nb, ncp);
nodes.SetSize(nb);
weights.SetSize(nb);
control_points.SetSize(ncp);
auto scalenodes = [](const Vector &in, const real_t a, const real_t b) -> Vector
{
Vector outVec(in.Size());
real_t maxv = in.Max();
real_t minv = in.Min();
for (int i = 0; i < in.Size(); i++)
{
outVec(i) = a + (b-a)*(in(i)-minv)/(maxv-minv);
}
return outVec;
};
MFEM_VERIFY(ncp >= 2,"At least 2 control points are required.");
if (cp_type == 0) // GL + End Point
{
control_points(0) = 0.0;
control_points(ncp-1) = 1.0;
if (ncp > 2)
{
const real_t *x = poly1d.GetPoints(ncp-3, 0);
MFEM_VERIFY(x, "Error in getting points.");
for (int i = 0; i < ncp-2; i++)
{
control_points(i+1) = x[i];
}
}
}
else if (cp_type == 1) // Chebyshev
{
auto GetChebyshevNodes = [](int n) -> Vector
{
Vector cheb(n);
for (int i = 0; i < n; ++i)
{
cheb(i) = -cos(M_PI * (static_cast<real_t>(i) / (n - 1)));
}
return cheb;
};
control_points = GetChebyshevNodes(ncp);
}
else
{
MFEM_ABORT("Unsupported interval points. Use [0,1].\n");
}
control_points = scalenodes(control_points, 0.0, 1.0); // rescale to [0,1]
Poly_1D::Basis &basis1d(poly1d.GetBasis(nb-1, b_type));
// Initialize bounds
lbound = 0.0;
ubound = 0.0;
Vector bmv(nb), bpv(nb), bv(nb); // basis values
Vector bdmv(nb), bdpv(nb), bdv(nb); // basis derivative values
Vector vals(3);
// See Section 3.1.1 of https://arxiv.org/pdf/2501.12349 for explanation of
// procedure below.
for (int j = 0; j < ncp; j++)
{
real_t x = control_points(j);
real_t xm = x;
if (j != 0)
{
xm = 0.5*(control_points(j-1)+control_points(j));
}
real_t xp = x;
if (j != ncp-1)
{
xp = 0.5*(control_points(j)+control_points(j+1));
}
basis1d.Eval(xm, bmv, bdmv);
basis1d.Eval(xp, bpv, bdpv);
basis1d.Eval(x, bv);
real_t dm = x-xm;
real_t dp = x-xp;
for (int i = 0; i < nb; i++)
{
if (j == 0)
{
lbound(i, j) = bv(i);
ubound(i, j) = bv(i);
}
else if (j == ncp-1)
{
lbound(i, j) = bv(i);
ubound(i, j) = bv(i);
}
else
{
vals(0) = bv(i);
vals(1) = bmv(i) + dm*bdmv(i);
vals(2) = bpv(i) + dp*bdpv(i);
lbound(i, j) = vals.Min()-tol; // tolerance for good measure
ubound(i, j) = vals.Max()+tol; // tolerance for good measure
}
}
}
IntegrationRule irule(nb);
if (b_type == 0)
{
QuadratureFunctions1D::GaussLegendre(nb, &irule);
for (int i = 0; i < nb; i++)
{
weights(i) = irule.IntPoint(i).weight;
nodes(i) = irule.IntPoint(i).x;
}
}
else if (b_type == 1)
{
QuadratureFunctions1D::GaussLobatto(nb, &irule);
for (int i = 0; i < nb; i++)
{
weights(i) = irule.IntPoint(i).weight;
nodes(i) = irule.IntPoint(i).x;
}
}
else if (b_type == 2)
{
QuadratureFunctions1D::ClosedUniform(nb, &irule);
for (int i = 0; i < nb; i++)
{
weights(i) = irule.IntPoint(i).weight;
nodes(i) = irule.IntPoint(i).x;
}
}
if (b_type == 2)
{
nodes_int.SetSize(nb);
weights_int.SetSize(nb);
IntegrationRule irule_int(nb);
{
QuadratureFunctions1D::GaussLobatto(nb, &irule_int);
for (int i = 0; i < nb; i++)
{
weights_int(i) = irule_int.IntPoint(i).weight;
nodes_int(i) = irule_int.IntPoint(i).x;
}
}
SetupBernsteinBasisMat(basisMatNodes, nodes);
// Setup memory for lu factors
basisMatLU = basisMatNodes;
lu_ip.SetSize(nb);
// Compute lu factors
LUFactors lu(basisMatLU.GetData(), lu_ip.GetData());
bool factor = lu.Factor(nb);
MFEM_VERIFY(factor,"Failure in LU factorization in PLBound.");
// Setup the Bernstein basis matrix for the GLL integration points. This
// is used to compute linear fit.
SetupBernsteinBasisMat(basisMatInt, nodes_int);
}
else
{
nodes_int.SetDataAndSize(nodes.GetData(), nb);
weights_int.SetDataAndSize(weights.GetData(), nb);
}
}
PLBound::PLBound(FiniteElementSpace *fes, int ncp_i, int cp_type_i)
{
MFEM_VERIFY(!fes->IsVariableOrder(),
"Variable order meshes not yet supported.");
const char *name = fes->FEColl()->Name();
string cname = name;
cp_type = cp_type_i;
b_type = BasisType::Invalid;
nb = fes->GetMaxElementOrder()+1;
tol = 0.0;
int minncp = 2;
if (nb > 12)
{
minncp = 2*nb;
}
else if (!strncmp(name, "H1_", 3) && strncmp(name, "H1_Trace_", 9))
{
// H1 GLL
b_type = BasisType::GaussLobatto;
minncp = min_ncp_gll_x[cp_type][nb-2];
}
else if (!strncmp(name, "H1Pos_", 6) && strncmp(name, "H1Pos_Trace_", 12))
{
// H1 Positive
b_type = BasisType::Positive;
minncp = min_ncp_pos_x[cp_type][nb-2];
}
else if (!strncmp(name, "L2_", 3) && strncmp(name, "L2_T", 4))
{
// L2 Gauss-Legendre
b_type = BasisType::GaussLegendre;
minncp = min_ncp_gl_x[cp_type][nb-2];
}
else if (!strncmp(name, "L2_T1", 5))
{
// L2 GLL
b_type = BasisType::GaussLobatto;
minncp = min_ncp_gll_x[cp_type][nb-2];
}
else if (!strncmp(name, "L2_T2", 5))
{
// L2 Positive
b_type = BasisType::Positive;
minncp = min_ncp_pos_x[cp_type][nb-2];
}
else
{
MFEM_ABORT("Only H1 GLL/Positive & L2 GL/GLL/Positive bases supported.");
}
ncp = std::max(minncp, ncp_i);
Setup(nb, ncp, b_type, cp_type, tol);
}
void PLBound::Get1DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const
{
real_t x,w;
intmin.SetSize(ncp);
intmax.SetSize(ncp);
intmin = 0.0;
intmax = 0.0;
Vector coeffm(nb);
coeffm = 0.0;
real_t a0 = 0.0;
real_t a1 = 0.0;
Vector nodal_vals, nodal_integ_vals;
if (b_type == 2) // compute values at equispaced nodes and GLL nodes
{
nodal_vals.SetSize(nb);
nodal_integ_vals.SetSize(nb);
Vector shape(nb);
for (int i = 0; i < nb; i++)
{
basisMatNodes.GetRow(i, shape);
nodal_vals(i) = shape*coeff;
basisMatInt.GetRow(i, shape);
nodal_integ_vals(i) = shape*coeff;
}
}
else
{
nodal_vals.SetDataAndSize(coeff.GetData(), nb);
nodal_integ_vals.SetDataAndSize(coeff.GetData(), nb);
}
// compute L2 projection for linear bases: a0 + a1*x
if (proj)
{
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes_int(i)-1;
w = 2.0*weights_int(i);
a0 += 0.5*nodal_integ_vals(i)*w;
a1 += 1.5*nodal_integ_vals(i)*w*x;
}
// offset the linear fit from nodal values
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes(i)-1;
coeffm(i) = nodal_vals(i) - a0 - a1*x;
}
// compute coefficients for Bernstein
if (b_type == 2)
{
LUFactors lu(basisMatLU.GetData(), lu_ip.GetData());
lu.Solve(nb, 1, coeffm.GetData());
}
// initialize the bounds to be the linear fit
for (int j = 0; j < ncp; j++)
{
x = 2.0*control_points(j)-1;
intmin(j) = a0 + a1*x;
intmax(j) = intmin(j);
}
}
else
{
coeffm.SetDataAndSize(coeff.GetData(), nb);
}
for (int i = 0; i < nb; i++)
{
real_t c = coeffm(i);
for (int j = 0; j < ncp; j++)
{
intmin(j) += min(lbound(i,j)*c, ubound(i,j)*c);
intmax(j) += max(lbound(i,j)*c, ubound(i,j)*c);
}
}
}
void PLBound::Get2DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const
{
intmin.SetSize(ncp*ncp);
intmax.SetSize(ncp*ncp);
intmin = 0.0;
intmax = 0.0;
Vector intminT(ncp*nb);
Vector intmaxT(ncp*nb);
// Get bounds for each row of the solution
for (int i = 0; i < nb; i++)
{
Vector solcoeff(coeff.GetData()+i*nb, nb);
Vector intminrow(intminT.GetData()+i*ncp, ncp);
Vector intmaxrow(intmaxT.GetData()+i*ncp, ncp);
Get1DBounds(solcoeff, intminrow, intmaxrow);
}
Vector intminT2 = intminT;
// Compute a0 and a1 for each column of nodes
Vector a0V(ncp), a1V(ncp);
a0V = 0.0;
a1V = 0.0;
real_t x,w,t;
if (proj)
{
if (b_type == 2)
{
// Note: DenseMatrix uses column-major ordering so we will need to
// transpose the matrix.
DenseMatrix intminTM(intminT.GetData(), ncp, nb),
intmaxTM(intmaxT.GetData(), ncp, nb),
intmeanTM(ncp, nb);
DenseMatrix minvalsM(nb, ncp), maxvalsM(nb, ncp), meanintvalsM(nb, ncp);
MultABt(basisMatNodes, intminTM, minvalsM);
MultABt(basisMatNodes, intmaxTM, maxvalsM);
intmeanTM = intminTM;
intmeanTM += intmaxTM;
intmeanTM *= 0.5;
MultABt(basisMatInt, intmeanTM, meanintvalsM);
// Compute the linear fit along each column and then offset it from
// the bounds on the coefficient.
// Note: Since Bernstein bases are positive, we can use the lower
// bounds to compute the lower bounding polynomial and subtract the
// linear fit before finding the Bernstein coefficients corresponding
// to the perturbation. Same for upper bounds. If the bases were not
// always positive, it is not yet clear if the perturbation
// coefficients will be this straightforward to compute.
for (int j = 0; j < ncp; j++) // row of interval points
{
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes_int(i)-1; // x-coordinate
w = 2.0*weights_int(i); // weight
t = meanintvalsM(i,j);
a0V(j) += 0.5*t*w;
a1V(j) += 1.5*t*w*x;
}
// Offset linear fit
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes(i)-1; // x-coordinate
minvalsM(i,j) -= a0V(j) + a1V(j)*x;
maxvalsM(i,j) -= a0V(j) + a1V(j)*x;
}
// Compute Bernstein coefficients
LUFactors lu(basisMatLU.GetData(), lu_ip.GetData());
lu.Solve(nb, 1, minvalsM.GetColumn(j));
lu.Solve(nb, 1, maxvalsM.GetColumn(j));
for (int i = 0; i < nb; i++)
{
intminT(i*ncp+j) = minvalsM(i,j);
intmaxT(i*ncp+j) = maxvalsM(i,j);
}
}
}
else
{
for (int j = 0; j < nb; j++) // row of nodes
{
x = 2.0*nodes(j)-1; // x-coordinate
w = 2.0*weights(j); // weight
for (int i = 0; i < ncp; i++) // column of interval points
{
t = 0.5*(intminT(j*ncp+i)+intmaxT(j*ncp+i));
a0V(i) += 0.5*t*w;
a1V(i) += 1.5*t*w*x;
}
}
// offset the linear fit from nodal values
for (int j = 0; j < nb; j++) // row of nodes
{
x = 2.0*nodes(j)-1; // x-coordinate
for (int i = 0; i < ncp; i++) // column of interval points
{
t = a0V(i) + a1V(i)*x;
intminT(j*ncp+i) -= t;
intmaxT(j*ncp+i) -= t;
}
}
}
// Initialize bounds using a0 and a1 values
for (int j = 0; j < ncp; j++) // row j
{
x = 2.0*control_points(j)-1;
for (int i = 0; i < ncp; i++) // column i
{
intmin(j*ncp+i) = a0V(i) + a1V(i)*x;
intmax(j*ncp+i) = intmin(j*ncp+i);
}
}
}
// Compute bounds
int id1 = 0, id2 = 0;
Vector vals(4);
for (int j = 0; j < nb; j++)
{
for (int i = 0; i < ncp; i++) // ith column
{
real_t w0 = intminT(id1++);
real_t w1 = intmaxT(id2++);
for (int k = 0; k < ncp; k++) // kth row
{
vals(0) = w0*lbound(j,k);
vals(1) = w0*ubound(j,k);
vals(2) = w1*lbound(j,k);
vals(3) = w1*ubound(j,k);
intmin(k*ncp+i) += vals.Min();
intmax(k*ncp+i) += vals.Max();
}
}
}
}
void PLBound::Get3DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const
{
int nb2 = nb*nb,
ncp2 = ncp*ncp,
ncp3 = ncp*ncp*ncp;
intmin.SetSize(ncp3);
intmax.SetSize(ncp3);
intmin = 0.0;
intmax = 0.0;
Vector intminT(ncp2*nb);
Vector intmaxT(ncp2*nb);
// Get bounds for each slice of the solution
for (int i = 0; i < nb; i++)
{
Vector solcoeff(coeff.GetData()+i*nb2, nb2);
Vector intminrow(intminT.GetData()+i*ncp2, ncp2);
Vector intmaxrow(intmaxT.GetData()+i*ncp2, ncp2);
Get2DBounds(solcoeff, intminrow, intmaxrow);
}
DenseMatrix intminTM(intminT.GetData(), ncp2, nb),
intmaxTM(intmaxT.GetData(), ncp2, nb);
// Compute a0 and a1 for each tower of nodes
Vector a0V(ncp2), a1V(ncp2);
a0V = 0.0;
a1V = 0.0;
real_t x,w,t;
if (proj)
{
if (b_type == 2) // Bernstein bases
{
// Compute the mean coefficients along each tower.
for (int j = 0; j < ncp2; j++) // slice of interval points
{
Vector meanBounds(nb), minBounds(nb), maxBounds(nb);
intminTM.GetRow(j, minBounds);
intmaxTM.GetRow(j, maxBounds);
for (int i = 0; i < nb; i++) // column of nodes
{
meanBounds(i) = 0.5*(minBounds(i)+maxBounds(i));
}
Vector meanNodalIntVals(nb);
Vector minNodalVals(nb);
Vector maxNodalVals(nb);
Vector row(nb);
for (int i = 0; i < nb; i++)
{
basisMatNodes.GetRow(i, row);
minNodalVals(i) = row*minBounds;
maxNodalVals(i) = row*maxBounds;
basisMatInt.GetRow(i, row);
meanNodalIntVals(i) = row*meanBounds;
}
// linear fit along each tower
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes_int(i)-1; // x-coordinate
w = 2.0*weights_int(i); // weight
a0V(j) += 0.5*meanNodalIntVals(i)*w;
a1V(j) += 1.5*meanNodalIntVals(i)*w*x;
}
// offset the linear fit from bounding coefficients
for (int i = 0; i < nb; i++)
{
x = 2.0*nodes(i)-1; // x-coordinate
minBounds(i) -= a0V(j) + a1V(j)*x;
maxBounds(i) -= a0V(j) + a1V(j)*x;
}
// Compute Bernstein coefficients
LUFactors lu(basisMatLU.GetData(), lu_ip.GetData());
lu.Solve(nb, 1, minBounds.GetData());
lu.Solve(nb, 1, maxBounds.GetData());
for (int i = 0; i < nb; i++)
{
intminT(i*ncp2+j) = minBounds(i);
intmaxT(i*ncp2+j) = maxBounds(i);
}
}
}
else
{
// nodal bases
for (int j = 0; j < nb; j++) // tower of nodes
{
x = 2.0*nodes(j)-1; // x-coordinate
w = 2.0*weights(j); // weight
for (int i = 0; i < ncp2; i++) // slice of interval points
{
t = 0.5*(intminT(j*ncp2+i)+intmaxT(j*ncp2+i));
a0V(i) += 0.5*t*w;
a1V(i) += 1.5*t*w*x;
}
}
// offset the linear fit from nodal values
for (int j = 0; j < nb; j++) // row of nodes
{
x = 2.0*nodes(j)-1; // x-coordinate
for (int i = 0; i < ncp2; i++) // column of interval points
{
t = a0V(i) + a1V(i)*x;
intminT(j*ncp2+i) -= t;
intmaxT(j*ncp2+i) -= t;
}
}
}
// Initialize bounds using a0 and a1 values
for (int j = 0; j < ncp; j++) // slice j
{
x = 2.0*control_points(j)-1;
for (int i = 0; i < ncp2; i++) // tower i
{
intmin(j*ncp2+i) = a0V(i) + a1V(i)*x;
intmax(j*ncp2+i) = a0V(i) + a1V(i)*x;
}
}
}
// Compute bounds
int id1 = 0, id2 = 0;
Vector vals(4);
for (int j = 0; j < nb; j++)
{
for (int i = 0; i < ncp2; i++) // ith tower
{
real_t w0 = intminT(id1++);
real_t w1 = intmaxT(id2++);
for (int k = 0; k < ncp; k++) // kth slice
{
vals(0) = w0*lbound(j,k);
vals(1) = w0*ubound(j,k);
vals(2) = w1*lbound(j,k);
vals(3) = w1*ubound(j,k);
intmin(k*ncp2+i) += vals.Min();
intmax(k*ncp2+i) += vals.Max();
}
}
}
}
void PLBound::GetNDBounds(int rdim, Vector &coeff,
Vector &intmin, Vector &intmax) const
{
if (rdim == 1)
{
Get1DBounds(coeff, intmin, intmax);
}
else if (rdim == 2)
{
Get2DBounds(coeff, intmin, intmax);
}
else if (rdim == 3)
{
Get3DBounds(coeff, intmin, intmax);
}
else
{
MFEM_ABORT("Currently not supported.");
}
}
void PLBound::SetupBernsteinBasisMat(DenseMatrix &basisMat,
Vector &nodesBern) const
{
const int nbern = nodesBern.Size();
L2_SegmentElement el(nbern-1, 2); // we use L2 to leverage lexicographic order
Array<int> ordering = el.GetLexicographicOrdering();
basisMat.SetSize(nbern, nbern);
Vector shape(nbern);
IntegrationPoint ip;
for (int i = 0; i < nbern; i++)
{
ip.x = nodesBern(i);
el.CalcShape(ip, shape);
basisMat.SetRow(i, shape);
}
}
constexpr int PLBound::min_ncp_gl_x[2][11];
constexpr int PLBound::min_ncp_gll_x[2][11];
constexpr int PLBound::min_ncp_pos_x[2][11];
int PLBound::GetMinimumPointsForGivenBases(int nb_i, int b_type_i,
int cp_type_i) const
{
MFEM_VERIFY(b_type_i >= 0 && b_type_i <= 2, "Invalid node type. Specify 0 "
"for GL, 1 for GLL, and 2 for positive " "bases.");
MFEM_VERIFY(cp_type_i == 0 || cp_type_i == 1, "Invalid control point type. "
"Specify 0 for GL+end points, 1 for Chebyshev.");
if (nb_i > 12)
{
MFEM_ABORT("GetMinimumPointsForGivenBases can only be used for maximum "
"order = 11, i.e. nb=12. 2*nb points should be sufficient to "
"bound the bases up to nb = 30.");
}
else if (b_type_i == 0)
{
return min_ncp_gl_x[cp_type_i][nb_i-2];
}
else if (b_type_i == 1)
{
return min_ncp_gll_x[cp_type_i][nb_i-2];
}
else if (b_type_i == 2)
{
return min_ncp_pos_x[cp_type_i][nb_i-2];
}
return 0;
}
void PLBound::Print(std::ostream &outp) const
{
outp << "PLBound nb: " << nb << std::endl;
outp << "PLBound ncp: " << ncp << std::endl;
outp << "PLBound b_type: " << b_type << std::endl;
outp << "PLBound cp_type: " << cp_type << std::endl;
outp << "Print nodes: " << std::endl;
nodes.Print(outp);
outp << "Print weights: " << std::endl;
weights.Print(outp);
outp << "Print control_points: " << std::endl;
control_points.Print(outp);
outp << "Print lower bounds: " << std::endl;
lbound.Print(outp);
outp << "Print upper bounds: " << std::endl;
ubound.Print(outp);
}
}
+136
View File
@@ -0,0 +1,136 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_BOUND
#define MFEM_BOUND
#include "../config/config.hpp"
#include "fespace.hpp"
namespace mfem
{
/** @name Piecewise linear bounds of bases
\brief Piecewise linear bounds of bases can be used to compute bounds on the grid function in each element. The bounds for the bases are constructed based on the following parameters:
(i) @b nb: number of bases/nodes in 1D (i.e. polynomial order+1),
(ii) @b b_type: bases type, 0 - Lagrange interpolants on Gauss-Legendre nodes, 1 - Lagrange interpolants on Gauss-Lobatto-Legendre nodes, and
2 - Positive/Bernstein bases on uniformly distributed nodes,
(iii) @b ncp: number of control points used to construct the piecewise linear bounds
(iv) @b cp_type: control point distribution. 0 - GL + end-points,
1 - Chebyshev.
Note: @b nb and @b b_type are inferred directly from the grid-function.
If the user does not specify @b ncp and @b cp_type, the minimum value of
@b ncp is used that would bound the bases for the @b cp_type. We default
to @b cp_type = 0 as it requires fewer number of points to bound the bases. Typically, @b ncp = 2 @b nb is sufficient to get fairly compact bounds, and increasing @b ncp results in tighter bounds.
Finally, only tensor-product elements are currently supported.
For more technical details see:
Mittal et al., "General Field Evaluation in High-Order Meshes on GPUs" &
Dzanic et al., "A method for bounding high-order finite element
functions: Applications to mesh validity and bounds-preserving limiters".
*/
class PLBound
{
private:
int nb; // #mesh nodes in 1D
int ncp; // #control points in 1D
int b_type; // bases type: 0 - GL, 1 - GLL, 2 - Bernstein
int cp_type; // control points type: 0 - GL+Ends, 1 - Chebyshev
bool proj = true; // Use linear projection to compute bounds.
real_t tol = 0.0; // offset bounds to avoid round-off errors
Vector nodes, weights, control_points;
DenseMatrix lbound, ubound; // nb x ncp matrices with bounds of all bases
// Some auxillary storage for computing the bounds with Bernstein
DenseMatrix basisMatNodes; // Bernstein bases at equispaced nodes
DenseMatrix basisMatInt; // Bernstein bases at GLL nodes
Vector nodes_int, weights_int; // Integration nodes and weights
DenseMatrix basisMatLU; // Used to compute LU factors for Bernstein
mutable Array<int> lu_ip;
// stores min_ncp for nb = 2..12 for Lagrange interpolants on GL nodes
// with GL+end points and Chebyshev points as control points
static constexpr int min_ncp_gl_x[2][11]= {{3,5,6,8,9,10,11,11,12,13,14},
{3,5,8,9,11,12,14,15,17,18,20}
};
// stores min_ncp for nb = 2..12 for Lagrange interpolants on GLL nodes
// with GL+end points and Chebyshev points as control points
static constexpr int min_ncp_gll_x[2][11]= {{3,5,7,8,9,10,12,13,14,15,16},
{3,5,8,10,12,13,15,17,19,21,22}
};
// stores min_ncp for nb = 2..12 for Bernstein bases with GL+end points
// and Chebyshev points as control points
static constexpr int min_ncp_pos_x[2][11]= {{3,5,7,8,8,9,10,10,11,12,13},
{3,5,8,9,11,12,13,13,14,15,16}
};
public:
// Constructor
PLBound(const int nb_i, const int ncp_i, const int b_type_i,
const int cp_type_i, const real_t tol_i)
{
Setup(nb_i, ncp_i, b_type_i, cp_type_i, tol_i);
}
// Constructor
PLBound(FiniteElementSpace *fes, int ncp_i = -1, int cp_type_i = 0);
// Get minimum number of control points needed to bound the given bases
int GetMinimumPointsForGivenBases(int nb_i, int b_type_i,
int cp_type_i) const;
// Print information about the bounds
void Print(std::ostream &outp = mfem::out) const;
// Enable (default) or disable linear projection before bounding.
// This projection increases the computational cost but results in tighter
// bounds.
void SetProjectionFlagForBounding(bool proj_) { proj = proj_; }
/// Compute piecewise linear bounds for the lexicographically-ordered
/// coefficients in @a coeff in 1D/2D/3D.
void GetNDBounds(int rdim, Vector &coeff,
Vector &intmin, Vector &intmax) const;
/// Get number of control points used to compute the bounds.
int GetNControlPoints() const { return ncp; }
private:
/// Compute piecewise linear bounds for the lexicographically-ordered
/// coefficients in @a coeff in 1D.
void Get1DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const;
/// Compute piecewise linear bounds for the lexicographically-ordered
/// coefficients in @a coeff in 2D.
void Get2DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const;
/// Compute piecewise linear bounds for the lexicographically-ordered
/// coefficients in @a coeff in 3D.
void Get3DBounds(Vector &coeff, Vector &intmin, Vector &intmax) const;
/// Setup matrix used to compute values at given 1D locations in [0,1]
/// for Bernstein bases.
void SetupBernsteinBasisMat(DenseMatrix &basisMat, Vector &nodesBern) const;
void Setup(const int nb_i, const int ncp_i, const int b_type_i,
const int cp_type_i, const real_t tol_i);
};
} // namespace mfem
#endif // MFEM_BOUND
+54
View File
@@ -0,0 +1,54 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "doperator.hpp"
#ifdef MFEM_USE_MPI
using namespace mfem;
using namespace mfem::future;
void DifferentiableOperator::SetParameters(std::vector<Vector *> p) const
{
MFEM_ASSERT(parameters.size() == p.size(),
"number of parameters doesn't match descriptors");
for (size_t i = 0; i < parameters.size(); i++)
{
p[i]->Read();
parameters_l[i] = *p[i];
}
}
DifferentiableOperator::DifferentiableOperator(
const std::vector<FieldDescriptor> &solutions,
const std::vector<FieldDescriptor> &parameters,
const ParMesh &mesh) :
mesh(mesh),
solutions(solutions),
parameters(parameters)
{
fields.resize(solutions.size() + parameters.size());
fields_e.resize(fields.size());
solutions_l.resize(solutions.size());
parameters_l.resize(parameters.size());
for (size_t i = 0; i < solutions.size(); i++)
{
fields[i] = solutions[i];
}
for (size_t i = 0; i < parameters.size(); i++)
{
fields[i + solutions.size()] = parameters[i];
}
}
#endif // MFEM_USE_MPI
+796
View File
@@ -0,0 +1,796 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include <type_traits>
#include <utility>
#include "../../config/config.hpp"
#ifdef MFEM_USE_MPI
#include "../fespace.hpp"
#include "util.hpp"
#include "interpolate.hpp"
#include "integrate.hpp"
#include "qfunction_apply.hpp"
namespace mfem::future
{
/// @brief Type alias for a function that computes the action of an operator
using action_t =
std::function<void(std::vector<Vector> &, const std::vector<Vector> &, Vector &)>;
/// @brief Type alias for a function that computes the action of a derivative
using derivative_action_t =
std::function<void(std::vector<Vector> &, const Vector &, Vector &)>;
/// @brief Type alias for a function that assembles the sparse matrix of a
/// derivative operator
using assemble_derivative_hypreparmatrix_callback_t =
std::function<void(std::vector<Vector> &, HypreParMatrix &)>;
/// @brief Type alias for a function that applies the appropriate restriction to
/// the solution and parameters
using restriction_callback_t =
std::function<void(std::vector<Vector> &,
const std::vector<Vector> &,
std::vector<Vector> &)>;
/// Class representing the derivative (Jacobian) operator of a
/// DifferentiableOperator.
///
/// This class implements a derivative operator that computes directional
/// derivatives for a given set of solution and parameter fields. It supports
/// both forward and transpose operations, as well as assembly into sparse
/// matrices.
///
/// @note The derivative operator uses only forward mode differentiation in Mult
/// and MultTranspose. It does not support reverse mode differentiation. The
/// MultTranspose operation is achieved by using the transpose of the derivative
/// actions on each quadrature point.
///
/// @see DifferentiableOperator
class DerivativeOperator : public Operator
{
public:
/// Constructor for the DerivativeOperator class.
///
/// This is usually not called directly from a user. A DifferentiableOperator
/// calls this constructor when using
/// DifferentiableOperator::GetDerivative().
DerivativeOperator(
const int &height,
const int &width,
const std::vector<derivative_action_t> &derivative_actions,
const FieldDescriptor &direction,
const int &daction_l_size,
const std::vector<derivative_action_t> &derivative_actions_transpose,
const FieldDescriptor &transpose_direction,
const int &daction_transpose_l_size,
const std::vector<Vector *> &solutions_l,
const std::vector<Vector *> &parameters_l,
const restriction_callback_t &restriction_callback,
const std::function<void(Vector &, Vector &)> &prolongation_transpose,
const std::vector<assemble_derivative_hypreparmatrix_callback_t>
&assemble_derivative_hypreparmatrix_callbacks) :
Operator(height, width),
derivative_actions(derivative_actions),
direction(direction),
daction_l(daction_l_size),
daction_l_size(daction_l_size),
derivative_actions_transpose(derivative_actions_transpose),
transpose_direction(transpose_direction),
prolongation_transpose(prolongation_transpose),
assemble_derivative_hypreparmatrix_callbacks(
assemble_derivative_hypreparmatrix_callbacks)
{
std::vector<Vector> s_l(solutions_l.size());
for (size_t i = 0; i < s_l.size(); i++)
{
s_l[i] = *solutions_l[i];
}
std::vector<Vector> p_l(parameters_l.size());
for (size_t i = 0; i < p_l.size(); i++)
{
p_l[i] = *parameters_l[i];
}
fields_e.resize(solutions_l.size() + parameters_l.size());
restriction_callback(s_l, p_l, fields_e);
}
/// @brief Compute the action of the derivative operator on a given vector.
///
/// @param direction_t The direction vector in which to compute the
/// derivative. This has to be a T-dof vector.
/// @param result_t Result vector of the action of the derivative on
/// direction_t on T-dofs.
void Mult(const Vector &direction_t, Vector &result_t) const override
{
daction_l.SetSize(daction_l_size);
daction_l = 0.0;
prolongation(direction, direction_t, direction_l);
for (const auto &f : derivative_actions)
{
f(fields_e, direction_l, daction_l);
}
prolongation_transpose(daction_l, result_t);
};
/// @brief Compute the transpose of the derivative operator on a given
/// vector.
///
/// This function computes the transpose of the derivative operator on a
/// given vector by transposing the quadrature point local forward derivative
/// action. It does not use reverse mode automatic differentiation.
///
/// @param direction_t The direction vector in which to compute the
/// derivative. This has to be a T-dof vector.
/// @param result_t Result vector of the transpose action of the derivative on
/// direction_t on T-dofs.
void MultTranspose(const Vector &direction_t, Vector &result_t) const override
{
MFEM_ASSERT(!derivative_actions_transpose.empty(),
"derivative can't be used to be multiplied in transpose mode");
daction_l.SetSize(width);
daction_l = 0.0;
prolongation(transpose_direction, direction_t, direction_l);
for (const auto &f : derivative_actions_transpose)
{
f(fields_e, direction_l, daction_l);
}
prolongation_transpose(daction_l, result_t);
};
/// @brief Assemble the derivative operator into a HypreParMatrix.
///
/// @param A The HypreParMatrix to assemble the derivative operator into. Can
/// be an uninitialized object.
void Assemble(HypreParMatrix &A)
{
MFEM_ASSERT(!assemble_derivative_hypreparmatrix_callbacks.empty(),
"derivative can't be assembled into a matrix");
for (const auto &f : assemble_derivative_hypreparmatrix_callbacks)
{
f(fields_e, A);
}
}
private:
/// Derivative action callbacks. Depending on the requested derivatives in
/// DifferentiableOperator the callbacks represent certain combinations of
/// actions of derivatives of the forward operator.
std::vector<derivative_action_t> derivative_actions;
FieldDescriptor direction;
mutable Vector daction_l;
const int daction_l_size;
/// Transpose Derivative action callbacks. Depending on the requested
/// derivatives in DifferentiableOperator the callbacks represent certain
/// combinations of actions of derivatives of the forward operator.
std::vector<derivative_action_t> derivative_actions_transpose;
FieldDescriptor transpose_direction;
mutable std::vector<Vector> fields_e;
mutable Vector direction_l;
std::function<void(Vector &, Vector &)> prolongation_transpose;
/// Callbacks that assemble derivatives into a HypreParMatrix.
std::vector<assemble_derivative_hypreparmatrix_callback_t>
assemble_derivative_hypreparmatrix_callbacks;
};
/// Class representing a differentiable operator which acts on solution and
/// parameter fields to compute residuals.
///
/// This class provides functionality to define differentiable operators by
/// composing functions that compute values at quadrature points. It supports
/// automatic differentiation to compute derivatives with respect to solutions
/// (Jacobians) and parameter fields (general derivative operators).
///
/// The operator is constructed with solution fields that it will act on and
/// parameter fields that define coefficients. Quadrature functions are added by
/// e.g. using AddDomainIntegrator() which specify how the operator evaluates f
/// those functionas and parameters at quadrature points.
///
/// Derivatives can be computed by obtaining a DerivativeOperator using
/// GetDerivative().
///
/// @see DerivativeOperator
class DifferentiableOperator : public Operator
{
public:
/// Constructor for the DifferentiableOperator class.
///
/// @param solutions The solution fields that the operator will act on.
/// @param parameters The parameter fields that define coefficients.
/// @param mesh The mesh on which the operator is defined.
DifferentiableOperator(
const std::vector<FieldDescriptor> &solutions,
const std::vector<FieldDescriptor> &parameters,
const ParMesh &mesh);
/// @brief Compute the action of the operator on a given vector.
///
/// @param solutions_t The solution vector in which to compute the action.
/// This has to be a T-dof vector.
/// @param result_t Result vector of the action of the operator on
/// solutions_t. The result is a T-dof vector.
void Mult(const Vector &solutions_t, Vector &result_t) const override
{
MFEM_ASSERT(!action_callbacks.empty(), "no integrators have been set");
prolongation(solutions, solutions_t, solutions_l);
for (auto &action : action_callbacks)
{
action(solutions_l, parameters_l, residual_l);
}
prolongation_transpose(residual_l, result_t);
}
/// @brief Add a domain integrator to the operator.
///
/// @param qfunc The quadrature function to be added.
/// @param inputs Tuple of FieldOperators for the inputs of the quadrature
/// function.
/// @param outputs Tuple of FieldOperators for the outputs of the quadrature
/// function.
/// @param integration_rule IntegrationRule to use with this integrator.
/// @param domain_attributes Domain attributes marker array indicating over
/// which attributes this integrator will integrate over.
/// @param derivative_ids Derivatives to be made available for this
/// integrator.
template <
typename qfunc_t,
typename input_t,
typename output_t,
typename derivative_ids_t = decltype(std::make_index_sequence<0> {})>
void AddDomainIntegrator(
qfunc_t &qfunc,
input_t inputs,
output_t outputs,
const IntegrationRule &integration_rule,
const Array<int> &domain_attributes,
derivative_ids_t derivative_ids = std::make_index_sequence<0> {});
/// @brief Set the parameters for the operator.
///
/// This has to be called before using Mult() or MultTranspose().
///
/// @param p The parameters to be set. This should be a vector of pointers to
/// the parameter vectors. The vectors have to be L-vectors (e.g.
/// GridFunctions).
void SetParameters(std::vector<Vector *> p) const;
/// @brief Disable the use of tensor product structure.
///
/// This function disables the use of tensor product structure for the
/// operator. Usually, DifferentiableOperator creates callbacks based on
/// heuristics that achieve good performance for each element type. Some
/// functionality is not implemented for these performant algorithms but only
/// for generic assembly. Therefore the user can decide to use fallback
/// methods.
void DisableTensorProductStructure(bool disable = true)
{
use_tensor_product_structure = !disable;
}
/// @brief Get the derivative operator for a given derivative ID.
///
/// This function returns a shared pointer to a DerivativeOperator that
/// computes the derivative of the operator with respect to the given
/// derivative ID. The derivative ID is used to identify the specific
/// derivative action to be performed.
///
/// @param derivative_id The ID of the derivative to be computed.
/// @param sol_l The solution vectors to be used for the derivative
/// computation. This should be a vector of pointers to the solution
/// vectors. The vectors have to be L-vectors (e.g. GridFunctions).
/// @param par_l The parameter vectors to be used for the derivative
/// computation. This should be a vector of pointers to the parameter
/// vectors. The vectors have to be L-vectors (e.g. GridFunctions).
/// @return A shared pointer to the DerivativeOperator.
std::shared_ptr<DerivativeOperator> GetDerivative(
size_t derivative_id, std::vector<Vector *> sol_l, std::vector<Vector *> par_l)
{
MFEM_ASSERT(derivative_action_callbacks.find(derivative_id) !=
derivative_action_callbacks.end(),
"no derivative action has been found for ID " << derivative_id);
MFEM_ASSERT(sol_l.size() == solutions.size(),
"wrong number of solutions");
MFEM_ASSERT(par_l.size() == parameters.size(),
"wrong number of parameters");
const size_t derivative_idx = FindIdx(derivative_id, fields);
return std::make_shared<DerivativeOperator>(
height,
GetTrueVSize(fields[derivative_idx]),
derivative_action_callbacks[derivative_id],
fields[derivative_idx],
residual_l.Size(),
daction_transpose_callbacks[derivative_id],
fields[test_space_field_idx],
GetVSize(fields[test_space_field_idx]),
sol_l,
par_l,
restriction_callback,
prolongation_transpose,
assemble_derivative_hypreparmatrix_callbacks[derivative_id]);
}
private:
const ParMesh &mesh;
std::vector<action_t> action_callbacks;
std::map<size_t,
std::vector<derivative_action_t>> derivative_action_callbacks;
std::map<size_t,
std::vector<derivative_action_t>> daction_transpose_callbacks;
std::map<size_t,
std::vector<assemble_derivative_hypreparmatrix_callback_t>>
assemble_derivative_hypreparmatrix_callbacks;
std::vector<FieldDescriptor> solutions;
std::vector<FieldDescriptor> parameters;
// solutions and parameters
std::vector<FieldDescriptor> fields;
mutable std::vector<Vector> solutions_l;
mutable std::vector<Vector> parameters_l;
mutable Vector residual_l;
mutable std::vector<Vector> fields_e;
mutable Vector residual_e;
std::function<void(Vector &, Vector &)> prolongation_transpose;
std::function<void(Vector &, Vector &)> output_restriction_transpose;
restriction_callback_t restriction_callback;
std::map<size_t, size_t> assembled_vector_sizes;
bool use_tensor_product_structure = true;
size_t test_space_field_idx = SIZE_MAX;
};
template <
typename qfunc_t,
typename input_t,
typename output_t,
typename derivative_ids_t>
void DifferentiableOperator::AddDomainIntegrator(
qfunc_t &qfunc,
input_t inputs,
output_t outputs,
const IntegrationRule &integration_rule,
const Array<int> &domain_attributes,
derivative_ids_t derivative_ids)
{
using entity_t = Entity::Element;
static constexpr size_t num_inputs =
tuple_size<decltype(inputs)>::value;
static constexpr size_t num_outputs =
tuple_size<decltype(outputs)>::value;
using qf_signature =
typename create_function_signature<decltype(&qfunc_t::operator())>::type;
using qf_param_ts = typename qf_signature::parameter_ts;
using qf_output_t = typename qf_signature::return_t;
// Consistency checks
if constexpr (num_outputs > 1)
{
static_assert(dfem::always_false<qfunc_t>,
"more than one output per quadrature functions is not supported right now");
}
if constexpr (std::is_same_v<qf_output_t, void>)
{
static_assert(dfem::always_false<qfunc_t>,
"quadrature function has no return value");
}
constexpr size_t num_qfinputs = tuple_size<qf_param_ts>::value;
static_assert(num_qfinputs == num_inputs,
"quadrature function inputs and descriptor inputs have to match");
constexpr size_t num_qf_outputs = tuple_size<qf_output_t>::value;
static_assert(num_qf_outputs == num_outputs,
"quadrature function outputs and descriptor outputs have to match");
constexpr auto inout_tuple =
merge_mfem_tuples_as_empty_std_tuple(inputs, outputs);
constexpr auto filtered_inout_tuple = filter_fields(inout_tuple);
static constexpr size_t num_fields =
count_unique_field_ids(filtered_inout_tuple);
MFEM_ASSERT(num_fields == solutions.size() + parameters.size(),
"Total number of fields doesn't match sum of solutions and parameters."
" This indicates that some fields are not used in the integrator,"
" which currently is not supported.");
auto dependency_map = make_dependency_map(inputs);
// pretty_print(dependency_map);
auto input_to_field =
create_descriptors_to_fields_map<entity_t>(fields, inputs);
auto output_to_field =
create_descriptors_to_fields_map<entity_t>(fields, outputs);
// TODO: factor out
std::vector<int> inputs_vdim(num_inputs);
for_constexpr<num_inputs>([&](auto i)
{
inputs_vdim[i] = get<i>(inputs).vdim;
});
Array<int> elem_attributes;
elem_attributes.SetSize(mesh.GetNE());
for (int i = 0; i < mesh.GetNE(); ++i)
{
elem_attributes[i] = mesh.GetAttribute(i);
}
const auto output_fop = get<0>(outputs);
test_space_field_idx = FindIdx(output_fop.GetFieldId(), fields);
bool use_sum_factorization = false;
auto entity_element_type =
Element::TypeFromGeometry(mesh.GetTypicalElementGeometry());
if ((entity_element_type == Element::QUADRILATERAL ||
entity_element_type == Element::HEXAHEDRON) &&
use_tensor_product_structure == true)
{
use_sum_factorization = true;
}
ElementDofOrdering element_dof_ordering = ElementDofOrdering::NATIVE;
DofToQuad::Mode doftoquad_mode = DofToQuad::Mode::FULL;
if (use_sum_factorization)
{
element_dof_ordering = ElementDofOrdering::LEXICOGRAPHIC;
doftoquad_mode = DofToQuad::Mode::TENSOR;
}
auto [output_rt,
output_e_sz] = get_restriction_transpose<entity_t>
(fields[test_space_field_idx],
element_dof_ordering, output_fop);
auto &output_e_size = output_e_sz;
output_restriction_transpose = output_rt;
residual_e.SetSize(output_e_size);
// The explicit captures are necessary to avoid dependency on
// the specific instance of this class (this pointer).
restriction_callback =
[=, solutions = this->solutions, parameters = this->parameters]
(std::vector<Vector> &sol,
const std::vector<Vector> &par,
std::vector<Vector> &f)
{
restriction<entity_t>(solutions, sol, f,
element_dof_ordering);
restriction<entity_t>(parameters, par, f,
element_dof_ordering,
solutions.size());
};
prolongation_transpose = get_prolongation_transpose(
fields[test_space_field_idx], output_fop, mesh.GetComm());
const int dimension = mesh.Dimension();
[[maybe_unused]] const int num_elements = GetNumEntities<Entity::Element>(mesh);
const int num_entities = GetNumEntities<entity_t>(mesh);
const int num_qp = integration_rule.GetNPoints();
if constexpr (is_sum_fop<decltype(output_fop)>::value)
{
residual_l.SetSize(1);
height = 1;
}
else
{
const int residual_lsize = GetVSize(fields[test_space_field_idx]);
residual_l.SetSize(residual_lsize);
height = GetTrueVSize(fields[test_space_field_idx]);
}
// TODO: Is this a hack?
width = GetTrueVSize(fields[0]);
std::vector<const DofToQuad*> dtq;
for (const auto &field : fields)
{
dtq.emplace_back(GetDofToQuad<entity_t>(
field,
integration_rule,
doftoquad_mode));
}
const int q1d = (int)floor(std::pow(num_qp, 1.0/dimension) + 0.5);
const int residual_size_on_qp =
GetSizeOnQP<entity_t>(output_fop,
fields[test_space_field_idx]);
auto input_dtq_maps = create_dtq_maps<entity_t>(inputs, dtq, input_to_field);
auto output_dtq_maps = create_dtq_maps<entity_t>(outputs, dtq, output_to_field);
const int test_vdim = output_fop.vdim;
const int test_op_dim = output_fop.size_on_qp / output_fop.vdim;
const int num_test_dof =
num_entities ? (output_e_size / output_fop.vdim / num_entities) : 0;
auto ir_weights = Reshape(integration_rule.GetWeights().Read(), num_qp);
auto input_size_on_qp =
get_input_size_on_qp(inputs, std::make_index_sequence<num_inputs> {});
auto action_shmem_info =
get_shmem_info<entity_t, num_fields, num_inputs, num_outputs>
(input_dtq_maps, output_dtq_maps, fields, num_entities, inputs, num_qp,
input_size_on_qp, residual_size_on_qp, element_dof_ordering);
Vector shmem_cache(action_shmem_info.total_size);
// print_shared_memory_info(action_shmem_info);
ThreadBlocks thread_blocks;
if (dimension == 3)
{
if (use_sum_factorization)
{
thread_blocks.x = q1d;
thread_blocks.y = q1d;
thread_blocks.z = q1d;
}
}
else if (dimension == 2)
{
if (use_sum_factorization)
{
thread_blocks.x = q1d;
thread_blocks.y = q1d;
thread_blocks.z = 1;
}
}
action_callbacks.push_back(
// Explicitly capture everything we need, so we can make explicit choice
// how to capture every variable, by copy or by ref.
[
// capture by copy:
dimension, // int
num_entities, // int
num_test_dof, // int
num_qp, // int
q1d, // int
residual_size_on_qp, // int
test_vdim, // int (= output_fop.vdim)
test_op_dim, // int (derived from output_fop)
inputs, // mfem::future::tuple
domain_attributes, // Array<int>
ir_weights, // DeviceTensor
use_sum_factorization, // bool
input_dtq_maps, // std::array<DofToQuadMap, num_fields>
output_dtq_maps, // std::array<DofToQuadMap, num_fields>
input_to_field, // std::array<int, s>
output_fop, // class derived from FieldOperator
qfunc, // qfunc_t
thread_blocks, // ThreadBlocks
shmem_cache, // Vector (local)
action_shmem_info, // SharedMemoryInfo
// TODO: make this Array<int> a member of the DifferentiableOperator
// and capture it by ref.
elem_attributes, // Array<int>
// capture by ref:
&restriction_cb = this->restriction_callback,
&fields_e = this->fields_e,
&residual_e = this->residual_e,
&output_restriction_transpose = this->output_restriction_transpose
]
(std::vector<Vector> &sol, const std::vector<Vector> &par, Vector &res)
mutable // mutable: needed to modify 'shmem_cache'
{
restriction_cb(sol, par, fields_e);
residual_e = 0.0;
auto ye = Reshape(residual_e.ReadWrite(), test_vdim, num_test_dof, num_entities);
auto wrapped_fields_e = wrap_fields(fields_e,
action_shmem_info.field_sizes,
num_entities);
const bool has_attr = domain_attributes.Size() > 0;
const auto d_domain_attr = domain_attributes.Read();
const auto d_elem_attr = elem_attributes.Read();
forall([=] MFEM_HOST_DEVICE (int e, void *shmem)
{
if (has_attr && !d_domain_attr[d_elem_attr[e] - 1]) { return; }
auto [input_dtq_shmem, output_dtq_shmem, fields_shmem, input_shmem,
residual_shmem, scratch_shmem] =
unpack_shmem(shmem, action_shmem_info, input_dtq_maps, output_dtq_maps,
wrapped_fields_e, num_qp, e);
map_fields_to_quadrature_data(
input_shmem, fields_shmem, input_dtq_shmem, input_to_field, inputs, ir_weights,
scratch_shmem, dimension, use_sum_factorization);
call_qfunction<qf_param_ts>(
qfunc, input_shmem, residual_shmem,
residual_size_on_qp, num_qp, q1d, dimension, use_sum_factorization);
auto fhat = Reshape(&residual_shmem(0, 0), test_vdim, test_op_dim, num_qp);
auto y = Reshape(&ye(0, 0, e), num_test_dof, test_vdim);
map_quadrature_data_to_fields(
y, fhat, output_fop, output_dtq_shmem[0],
scratch_shmem, dimension, use_sum_factorization);
}, num_entities, thread_blocks, action_shmem_info.total_size, shmem_cache.ReadWrite());
output_restriction_transpose(residual_e, res);
});
// Without this compile-time check, some valid instantiations of this method
// will fail.
if constexpr (derivative_ids_t::size() != 0)
{
// Create the action of the derivatives
for_constexpr([&, &or_transpose =
this->output_restriction_transpose](const std::size_t derivative_id)
{
const size_t d_field_idx = FindIdx(derivative_id, fields);
const auto direction = fields[d_field_idx];
const int da_size_on_qp =
GetSizeOnQP<entity_t>(output_fop, fields[test_space_field_idx]);
auto shmem_info =
get_shmem_info<entity_t, num_fields, num_inputs, num_outputs>(
input_dtq_maps, output_dtq_maps, fields, num_entities, inputs,
num_qp, input_size_on_qp, residual_size_on_qp,
element_dof_ordering, d_field_idx);
Vector shmem_cache(shmem_info.total_size);
// print_shared_memory_info(shmem_info);
Vector direction_e;
Vector derivative_action_e(output_e_size);
derivative_action_e = 0.0;
// Lookup the derivative_id key in the dependency map
auto it = dependency_map.find(derivative_id);
if (it == dependency_map.end())
{
MFEM_ABORT("Derivative ID not found in dependency map");
}
const auto input_is_dependent = it->second;
derivative_action_callbacks[derivative_id].push_back(
[
// capture by copy:
dimension, // int
num_entities, // int
num_test_dof, // int
num_qp, // int
q1d, // int
test_vdim, // int (= output_fop.vdim)
test_op_dim, // int (derived from output_fop)
inputs, // mfem::future::tuple
domain_attributes, // Array<int>
ir_weights, // DeviceTensor
use_sum_factorization, // bool
input_dtq_maps, // std::array<DofToQuadMap, num_fields>
output_dtq_maps, // std::array<DofToQuadMap, num_fields>
input_to_field, // std::array<int, s>
output_fop, // class derived from FieldOperator
qfunc, // qfunc_t
thread_blocks, // ThreadBlocks
shmem_cache, // Vector (local)
shmem_info, // SharedMemoryInfo
// TODO: make this Array<int> a member of the DifferentiableOperator
// and capture it by ref.
elem_attributes, // Array<int>
input_is_dependent, // std::array<bool, num_inputs>
direction, // FieldDescriptor
direction_e, // Vector
derivative_action_e, // Vector
element_dof_ordering, // ElementDofOrdering
da_size_on_qp, // int
// capture by ref:
&or_transpose
](
std::vector<Vector> &f_e, const Vector &dir_l,
Vector &der_action_l) mutable
{
restriction<entity_t>(direction, dir_l, direction_e,
element_dof_ordering);
auto ye = Reshape(derivative_action_e.ReadWrite(), num_test_dof,
test_vdim, num_entities);
auto wrapped_fields_e = wrap_fields(f_e, shmem_info.field_sizes,
num_entities);
auto wrapped_direction_e = Reshape(direction_e.ReadWrite(),
shmem_info.direction_size,
num_entities);
const auto d_elem_attr = elem_attributes.Read();
const bool has_attr = domain_attributes.Size() > 0;
const auto d_domain_attr = domain_attributes.Read();
derivative_action_e = 0.0;
forall([=] MFEM_HOST_DEVICE (int e, real_t *shmem)
{
if (has_attr && !d_domain_attr[d_elem_attr[e] - 1]) { return; }
auto [input_dtq_shmem, output_dtq_shmem, fields_shmem,
direction_shmem, input_shmem,
shadow_shmem_, residual_shmem,
scratch_shmem] =
unpack_shmem(shmem, shmem_info, input_dtq_maps, output_dtq_maps,
wrapped_fields_e, wrapped_direction_e, num_qp, e);
auto &shadow_shmem = shadow_shmem_;
map_fields_to_quadrature_data(
input_shmem, fields_shmem, input_dtq_shmem, input_to_field,
inputs, ir_weights, scratch_shmem, dimension,
use_sum_factorization);
// TODO: Probably redundant
set_zero(shadow_shmem);
map_direction_to_quadrature_data_conditional(
shadow_shmem, direction_shmem, input_dtq_shmem, inputs,
ir_weights, scratch_shmem, input_is_dependent, dimension,
use_sum_factorization);
call_qfunction_derivative_action<qf_param_ts>(
qfunc, input_shmem, shadow_shmem, residual_shmem,
da_size_on_qp, num_qp, q1d, dimension, use_sum_factorization);
auto fhat = Reshape(&residual_shmem(0, 0), test_vdim,
test_op_dim, num_qp);
auto y = Reshape(&ye(0, 0, e), num_test_dof, test_vdim);
map_quadrature_data_to_fields(
y, fhat, output_fop, output_dtq_shmem[0],
scratch_shmem, dimension, use_sum_factorization);
}, num_entities, thread_blocks, shmem_info.total_size,
shmem_cache.ReadWrite());
or_transpose(derivative_action_e, der_action_l);
});
}, derivative_ids);
}
}
} // namespace mfem::future
#endif
+144
View File
@@ -0,0 +1,144 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include <type_traits>
namespace mfem::future
{
/// @brief Base class for FieldOperators.
///
/// This class serves as a base for different FieldOperator types which can be
/// applied to fields that are used with inputs to a quadrature point function.
/// See DifferentialOperator.
template <int FIELD_ID = -1>
class FieldOperator
{
public:
/// @brief Constructor for the FieldOperator.
///
/// This constructor initializes the FieldOperator with it's size on
/// quadrature points. The size on quadrature points has to be determined by
/// the FieldOperator type, the dimension and the vector dimension (number
/// of components). See the following examples
///
/// Scalar FiniteElementSpace with Value FieldOperator:
/// size = vdim x dim x 1 = 1 x dim x 1 = dim
///
/// Vector FiniteElementSpace with Gradient FieldOperator:
/// size = vdim x dim x dim = vdim x dim x dim = vdim * dim^2
///
/// ParameterSpace with Identity FieldOperator:
/// size = vdim = vdim
constexpr FieldOperator(int size_on_qp = 0) :
size_on_qp(size_on_qp) {};
/// @brief Get the field id this FieldOperator is attached to.
static constexpr int GetFieldId() { return FIELD_ID; }
/// @brief Get the size on quadrature point for this FieldOperator.
int size_on_qp = -1;
/// @brief Get the dimension of the FieldOperator.
int dim = -1;
/// @brief Get the vector dimension (number of components)
/// of the FieldOperator.
int vdim = -1;
};
/// @brief Identity FieldOperator.
///
/// This FieldOperator does nothing to the field. The field (usually a
/// ParametricFunction) transfers the values to the quadrature point data and
/// Identity can be viewed as an identity operation.
template <int FIELD_ID = -1>
class Identity : public FieldOperator<FIELD_ID>
{
public:
constexpr Identity() : FieldOperator<FIELD_ID>() {}
};
template< typename T >
struct is_identity_fop : std::false_type {};
template <int FIELD_ID>
struct is_identity_fop<Identity<FIELD_ID>> : std::true_type {};
/// @brief Weight FieldOperator.
///
/// This FieldOperator is used to signal that this field contains the quadrature
/// point weights.
class Weight : public FieldOperator<-1>
{
public:
constexpr Weight() : FieldOperator<-1>() {};
};
template< typename T >
struct is_weight_fop : std::false_type {};
template <>
struct is_weight_fop<Weight> : std::true_type {};
/// @brief Value FieldOperator.
///
/// This FieldOperator is used to signal that the field contains the
/// interpolated values of the degrees of freedom at the quadrature points.
template <int FIELD_ID = -1>
class Value : public FieldOperator<FIELD_ID>
{
public:
constexpr Value() : FieldOperator<FIELD_ID>() {};
};
template< typename T >
struct is_value_fop : std::false_type {};
template <int FIELD_ID>
struct is_value_fop<Value<FIELD_ID>> : std::true_type {};
/// @brief Gradient FieldOperator.
///
/// This FieldOperator is used to signal that the field contains the
/// interpolated gradients of the degrees of freedom at the quadrature points.
template <int FIELD_ID = -1>
class Gradient : public FieldOperator<FIELD_ID>
{
public:
constexpr Gradient() : FieldOperator<FIELD_ID>() {};
};
template< typename T >
struct is_gradient_fop : std::false_type {};
template <int FIELD_ID>
struct is_gradient_fop<Gradient<FIELD_ID>> : std::true_type {};
/// @brief Sum FieldOperator.
///
/// This FieldOperator is commonly used to signal that an output of a quadrature
/// function should be summed.
template <int FIELD_ID = -1>
class Sum : public FieldOperator<FIELD_ID>
{
public:
constexpr Sum() : FieldOperator<FIELD_ID>() {};
};
template< typename T >
struct is_sum_fop : std::false_type {};
template <int FIELD_ID>
struct is_sum_fop<Sum<FIELD_ID>> : std::true_type {};
} // namespace mfem::future
+450
View File
@@ -0,0 +1,450 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include "util.hpp"
namespace mfem::future
{
template <typename output_t>
MFEM_HOST_DEVICE
void map_quadrature_data_to_fields_impl(
DeviceTensor<2, real_t> &y,
const DeviceTensor<3, real_t> &f,
const output_t &output,
const DofToQuadMap &dtq)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
// assuming the quadrature point residual has to "play nice with
// the test function"
if constexpr (is_value_fop<std::decay_t<output_t>>::value)
{
const auto [num_qp, cdim, num_dof] = B.GetShape();
const int vdim = output.vdim > 0 ? output.vdim : cdim ;
for (int dof = 0; dof < num_dof; dof++)
{
for (int vd = 0; vd < vdim; vd++)
{
real_t acc = 0.0;
for (int qp = 0; qp < num_qp; qp++)
{
acc += B(qp, 0, dof) * f(vd, 0, qp);
}
y(dof, vd) += acc;
}
}
}
else if constexpr (
is_gradient_fop<std::decay_t<output_t>>::value)
{
const auto [num_qp, dim, num_dof] = G.GetShape();
const int vdim = output.vdim;
for (int dof = 0; dof < num_dof; dof++)
{
for (int vd = 0; vd < vdim; vd++)
{
real_t acc = 0.0;
for (int d = 0; d < dim; d++)
{
for (int qp = 0; qp < num_qp; qp++)
{
acc += G(qp, d, dof) * f(vd, d, qp);
}
}
y(dof, vd) += acc;
}
}
}
else if constexpr (is_sum_fop<std::decay_t<output_t>>::value)
{
// This is the "integral over all quadrature points type" applying
// B = 1 s.t. B^T * C \in R^1.
const auto [num_qp, unused, unused1] = B.GetShape();
auto cc = Reshape(&f(0, 0, 0), num_qp);
for (int i = 0; i < num_qp; i++)
{
y(0, 0) += cc(i);
}
}
else if constexpr (is_identity_fop<std::decay_t<output_t>>::value)
{
const auto [num_qp, unused, num_dof] = B.GetShape();
const auto vdim = output.vdim;
auto cc = Reshape(&f(0, 0, 0), num_qp * vdim);
auto yy = Reshape(&y(0, 0), num_qp * vdim);
for (int i = 0; i < num_qp * vdim; i++)
{
yy(i) = cc(i);
}
}
else
{
MFEM_ABORT("quadrature data mapping to field is not implemented for"
" this field descriptor");
}
}
template <typename output_t>
MFEM_HOST_DEVICE
void map_quadrature_data_to_fields_tensor_impl_2d(
DeviceTensor<2, real_t> &y,
const DeviceTensor<3, real_t> &f,
const output_t &output,
const DofToQuadMap &dtq,
std::array<DeviceTensor<1>, 6> &scratch_mem)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
if constexpr (is_value_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
const int vdim = output.vdim;
const int test_dim = output.size_on_qp / vdim;
auto fqp = Reshape(&f(0, 0, 0), vdim, test_dim, q1d, q1d);
auto yd = Reshape(&y(0, 0), d1d, d1d, vdim);
auto s0 = Reshape(&scratch_mem[0](0), q1d, d1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t acc = 0.0;
for (int qx = 0; qx < q1d; qx++)
{
acc += fqp(vd, 0, qx, qy) * B(qx, 0, dx);
}
s0(qy, dx) = acc;
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t acc = 0.0;
for (int qy = 0; qy < q1d; qy++)
{
acc += s0(qy, dx) * B(qy, 0, dy);
}
yd(dx, dy, vd) += acc;
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (is_gradient_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = G.GetShape();
const int vdim = output.vdim;
const int test_dim = output.size_on_qp / vdim;
auto fqp = Reshape(&f(0, 0, 0), vdim, test_dim, q1d, q1d);
auto yd = Reshape(&y(0, 0), d1d, d1d, vdim);
auto s0 = Reshape(&scratch_mem[0](0), q1d, d1d);
auto s1 = Reshape(&scratch_mem[1](0), q1d, d1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t uv[2] = {0.0, 0.0};
for (int qx = 0; qx < q1d; qx++)
{
uv[0] += fqp(vd, 0, qx, qy) * G(qx, 0, dx);
uv[1] += fqp(vd, 1, qx, qy) * B(qx, 0, dx);
}
s0(qy, dx) = uv[0];
s1(qy, dx) = uv[1];
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t uv[2] = {0.0, 0.0};
for (int qy = 0; qy < q1d; qy++)
{
uv[0] += s0(qy, dx) * B(qy, 0, dy);
uv[1] += s1(qy, dx) * G(qy, 0, dy);
}
yd(dx, dy, vd) += uv[0] + uv[1];
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (is_identity_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
// // TODO: Check if this is the right fix for all cases
// auto fqp = Reshape(&f(0, 0, 0), output.size_on_qp, q1d);
// auto yqp = Reshape(&y(0, 0), output.size_on_qp, q1d);
// for (int sq = 0; sq < output.size_on_qp; sq++)
// {
// MFEM_FOREACH_THREAD(qx, x, q1d)
// {
// yqp(sq, qx) = fqp(sq, qx);
// }
// MFEM_SYNC_THREAD;
// }
auto fqp = Reshape(&f(0, 0, 0), output.size_on_qp, q1d, q1d);
auto yqp = Reshape(&y(0, 0), output.size_on_qp, q1d, q1d);
for (int sq = 0; sq < output.size_on_qp; sq++)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
yqp(sq, qx, qy) = fqp(sq, qx, qy);
}
}
MFEM_SYNC_THREAD;
}
}
else
{
MFEM_ABORT("quadrature data mapping to field is not implemented for"
" this field descriptor with sum factorization on tensor product elements");
}
}
template <typename output_t>
MFEM_HOST_DEVICE
void map_quadrature_data_to_fields_tensor_impl_3d(
DeviceTensor<2, real_t> &y,
const DeviceTensor<3, real_t> &f,
const output_t &output,
const DofToQuadMap &dtq,
std::array<DeviceTensor<1>, 6> &scratch_mem)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
if constexpr (is_value_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
const int vdim = output.vdim;
const int test_dim = output.size_on_qp / vdim;
auto fqp = Reshape(&f(0, 0, 0), vdim, test_dim, q1d, q1d, q1d);
auto yd = Reshape(&y(0, 0), d1d, d1d, d1d, vdim);
auto s0 = Reshape(&scratch_mem[0](0), q1d, q1d, d1d);
auto s1 = Reshape(&scratch_mem[1](0), q1d, d1d, d1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
real_t acc = 0.0;
for (int qx = 0; qx < q1d; qx++)
{
acc += fqp(vd, 0, qx, qy, qz) * B(qx, 0, dx);
}
s0(qz, qy, dx) = acc;
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
real_t acc = 0.0;
for (int qy = 0; qy < q1d; qy++)
{
acc += s0(qz, qy, dx) * B(qy, 0, dy);
}
s1(qz, dy, dx) = acc;
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
MFEM_FOREACH_THREAD(dz, z, d1d)
{
real_t acc = 0.0;
for (int qz = 0; qz < q1d; qz++)
{
acc += s1(qz, dy, dx) * B(qz, 0, dz);
}
yd(dx, dy, dz, vd) += acc;
}
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (is_gradient_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = G.GetShape();
const int vdim = output.vdim;
const int test_dim = output.size_on_qp / vdim;
auto fqp = Reshape(&f(0, 0, 0), vdim, test_dim, q1d, q1d, q1d);
auto yd = Reshape(&y(0, 0), d1d, d1d, d1d, vdim);
auto s0 = Reshape(&scratch_mem[0](0), q1d, q1d, d1d);
auto s1 = Reshape(&scratch_mem[1](0), q1d, q1d, d1d);
auto s2 = Reshape(&scratch_mem[2](0), q1d, q1d, d1d);
auto s3 = Reshape(&scratch_mem[3](0), q1d, d1d, d1d);
auto s4 = Reshape(&scratch_mem[4](0), q1d, d1d, d1d);
auto s5 = Reshape(&scratch_mem[5](0), q1d, d1d, d1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t uvw[3] = {0.0, 0.0, 0.0};
for (int qx = 0; qx < q1d; qx++)
{
uvw[0] += fqp(vd, 0, qx, qy, qz) * G(qx, 0, dx);
uvw[1] += fqp(vd, 1, qx, qy, qz) * B(qx, 0, dx);
uvw[2] += fqp(vd, 2, qx, qy, qz) * B(qx, 0, dx);
}
s0(qz, qy, dx) = uvw[0];
s1(qz, qy, dx) = uvw[1];
s2(qz, qy, dx) = uvw[2];
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(qz, z, q1d)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t uvw[3] = {0.0, 0.0, 0.0};
for (int qy = 0; qy < q1d; qy++)
{
uvw[0] += s0(qz, qy, dx) * B(qy, 0, dy);
uvw[1] += s1(qz, qy, dx) * G(qy, 0, dy);
uvw[2] += s2(qz, qy, dx) * B(qy, 0, dy);
}
s3(qz, dy, dx) = uvw[0];
s4(qz, dy, dx) = uvw[1];
s5(qz, dy, dx) = uvw[2];
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dz, z, d1d)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(dx, x, d1d)
{
real_t uvw[3] = {0.0, 0.0, 0.0};
for (int qz = 0; qz < q1d; qz++)
{
uvw[0] += s3(qz, dy, dx) * B(qz, 0, dz);
uvw[1] += s4(qz, dy, dx) * B(qz, 0, dz);
uvw[2] += s5(qz, dy, dx) * G(qz, 0, dz);
}
yd(dx, dy, dz, vd) += uvw[0] + uvw[1] + uvw[2];
}
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (is_identity_fop<std::decay_t<output_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
auto fqp = Reshape(&f(0, 0, 0), output.size_on_qp, q1d, q1d, q1d);
auto yqp = Reshape(&y(0, 0), output.size_on_qp, q1d, q1d, q1d);
for (int sq = 0; sq < output.size_on_qp; sq++)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
yqp(sq, qx, qy, qz) = fqp(sq, qx, qy, qz);
}
}
}
MFEM_SYNC_THREAD;
}
}
else
{
MFEM_ABORT("quadrature data mapping to field is not implemented for"
" this field descriptor with sum factorization on tensor product elements");
}
}
template <typename output_t>
MFEM_HOST_DEVICE
void map_quadrature_data_to_fields(
DeviceTensor<2, real_t> &y,
const DeviceTensor<3, real_t> &f,
const output_t &output,
const DofToQuadMap &dtq,
std::array<DeviceTensor<1>, 6> &scratch_mem,
const int &dimension,
const bool &use_sum_factorization)
{
if (use_sum_factorization)
{
if (dimension == 2)
{
map_quadrature_data_to_fields_tensor_impl_2d(y, f, output, dtq, scratch_mem);
}
else if (dimension == 3)
{
map_quadrature_data_to_fields_tensor_impl_3d(y, f, output, dtq, scratch_mem);
}
else { MFEM_ABORT_KERNEL("dimension not supported"); }
}
else
{
map_quadrature_data_to_fields_impl(y, f, output, dtq);
}
}
} // namespace mfem::future
+573
View File
@@ -0,0 +1,573 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include "util.hpp"
namespace mfem::future
{
template <typename field_operator_t>
MFEM_HOST_DEVICE inline
void map_field_to_quadrature_data_tensor_product_3d(
DeviceTensor<2> &field_qp,
const DofToQuadMap &dtq,
const DeviceTensor<1> &field_e,
const field_operator_t &input,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
if constexpr (is_value_fop<std::decay_t<field_operator_t>>::value)
{
auto [q1d, unused, d1d] = B.GetShape();
const int vdim = input.vdim;
const auto field = Reshape(&field_e[0], d1d, d1d, d1d, vdim);
auto fqp = Reshape(&field_qp[0], vdim, q1d, q1d, q1d);
auto s0 = Reshape(&scratch_mem[0](0), d1d, d1d, q1d);
auto s1 = Reshape(&scratch_mem[1](0), d1d, q1d, q1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(dz, z, d1d)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t acc = 0.0;
for (int dx = 0; dx < d1d; dx++)
{
acc += B(qx, 0, dx) * field(dx, dy, dz, vd);
}
s0(dz, dy, qx) = acc;
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dz, z, d1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
real_t acc = 0.0;
for (int dy = 0; dy < d1d; dy++)
{
acc += s0(dz, dy, qx) * B(qy, 0, dy);
}
s1(dz, qy, qx) = acc;
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(qz, z, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t acc = 0.0;
for (int dz = 0; dz < d1d; dz++)
{
acc += s1(dz, qy, qx) * B(qz, 0, dz);
}
fqp(vd, qx, qy, qz) = acc;
}
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (
is_gradient_fop<std::decay_t<field_operator_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
const int vdim = input.vdim;
const int dim = input.dim;
const auto field = Reshape(&field_e[0], d1d, d1d, d1d, vdim);
auto fqp = Reshape(&field_qp[0], vdim, dim, q1d, q1d, q1d);
auto s0 = Reshape(&scratch_mem[0](0), d1d, d1d, q1d);
auto s1 = Reshape(&scratch_mem[1](0), d1d, d1d, q1d);
auto s2 = Reshape(&scratch_mem[2](0), d1d, q1d, q1d);
auto s3 = Reshape(&scratch_mem[3](0), d1d, q1d, q1d);
auto s4 = Reshape(&scratch_mem[4](0), d1d, q1d, q1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(dz, z, d1d)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t uv[2] = {0.0, 0.0};
for (int dx = 0; dx < d1d; dx++)
{
const real_t f = field(dx, dy, dz, vd);
uv[0] += f * B(qx, 0, dx);
uv[1] += f * G(qx, 0, dx);
}
s0(dz, dy, qx) = uv[0];
s1(dz, dy, qx) = uv[1];
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(dz, z, d1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t uvw[3] = {0.0, 0.0, 0.0};
for (int dy = 0; dy < d1d; dy++)
{
const real_t s0i = s0(dz, dy, qx);
uvw[0] += s1(dz, dy, qx) * B(qy, 0, dy);
uvw[1] += s0i * G(qy, 0, dy);
uvw[2] += s0i * B(qy, 0, dy);
}
s2(dz, qy, qx) = uvw[0];
s3(dz, qy, qx) = uvw[1];
s4(dz, qy, qx) = uvw[2];
}
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(qz, z, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t uvw[3] = {0.0, 0.0, 0.0};
for (int dz = 0; dz < d1d; dz++)
{
uvw[0] += s2(dz, qy, qx) * B(qz, 0, dz);
uvw[1] += s3(dz, qy, qx) * B(qz, 0, dz);
uvw[2] += s4(dz, qy, qx) * G(qz, 0, dz);
}
fqp(vd, 0, qx, qy, qz) = uvw[0];
fqp(vd, 1, qx, qy, qz) = uvw[1];
fqp(vd, 2, qx, qy, qz) = uvw[2];
}
}
}
MFEM_SYNC_THREAD;
}
}
// TODO: Create separate function for clarity
else if constexpr (
std::is_same_v<std::decay_t<field_operator_t>, Weight>)
{
const int num_qp = integration_weights.GetShape()[0];
// TODO: eeek
const int q1d = (int)floor(std::pow(num_qp, 1.0/input.dim) + 0.5);
auto w = Reshape(&integration_weights[0], q1d, q1d, q1d);
auto f = Reshape(&field_qp[0], q1d, q1d, q1d);
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
f(qx, qy, qz) = w(qx, qy, qz);
}
}
}
MFEM_SYNC_THREAD;
}
else if constexpr (is_identity_fop<std::decay_t<field_operator_t>>::value)
{
const int q1d = B.GetShape()[0];
auto field = Reshape(&field_e[0], input.size_on_qp, q1d * q1d * q1d);
field_qp = field;
}
else
{
static_assert(dfem::always_false<std::decay_t<field_operator_t>>,
"can't map field to quadrature data");
}
}
template <typename field_operator_t>
MFEM_HOST_DEVICE inline
void map_field_to_quadrature_data_tensor_product_2d(
DeviceTensor<2> &field_qp,
const DofToQuadMap &dtq,
const DeviceTensor<1> &field_e,
const field_operator_t &input,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
if constexpr (is_value_fop<std::decay_t<field_operator_t>>::value)
{
auto [q1d, unused, d1d] = B.GetShape();
const int vdim = input.vdim;
const auto field = Reshape(&field_e[0], d1d, d1d, vdim);
auto fqp = Reshape(&field_qp[0], vdim, q1d, q1d);
auto s0 = Reshape(&scratch_mem[0](0), d1d, q1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t acc = 0.0;
for (int dx = 0; dx < d1d; dx++)
{
acc += B(qx, 0, dx) * field(dx, dy, vd);
}
s0(dy, qx) = acc;
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
real_t acc = 0.0;
for (int dy = 0; dy < d1d; dy++)
{
acc += s0(dy, qx) * B(qy, 0, dy);
}
fqp(vd, qx, qy) = acc;
}
}
MFEM_SYNC_THREAD;
}
}
else if constexpr (
is_gradient_fop<std::decay_t<field_operator_t>>::value)
{
const auto [q1d, unused, d1d] = B.GetShape();
const int vdim = input.vdim;
const int dim = input.dim;
const auto field = Reshape(&field_e[0], d1d, d1d, vdim);
auto fqp = Reshape(&field_qp[0], vdim, dim, q1d, q1d);
auto s0 = Reshape(&scratch_mem[0](0), d1d, q1d);
auto s1 = Reshape(&scratch_mem[1](0), d1d, q1d);
for (int vd = 0; vd < vdim; vd++)
{
MFEM_FOREACH_THREAD(dy, y, d1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t uv[2] = {0.0, 0.0};
for (int dx = 0; dx < d1d; dx++)
{
const real_t f = field(dx, dy, vd);
uv[0] += f * B(qx, 0, dx);
uv[1] += f * G(qx, 0, dx);
}
s0(dy, qx) = uv[0];
s1(dy, qx) = uv[1];
}
}
MFEM_SYNC_THREAD;
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
real_t uv[2] = {0.0, 0.0};
for (int dy = 0; dy < d1d; dy++)
{
const real_t s0i = s0(dy, qx);
uv[0] += s1(dy, qx) * B(qy, 0, dy);
uv[1] += s0i * G(qy, 0, dy);
}
fqp(vd, 0, qx, qy) = uv[0];
fqp(vd, 1, qx, qy) = uv[1];
}
}
MFEM_SYNC_THREAD;
}
}
// TODO: Create separate function for clarity
else if constexpr (
std::is_same_v<std::decay_t<field_operator_t>, Weight>)
{
const int num_qp = integration_weights.GetShape()[0];
// TODO: eeek
const int q1d = (int)floor(std::pow(num_qp, 1.0/input.dim) + 0.5);
auto w = Reshape(&integration_weights[0], q1d, q1d);
auto f = Reshape(&field_qp[0], q1d, q1d);
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
f(qx, qy) = w(qx, qy);
}
}
MFEM_SYNC_THREAD;
}
else if constexpr (is_identity_fop<std::decay_t<field_operator_t>>::value)
{
const int q1d = B.GetShape()[0];
auto field = Reshape(&field_e[0], input.size_on_qp, q1d * q1d);
field_qp = field;
}
else
{
static_assert(dfem::always_false<std::decay_t<field_operator_t>>,
"can't map field to quadrature data");
}
}
template <typename field_operator_t>
MFEM_HOST_DEVICE
void map_field_to_quadrature_data(
DeviceTensor<2> field_qp,
const DofToQuadMap &dtq,
const DeviceTensor<1> &field_e,
const field_operator_t &input,
const DeviceTensor<1, const real_t> &integration_weights)
{
[[maybe_unused]] auto B = dtq.B;
[[maybe_unused]] auto G = dtq.G;
if constexpr (is_value_fop<field_operator_t>::value)
{
auto [num_qp, dim, num_dof] = B.GetShape();
const int vdim = input.vdim;
const auto field = Reshape(&field_e(0), num_dof, vdim);
for (int vd = 0; vd < vdim; vd++)
{
for (int qp = 0; qp < num_qp; qp++)
{
real_t acc = 0.0;
for (int dof = 0; dof < num_dof; dof++)
{
acc += B(qp, 0, dof) * field(dof, vd);
}
field_qp(vd, qp) = acc;
}
}
}
else if constexpr (is_gradient_fop<field_operator_t>::value)
{
const auto [num_qp, dim, num_dof] = G.GetShape();
const int vdim = input.vdim;
const auto field = Reshape(&field_e(0), num_dof, vdim);
auto f = Reshape(&field_qp[0], vdim, dim, num_qp);
for (int vd = 0; vd < vdim; vd++)
{
for (int qp = 0; qp < num_qp; qp++)
{
for (int d = 0; d < dim; d++)
{
real_t acc = 0.0;
for (int dof = 0; dof < num_dof; dof++)
{
acc += G(qp, d, dof) * field(dof, vd);
}
f(vd, d, qp) = acc;
}
}
}
}
else if constexpr (std::is_same_v<field_operator_t, Weight>)
{
const int num_qp = integration_weights.GetShape()[0];
auto f = Reshape(&field_qp[0], num_qp);
for (int qp = 0; qp < num_qp; qp++)
{
f(qp) = integration_weights(qp);
}
}
else if constexpr (is_identity_fop<field_operator_t>::value)
{
auto [num_qp, unused, num_dof] = B.GetShape();
const int size_on_qp = input.size_on_qp;
const auto field = Reshape(&field_e[0], size_on_qp * num_qp);
auto f = Reshape(&field_qp[0], size_on_qp * num_qp);
for (int i = 0; i < size_on_qp * num_qp; i++)
{
f(i) = field(i);
}
}
else
{
static_assert(dfem::always_false<field_operator_t>,
"can't map field to quadrature data");
}
}
template <typename field_operator_ts, size_t num_inputs, size_t num_fields>
MFEM_HOST_DEVICE inline
void map_fields_to_quadrature_data(
std::array<DeviceTensor<2>, num_inputs> &fields_qp,
const std::array<DeviceTensor<1>, num_fields> &fields_e,
const std::array<DofToQuadMap, num_inputs> &dtqmaps,
const std::array<int, num_inputs> &input_to_field,
const field_operator_ts &fops,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem,
const int &dimension,
const bool &use_sum_factorization = false)
{
// When the input_to_field map returns -1, this means the requested input
// is the integration weight. Weights don't have a user defined field
// attached to them and we create a dummy field which is not accessed
// inside the functions it is passed to.
const auto dummy_field_weight = DeviceTensor<1>(nullptr, 0);
for_constexpr<num_inputs>([&](auto i)
{
const DeviceTensor<1> &field_e =
(input_to_field[i] == -1) ? dummy_field_weight : fields_e[input_to_field[i]];
if (use_sum_factorization)
{
if (dimension == 2)
{
map_field_to_quadrature_data_tensor_product_2d(
fields_qp[i], dtqmaps[i], field_e, get<i>(fops),
integration_weights, scratch_mem);
}
else if (dimension == 3)
{
map_field_to_quadrature_data_tensor_product_3d(
fields_qp[i], dtqmaps[i], field_e, get<i>(fops),
integration_weights, scratch_mem);
}
else
{
#if !(defined(MFEM_USE_CUDA) || defined(MFEM_USE_HIP))
MFEM_ABORT("unsupported dimension");
#endif
}
}
else
{
map_field_to_quadrature_data(
fields_qp[i], dtqmaps[i], field_e, get<i>(fops),
integration_weights);
}
});
}
template <typename field_operator_t>
MFEM_HOST_DEVICE
void map_field_to_quadrature_data_conditional(
DeviceTensor<2> &field_qp,
const DeviceTensor<1> &field_e,
const DofToQuadMap &dtqmap,
field_operator_t &fop,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem,
const bool &condition,
const int &dimension,
const bool &use_sum_factorization = false)
{
if (condition)
{
if (use_sum_factorization)
{
if (dimension == 2)
{
map_field_to_quadrature_data_tensor_product_3d(
field_qp, dtqmap, field_e, fop, integration_weights, scratch_mem);
}
else if (dimension == 3)
{
map_field_to_quadrature_data_tensor_product_2d(
field_qp, dtqmap, field_e, fop, integration_weights, scratch_mem);
}
}
else
{
map_field_to_quadrature_data(
field_qp, dtqmap, field_e, fop, integration_weights);
}
}
}
template <size_t num_fields, size_t num_inputs, typename field_operator_ts>
MFEM_HOST_DEVICE
void map_fields_to_quadrature_data_conditional(
std::array<DeviceTensor<2>, num_inputs> &fields_qp,
const std::array<DeviceTensor<1, const real_t>, num_fields> &fields_e,
const std::array<DofToQuadMap, num_inputs> &dtqmaps,
field_operator_ts fops,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem,
const std::array<bool, num_inputs> &conditions,
const bool &use_sum_factorization = false)
{
for_constexpr<num_inputs>([&](auto i)
{
map_field_to_quadrature_data_conditional(
fields_qp[i], fields_e[i], dtqmaps[i], get<i>(fops), integration_weights,
scratch_mem, conditions[i], use_sum_factorization);
});
}
template <size_t num_inputs, typename field_operator_ts>
MFEM_HOST_DEVICE
void map_direction_to_quadrature_data_conditional(
std::array<DeviceTensor<2>, num_inputs> &directions_qp,
const DeviceTensor<1> &direction_e,
const std::array<DofToQuadMap, num_inputs> &dtqmaps,
field_operator_ts fops,
const DeviceTensor<1, const real_t> &integration_weights,
const std::array<DeviceTensor<1>, 6> &scratch_mem,
const std::array<bool, num_inputs> &conditions,
const int &dimension,
const bool &use_sum_factorization = false)
{
for_constexpr<num_inputs>([&](auto i)
{
if (conditions[i])
{
if (use_sum_factorization)
{
if (dimension == 2)
{
map_field_to_quadrature_data_tensor_product_2d(
directions_qp[i], dtqmaps[i], direction_e, get<i>(fops),
integration_weights, scratch_mem);
}
else if (dimension == 3)
{
map_field_to_quadrature_data_tensor_product_3d(
directions_qp[i], dtqmaps[i], direction_e, get<i>(fops),
integration_weights, scratch_mem);
}
}
else
{
map_field_to_quadrature_data(
directions_qp[i], dtqmaps[i], direction_e, get<i>(fops),
integration_weights);
}
}
});
}
}
+154
View File
@@ -0,0 +1,154 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include "../fe/fe_base.hpp"
#include "../../fem/fespace.hpp"
namespace mfem::future
{
/// Base class for parametric spaces
class ParameterSpace
{
public:
ParameterSpace(int vdim = 1) : vdim(vdim) {}
/// @brief Get vector dimension at each point
///
/// This is the number of components at each point in the parametric space.
int GetVDim() const { return vdim; }
/// Get DofToQuad information
const DofToQuad& GetDofToQuad() const { return dtq; }
/// Get total size of the space (T-vector size)
///
/// returns the true size vsize of the space
virtual int GetTrueVSize() const = 0;
/// Get local vector size (L-vector size)
///
/// returns the local size of the space
virtual int GetVSize() const = 0;
/// Get spatial dimension
///
/// returns always 1.
int Dimension() const
{
return 1;
}
/// @brief Get T-vector to L-vector transformation
///
/// returns identity by default that is lazy evaluated.
virtual const Operator* GetProlongationMatrix() const
{
if (!prolongation)
{
prolongation.reset(new IdentityOperator(GetTrueVSize()));
}
return prolongation.get();
}
/// @brief Get L-vector to E-vector transformation
/// @note This is a mock call to replicate interface of FiniteElementSpace.
/// It should not be used by a user.
///
/// returns identity by default that is lazy evaluated.
virtual const Operator* GetElementRestriction(ElementDofOrdering o) const
{
if (!elem_restr)
{
elem_restr.reset(new IdentityOperator(GetVSize()));
}
return elem_restr.get();
}
protected:
int vdim;
DofToQuad dtq;
mutable std::unique_ptr<Operator> prolongation;
mutable std::unique_ptr<Operator> elem_restr;
};
/// @brief Uniform parameter space
class UniformParameterSpace : public ParameterSpace
{
public:
/// @brief Constructor for a uniform parameter space
///
/// @param mesh The mesh to determine dimension and number of elements.
/// @param ir The integration rule to determine the number of quadrature points.
/// @param vdim The vector dimension at each point.
/// @param used_in_tensor_product If true, the number of quadrature points is
/// calculated as the nth root of the number of points in the integration rule,
/// where n is the mesh dimension. If false, the number of quadrature points is
/// taken directly from the integration rule.
UniformParameterSpace(Mesh &mesh, const IntegrationRule &ir, int vdim,
bool used_in_tensor_product = true) :
ParameterSpace(vdim)
{
// Setup DofToQuad information
dtq.nqpt = (int)floor(std::pow(ir.GetNPoints(), 1.0 / mesh.Dimension()) + 0.5);
dtq.ndof = dtq.nqpt;
dtq.mode = used_in_tensor_product ? DofToQuad::TENSOR : DofToQuad::FULL;
// Calculate sizes
const int num_qp = used_in_tensor_product ?
static_cast<int>(std::pow(dtq.nqpt, mesh.Dimension())) :
ir.GetNPoints();
tsize = vdim * num_qp * mesh.GetNE();
lsize = tsize;
}
int GetTrueVSize() const override
{
return tsize;
}
int GetVSize() const override
{
return lsize;
}
private:
/// T-vector size
int tsize;
/// L-vector size
int lsize;
};
class ParameterFunction : public Vector
{
public:
ParameterFunction(ParameterSpace &space) :
Vector(space.GetTrueVSize()),
space(space)
{}
/// @brief Get the ParameterSpace
const ParameterSpace& GetParameterSpace() const
{
return space;
}
using Vector::operator=;
private:
/// the parametric space
ParameterSpace &space;
};
} // namespace mfem::future
+298
View File
@@ -0,0 +1,298 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include "util.hpp"
#include "qfunction_transform.hpp"
namespace mfem::future
{
/// @brief Call a qfunction with the given parameters.
///
/// @param qfunc the qfunction to call.
/// @param input_shmem the input shared memory.
/// @param residual_shmem the residual shared memory.
/// @param rs_qp the size of the residual.
/// @param num_qp the number of quadrature points.
/// @param q1d the number of quadrature points in 1D.
/// @param dimension the spatial dimension.
/// @param use_sum_factorization whether to use sum factorization.
/// @tparam qf_param_ts the tuple type of the qfunction parameters.
template <
typename qf_param_ts,
typename qfunc_t,
std::size_t num_fields>
MFEM_HOST_DEVICE inline
void call_qfunction(
qfunc_t &qfunc,
const std::array<DeviceTensor<2>, num_fields> &input_shmem,
DeviceTensor<2> &residual_shmem,
const int &rs_qp,
const int &num_qp,
const int &q1d,
const int &dimension,
const bool &use_sum_factorization)
{
if (use_sum_factorization)
{
if (dimension == 2)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
const int q = qx + q1d * qy;
auto qf_args = decay_tuple<qf_param_ts> {};
auto r = Reshape(&residual_shmem(0, q), rs_qp);
apply_kernel(r, qfunc, qf_args, input_shmem, q);
}
}
}
else if (dimension == 3)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
const int q = qx + q1d * (qy + q1d * qz);
auto qf_args = decay_tuple<qf_param_ts> {};
auto r = Reshape(&residual_shmem(0, q), rs_qp);
apply_kernel(r, qfunc, qf_args, input_shmem, q);
}
}
}
}
else
{
#if !(defined(MFEM_USE_CUDA) || defined(MFEM_USE_HIP))
MFEM_ABORT("unsupported dimension for sum factorization");
#endif
}
MFEM_SYNC_THREAD;
}
else
{
MFEM_FOREACH_THREAD(q, x, num_qp)
{
auto qf_args = decay_tuple<qf_param_ts> {};
auto r = Reshape(&residual_shmem(0, q), rs_qp);
apply_kernel(r, qfunc, qf_args, input_shmem, q);
}
}
}
/// @brief Call a qfunction with the given parameters and
/// compute it's derivative action.
///
/// @param qfunc the qfunction to call.
/// @param input_shmem the input shared memory.
/// @param shadow_shmem the shadow shared memory.
/// @param residual_shmem the residual shared memory.
/// @param das_qp the size of the derivative action.
/// @param num_qp the number of quadrature points.
/// @param q1d the number of quadrature points in 1D.
/// @param dimension the spatial dimension.
/// @param use_sum_factorization whether to use sum factorization.
/// @tparam qf_param_ts the tuple type of the qfunction parameters.
template <
typename qf_param_ts,
typename qfunc_t,
std::size_t num_fields>
MFEM_HOST_DEVICE inline
void call_qfunction_derivative_action(
qfunc_t &qfunc,
const std::array<DeviceTensor<2>, num_fields> &input_shmem,
const std::array<DeviceTensor<2>, num_fields> &shadow_shmem,
DeviceTensor<2> &residual_shmem,
const int &das_qp,
const int &num_qp,
const int &q1d,
const int &dimension,
const bool &use_sum_factorization)
{
if (use_sum_factorization)
{
if (dimension == 2)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
const int q = qx + q1d * qy;
auto r = Reshape(&residual_shmem(0, q), das_qp);
auto qf_args = decay_tuple<qf_param_ts> {};
#ifdef MFEM_USE_ENZYME
auto qf_shadow_args = decay_tuple<qf_param_ts> {};
apply_kernel_fwddiff_enzyme(r, qfunc, qf_args, qf_shadow_args, input_shmem,
shadow_shmem, q);
#else
apply_kernel_native_dual(r, qfunc, qf_args, input_shmem, shadow_shmem, q);
#endif
}
}
}
else if (dimension == 3)
{
MFEM_FOREACH_THREAD(qx, x, q1d)
{
MFEM_FOREACH_THREAD(qy, y, q1d)
{
MFEM_FOREACH_THREAD(qz, z, q1d)
{
const int q = qx + q1d * (qy + q1d * qz);
auto r = Reshape(&residual_shmem(0, q), das_qp);
auto qf_args = decay_tuple<qf_param_ts> {};
#ifdef MFEM_USE_ENZYME
auto qf_shadow_args = decay_tuple<qf_param_ts> {};
apply_kernel_fwddiff_enzyme(r, qfunc, qf_args, qf_shadow_args, input_shmem,
shadow_shmem, q);
#else
apply_kernel_native_dual(r, qfunc, qf_args, input_shmem, shadow_shmem, q);
#endif
}
}
}
}
MFEM_SYNC_THREAD;
}
else
{
MFEM_FOREACH_THREAD(q, x, num_qp)
{
auto r = Reshape(&residual_shmem(0, q), das_qp);
auto qf_args = decay_tuple<qf_param_ts> {};
#ifdef MFEM_USE_ENZYME
auto qf_shadow_args = decay_tuple<qf_param_ts> {};
apply_kernel_fwddiff_enzyme(r, qfunc, qf_args, qf_shadow_args, input_shmem,
shadow_shmem, q);
#else
apply_kernel_native_dual(r, qfunc, qf_args, input_shmem, shadow_shmem, q);
#endif
}
MFEM_SYNC_THREAD;
}
}
template <typename qfunc_t, typename args_ts, size_t num_args>
MFEM_HOST_DEVICE inline
void apply_kernel(
DeviceTensor<1, real_t> &f_qp,
const qfunc_t &qfunc,
args_ts &args,
const std::array<DeviceTensor<2>, num_args> &u,
int qp)
{
process_qf_args(u, args, qp);
process_qf_result(f_qp, get<0>(apply(qfunc, args)));
}
template <typename qfunc_t, typename arg_ts, size_t num_args>
MFEM_HOST_DEVICE inline
void apply_kernel_native_dual(
DeviceTensor<1, real_t> &f_qp,
const qfunc_t &qfunc,
arg_ts &args,
const std::array<DeviceTensor<2>, num_args> &u,
const std::array<DeviceTensor<2>, num_args> &v,
const int &qp_idx)
{
process_qf_args(u, v, args, qp_idx);
auto r = get<0>(apply(qfunc, args));
process_derivative_from_native_dual(f_qp, r);
}
#ifdef MFEM_USE_ENZYME
template <typename func_t, typename... arg_ts>
MFEM_HOST_DEVICE inline
auto qfunction_wrapper(const func_t &f, arg_ts &&...args)
{
return f(args...);
}
// Version for active function arguments only
//
// This is an Enzyme regression and can be removed in later versions.
template <typename qfunc_t, typename arg_ts, std::size_t... Is,
typename inactive_arg_ts>
MFEM_HOST_DEVICE inline
auto fwddiff_apply_enzyme_indexed(qfunc_t &qfunc, arg_ts &&args,
arg_ts &&shadow_args,
std::index_sequence<Is...>,
inactive_arg_ts &&inactive_args,
std::index_sequence<>)
{
using qf_return_t = typename create_function_signature<
decltype(&qfunc_t::operator())>::type::return_t;
return __enzyme_fwddiff<qf_return_t>(
qfunction_wrapper<qfunc_t, decltype(get<Is>(args))...>, enzyme_const,
(void *)&qfunc, enzyme_dup, &get<Is>(args)..., enzyme_interleave,
&get<Is>(shadow_args)...);
}
// Interleave function arguments for enzyme
template <typename qfunc_t, typename arg_ts, std::size_t... Is,
typename inactive_arg_ts, std::size_t... Js>
MFEM_HOST_DEVICE inline
auto fwddiff_apply_enzyme_indexed(qfunc_t &qfunc, arg_ts &&args,
arg_ts &&shadow_args,
std::index_sequence<Is...>,
inactive_arg_ts &&inactive_args,
std::index_sequence<Js...>)
{
using qf_return_t = typename create_function_signature<
decltype(&qfunc_t::operator())>::type::return_t;
return __enzyme_fwddiff<qf_return_t>(
qfunction_wrapper<qfunc_t, decltype(get<Is>(args))...,
decltype(get<Js>(inactive_args))...>,
enzyme_const, (void *)&qfunc, enzyme_dup, &get<Is>(args)...,
enzyme_const, &get<Js>(inactive_args)..., enzyme_interleave,
&get<Is>(shadow_args)...);
}
template <typename qfunc_t, typename arg_ts, typename inactive_arg_ts>
MFEM_HOST_DEVICE inline
auto fwddiff_apply_enzyme(qfunc_t &qfunc, arg_ts &&args,
arg_ts &&shadow_args,
inactive_arg_ts &&inactive_args)
{
auto arg_indices = std::make_index_sequence<
tuple_size<std::remove_reference_t<arg_ts>>::value> {};
auto inactive_arg_indices = std::make_index_sequence<
tuple_size<std::remove_reference_t<inactive_arg_ts>>::value> {};
return fwddiff_apply_enzyme_indexed(qfunc, args, shadow_args, arg_indices,
inactive_args, inactive_arg_indices);
}
template <typename qfunc_t, typename arg_ts, size_t num_args>
MFEM_HOST_DEVICE inline
void apply_kernel_fwddiff_enzyme(
DeviceTensor<1, real_t> &f_qp,
qfunc_t &qfunc,
arg_ts &args,
arg_ts &shadow_args,
const std::array<DeviceTensor<2>, num_args> &u,
const std::array<DeviceTensor<2>, num_args> &v,
int qp_idx)
{
process_qf_args(u, args, qp_idx);
process_qf_args(v, shadow_args, qp_idx);
process_qf_result(f_qp,
get<0>(fwddiff_apply_enzyme(qfunc, args, shadow_args, tuple<> {})));
}
#endif // MFEM_USE_ENZYME
} // namespace mfem::future
+338
View File
@@ -0,0 +1,338 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
#include "util.hpp"
#include "../../linalg/tensor.hpp"
namespace mfem::future
{
template <typename T0, typename T1, typename T2>
MFEM_HOST_DEVICE
void process_qf_arg(const T0 &, const T1 &, T2 &)
{
static_assert(dfem::always_false<T0, T1, T2>,
"process_qf_arg not implemented for arg type");
}
template <typename T>
MFEM_HOST_DEVICE
void process_qf_arg(
const DeviceTensor<1, T> &u,
const DeviceTensor<1, T> &v,
T &arg)
{
arg = u(0);
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
tensor<dual<T, T>, n, m> &arg)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arg(j, i).value = u((i * m) + j);
}
}
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
dual<T, T> &arg)
{
arg.value = u(0);
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
const DeviceTensor<1> &v,
dual<T, T> &arg)
{
arg.value = u(0);
arg.gradient = v(0);
}
template <typename T, int n>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
const DeviceTensor<1> &v,
tensor<dual<T, T>, n> &arg)
{
for (int i = 0; i < n; i++)
{
arg(i).value = u(i);
arg(i).gradient = v(i);
}
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
const DeviceTensor<1> &v,
tensor<dual<T, T>, n, m> &arg)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arg(j, i).value = u((i * m) + j);
arg(j, i).gradient = v((i * m) + j);
}
}
}
template <typename T, int n>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const tensor<dual<T, T>, n> &x)
{
for (size_t i = 0; i < n; i++)
{
r(i) = x(i).value;
}
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const tensor<dual<T, T>, n, m> &x)
{
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < m; j++)
{
r(i + n * j) = x(i, j).value;
}
}
}
template <typename arg_type>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<2> &u,
const DeviceTensor<2> &v,
arg_type &arg,
const int &qp)
{
const auto u_qp = Reshape(&u(0, qp), u.GetShape()[0]);
const auto v_qp = Reshape(&v(0, qp), v.GetShape()[0]);
process_qf_arg(u_qp, v_qp, arg);
}
template <size_t num_fields, typename qf_args>
MFEM_HOST_DEVICE inline
void process_qf_args(
const std::array<DeviceTensor<2>, num_fields> &u,
const std::array<DeviceTensor<2>, num_fields> &v,
qf_args &args,
const int &qp)
{
for_constexpr<tuple_size<qf_args>::value>([&](auto i)
{
process_qf_arg(u[i], v[i], get<i>(args), qp);
});
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_derivative_from_native_dual(
DeviceTensor<1, T> &r,
const tensor<dual<T, T>, n, m> &x)
{
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < m; j++)
{
r(i + n * j) = x(i, j).gradient;
}
}
}
template <typename T, int n>
MFEM_HOST_DEVICE inline
void process_derivative_from_native_dual(
DeviceTensor<1, T> &r,
const tensor<dual<T, T>, n> &x)
{
for (size_t i = 0; i < n; i++)
{
r(i) = x(i).gradient;
}
}
template <typename T0, typename T1>
MFEM_HOST_DEVICE inline
void process_qf_arg(const T0 &, T1 &)
{
static_assert(dfem::always_false<T0, T1>,
"process_qf_arg not implemented for arg type");
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1, T> &u,
T &arg)
{
arg = u(0);
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1, T> &u,
tensor<T> &arg)
{
arg(0) = u(0);
}
template <typename T, int n>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
tensor<T, n> &arg)
{
for (int i = 0; i < n; i++)
{
arg(i) = u(i);
}
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1> &u,
tensor<T, n, m> &arg)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arg(j, i) = u((i * m) + j);
}
}
}
template <typename arg_type>
MFEM_HOST_DEVICE inline
void process_qf_arg(const DeviceTensor<2> &u, arg_type &arg, int qp)
{
const auto u_qp = Reshape(&u(0, qp), u.GetShape()[0]);
process_qf_arg(u_qp, arg);
}
template <size_t num_fields, typename qf_args>
MFEM_HOST_DEVICE inline
void process_qf_args(
const std::array<DeviceTensor<2>, num_fields> &u,
qf_args &args,
const int &qp)
{
for_constexpr<tuple_size<qf_args>::value>([&](auto i)
{
process_qf_arg(u[i], get<i>(args), qp);
});
}
template <typename T0, typename T1>
MFEM_HOST_DEVICE inline
Vector process_qf_result(T0, T1)
{
static_assert(dfem::always_false<T0, T1>,
"process_qf_result not implemented for result type");
return Vector{};
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const T &x)
{
r(0) = x;
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1> &r,
const dual<T, T> &x)
{
r(0) = x.value;
}
template <typename T>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const tensor<T> &x)
{
r(0) = x(0);
}
template <typename T, int n>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const tensor<T, n> &x)
{
for (size_t i = 0; i < n; i++)
{
r(i) = x(i);
}
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_result(
DeviceTensor<1, T> &r,
const tensor<T, n, m> &x)
{
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < m; j++)
{
r(i + n * j) = x(i, j);
}
}
}
template <typename T, int n, int m>
MFEM_HOST_DEVICE inline
void process_qf_arg(
const DeviceTensor<1, T> &u,
const DeviceTensor<1, T> &v,
tensor<T, n, m> &arg)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arg(j, i) = u((i * m) + j);
}
}
}
} // namespace mfem::future
+885
View File
@@ -0,0 +1,885 @@
// Copyright (c) 2010-2025, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#pragma once
// This is serac's tuple implementation
#include <ostream>
#include "../../config/config.hpp"
#include <utility>
// Define a portable unreachable macro
#if defined(__GNUC__) || defined(__clang__)
#if defined(__CUDACC_VER_MAJOR__)
#if __CUDACC_VER_MAJOR__ <= 11 && __CUDACC_VER_MINOR__ < 3
// nvcc didn't add __builtin_unreachable() until cuda 11.3
#define MFEM_UNREACHABLE()
#else
// nvcc >= 11.3
#define MFEM_UNREACHABLE() __builtin_unreachable()
#endif
#else
// host-only version
#define MFEM_UNREACHABLE() __builtin_unreachable()
#endif
#elif defined(_MSC_VER)
#define MFEM_UNREACHABLE() __assume(0)
#endif
namespace mfem::future
{
/**
* @tparam T the types stored in the tuple
* @brief This is a class that mimics most of std::tuple's interface,
* except that it is usable in CUDA kernels and admits some arithmetic operator overloads.
*
* see https://en.cppreference.com/w/cpp/utility/tuple for more information about std::tuple
*/
template <typename... T>
struct tuple
{
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
*/
template <typename T0>
struct tuple<T0>
{
T0 v0; ///< The first member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
*/
template <typename T0, typename T1>
struct tuple<T0, T1>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
*/
template <typename T0, typename T1, typename T2>
struct tuple<T0, T1, T2>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
* @tparam T3 The fourth type stored in the tuple
*/
template <typename T0, typename T1, typename T2, typename T3>
struct tuple<T0, T1, T2, T3>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
* @tparam T3 The fourth type stored in the tuple
* @tparam T4 The fifth type stored in the tuple
*/
template <typename T0, typename T1, typename T2, typename T3, typename T4>
struct tuple<T0, T1, T2, T3, T4>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
T4 v4; ///< The fifth member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
* @tparam T3 The fourth type stored in the tuple
* @tparam T4 The fifth type stored in the tuple
* @tparam T5 The sixth type stored in the tuple
*/
template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5>
struct tuple<T0, T1, T2, T3, T4, T5>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
T4 v4; ///< The fifth member of the tuple
T5 v5; ///< The sixth member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
* @tparam T3 The fourth type stored in the tuple
* @tparam T4 The fifth type stored in the tuple
* @tparam T5 The sixth type stored in the tuple
* @tparam T6 The seventh type stored in the tuple
*/
template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
struct tuple<T0, T1, T2, T3, T4, T5, T6>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
T4 v4; ///< The fifth member of the tuple
T5 v5; ///< The sixth member of the tuple
T6 v6; ///< The seventh member of the tuple
};
/**
* @brief Type that mimics std::tuple
*
* @tparam T0 The first type stored in the tuple
* @tparam T1 The second type stored in the tuple
* @tparam T2 The third type stored in the tuple
* @tparam T3 The fourth type stored in the tuple
* @tparam T4 The fifth type stored in the tuple
* @tparam T5 The sixth type stored in the tuple
* @tparam T6 The seventh type stored in the tuple
* @tparam T7 The eighth type stored in the tuple
*/
template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
struct tuple<T0, T1, T2, T3, T4, T5, T6, T7>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
T4 v4; ///< The fifth member of the tuple
T5 v5; ///< The sixth member of the tuple
T6 v6; ///< The seventh member of the tuple
T7 v7; ///< The eighth member of the tuple
};
template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
struct tuple<T0, T1, T2, T3, T4, T5, T6, T7, T8>
{
T0 v0; ///< The first member of the tuple
T1 v1; ///< The second member of the tuple
T2 v2; ///< The third member of the tuple
T3 v3; ///< The fourth member of the tuple
T4 v4; ///< The fifth member of the tuple
T5 v5; ///< The sixth member of the tuple
T6 v6; ///< The seventh member of the tuple
T7 v7; ///< The eighth member of the tuple
T8 v8;
};
/**
* @brief Class template argument deduction rule for tuples
* @tparam T The variadic template parameter for tuple types
*/
template <typename... T>
MFEM_HOST_DEVICE
tuple(T...) -> tuple<T...>;
/**
* @brief helper function for combining a list of values into a tuple
* @tparam T types of the values to be tuple-d
* @param args the actual values to be put into a tuple
*/
template <typename... T>
MFEM_HOST_DEVICE tuple<T...> make_tuple(const T&... args)
{
return tuple<T...> {args...};
}
template <class... Types>
struct tuple_size
{
};
template <class... Types>
struct tuple_size<tuple<Types...>> :
std::integral_constant<std::size_t, sizeof...(Types)>
{
};
/**
* @tparam i the tuple index to access
* @tparam T the types stored in the tuple
* @brief return a reference to the ith tuple entry
*/
template <int i, typename... T>
MFEM_HOST_DEVICE constexpr auto& get(tuple<T...>& values)
{
static_assert(i < sizeof...(T));
if constexpr (i == 0)
{
return values.v0;
}
if constexpr (i == 1)
{
return values.v1;
}
if constexpr (i == 2)
{
return values.v2;
}
if constexpr (i == 3)
{
return values.v3;
}
if constexpr (i == 4)
{
return values.v4;
}
if constexpr (i == 5)
{
return values.v5;
}
if constexpr (i == 6)
{
return values.v6;
}
if constexpr (i == 7)
{
return values.v7;
}
if constexpr (i == 8)
{
return values.v8;
}
MFEM_UNREACHABLE();
}
/**
* @tparam i the tuple index to access
* @tparam T the types stored in the tuple
* @brief return a copy of the ith tuple entry
*/
template <int i, typename... T>
MFEM_HOST_DEVICE constexpr const auto& get(const tuple<T...>& values)
{
static_assert(i < sizeof...(T));
if constexpr (i == 0)
{
return values.v0;
}
if constexpr (i == 1)
{
return values.v1;
}
if constexpr (i == 2)
{
return values.v2;
}
if constexpr (i == 3)
{
return values.v3;
}
if constexpr (i == 4)
{
return values.v4;
}
if constexpr (i == 5)
{
return values.v5;
}
if constexpr (i == 6)
{
return values.v6;
}
if constexpr (i == 7)
{
return values.v7;
}
if constexpr (i == 8)
{
return values.v8;
}
MFEM_UNREACHABLE();
}
/**
* @brief a function intended to be used for extracting the ith type from a tuple.
*
* @note type<i>(my_tuple) returns a value, whereas get<i>(my_tuple) returns a reference
*
* @tparam i the index of the tuple to query
* @tparam T the types stored in the tuple
* @param values the tuple of values
* @return a copy of the ith entry of the input
*/
template <int i, typename... T>
MFEM_HOST_DEVICE constexpr auto type(const tuple<T...>& values)
{
static_assert(i < sizeof...(T));
if constexpr (i == 0)
{
return values.v0;
}
if constexpr (i == 1)
{
return values.v1;
}
if constexpr (i == 2)
{
return values.v2;
}
if constexpr (i == 3)
{
return values.v3;
}
if constexpr (i == 4)
{
return values.v4;
}
if constexpr (i == 5)
{
return values.v5;
}
if constexpr (i == 6)
{
return values.v6;
}
if constexpr (i == 7)
{
return values.v7;
}
if constexpr (i == 8)
{
return values.v8;
}
}
/**
* @brief A helper function for the + operator of tuples
*
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param y tuple of values
* @return the returned tuple sum
*/
template <typename... S, typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto plus_helper(const tuple<S...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) + get<i>(y)...};
}
/**
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @param x a tuple of values
* @param y a tuple of values
* @brief return a tuple of values defined by elementwise sum of x and y
*/
template <typename... S, typename... T>
MFEM_HOST_DEVICE constexpr auto operator+(const tuple<S...>& x,
const tuple<T...>& y)
{
static_assert(sizeof...(S) == sizeof...(T));
return plus_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(S))>());
}
/**
* @brief A helper function for the += operator of tuples
*
* @tparam T the types stored in the tuples x and y
* @tparam i integer sequence used to index the tuples
* @param x tuple of values to be incremented
* @param y tuple of increment values
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr void plus_equals_helper(tuple<T...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
((get<i>(x) += get<i>(y)), ...);
}
/**
* @tparam T the types stored in the tuples x and y
* @param x a tuple of values
* @param y a tuple of values
* @brief add values contained in y, to the tuple x
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator+=(tuple<T...>& x,
const tuple<T...>& y)
{
return plus_equals_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @brief A helper function for the -= operator of tuples
*
* @tparam T the types stored in the tuples x and y
* @tparam i integer sequence used to index the tuples
* @param x tuple of values to be subracted from
* @param y tuple of values to subtract from x
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr void minus_equals_helper(tuple<T...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
((get<i>(x) -= get<i>(y)), ...);
}
/**
* @tparam T the types stored in the tuples x and y
* @param x a tuple of values
* @param y a tuple of values
* @brief add values contained in y, to the tuple x
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator-=(tuple<T...>& x,
const tuple<T...>& y)
{
return minus_equals_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @brief A helper function for the - operator of tuples
*
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param y tuple of values
* @return the returned tuple difference
*/
template <typename... S, typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto minus_helper(const tuple<S...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) - get<i>(y)...};
}
/**
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @param x a tuple of values
* @param y a tuple of values
* @brief return a tuple of values defined by elementwise difference of x and y
*/
template <typename... S, typename... T>
MFEM_HOST_DEVICE constexpr auto operator-(const tuple<S...>& x,
const tuple<T...>& y)
{
static_assert(sizeof...(S) == sizeof...(T));
return minus_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(S))>());
}
/**
* @brief A helper function for the - operator of tuples
*
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @return the returned tuple difference
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto unary_minus_helper(const tuple<T...>& x,
std::integer_sequence<int, i...>)
{
return tuple{-get<i>(x)...};
}
/**
* @tparam T the types stored in the tuple y
* @param x a tuple of values
* @brief return a tuple of values defined by applying the unary minus operator to each element of x
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator-(const tuple<T...>& x)
{
return unary_minus_helper(x,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @brief A helper function for the / operator of tuples
*
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param y tuple of values
* @return the returned tuple ratio
*/
template <typename... S, typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto div_helper(const tuple<S...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) / get<i>(y)...};
}
/**
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @param x a tuple of values
* @param y a tuple of values
* @brief return a tuple of values defined by elementwise division of x by y
*/
template <typename... S, typename... T>
MFEM_HOST_DEVICE constexpr auto operator/(const tuple<S...>& x,
const tuple<T...>& y)
{
static_assert(sizeof...(S) == sizeof...(T));
return div_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(S))>());
}
/**
* @brief A helper function for the / operator of tuples
*
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param a the constant numerator
* @return the returned tuple ratio
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto div_helper(const real_t a,
const tuple<T...>& x, std::integer_sequence<int, i...>)
{
return tuple{a / get<i>(x)...};
}
/**
* @brief A helper function for the / operator of tuples
*
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param a the constant denomenator
* @return the returned tuple ratio
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto div_helper(const tuple<T...>& x,
const real_t a, std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) / a...};
}
/**
* @tparam T the types stored in the tuple x
* @param a the numerator
* @param x a tuple of denominator values
* @brief return a tuple of values defined by division of a by the elements of x
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator/(const real_t a, const tuple<T...>& x)
{
return div_helper(a, x,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @tparam T the types stored in the tuple y
* @param x a tuple of numerator values
* @param a a denominator
* @brief return a tuple of values defined by elementwise division of x by a
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator/(const tuple<T...>& x, const real_t a)
{
return div_helper(x, a,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @brief A helper function for the * operator of tuples
*
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param y tuple of values
* @return the returned tuple product
*/
template <typename... S, typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto mult_helper(const tuple<S...>& x,
const tuple<T...>& y,
std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) * get<i>(y)...};
}
/**
* @tparam S the types stored in the tuple x
* @tparam T the types stored in the tuple y
* @param x a tuple of values
* @param y a tuple of values
* @brief return a tuple of values defined by elementwise multiplication of x and y
*/
template <typename... S, typename... T>
MFEM_HOST_DEVICE constexpr auto operator*(const tuple<S...>& x,
const tuple<T...>& y)
{
static_assert(sizeof...(S) == sizeof...(T));
return mult_helper(x, y,
std::make_integer_sequence<int, static_cast<int>(sizeof...(S))>());
}
/**
* @brief A helper function for the * operator of tuples
*
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param a a constant multiplier
* @return the returned tuple product
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto mult_helper(const real_t a,
const tuple<T...>& x, std::integer_sequence<int, i...>)
{
return tuple{a * get<i>(x)...};
}
/**
* @brief A helper function for the * operator of tuples
*
* @tparam T the types stored in the tuple y
* @tparam i The integer sequence to i
* @param x tuple of values
* @param a a constant multiplier
* @return the returned tuple product
*/
template <typename... T, int... i>
MFEM_HOST_DEVICE constexpr auto mult_helper(const tuple<T...>& x,
const real_t a, std::integer_sequence<int, i...>)
{
return tuple{get<i>(x) * a...};
}
/**
* @tparam T the types stored in the tuple
* @param a a scaling factor
* @param x the tuple object
* @brief multiply each component of x by the value a on the left
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator*(const real_t a, const tuple<T...>& x)
{
return mult_helper(a, x,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @tparam T the types stored in the tuple
* @param x the tuple object
* @param a a scaling factor
* @brief multiply each component of x by the value a on the right
*/
template <typename... T>
MFEM_HOST_DEVICE constexpr auto operator*(const tuple<T...>& x, const real_t a)
{
return mult_helper(x, a,
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @tparam T the types stored in the tuple
* @tparam i a list of indices used to acces each element of the tuple
* @param out the ostream to write the output to
* @param A the tuple of values
* @brief helper used to implement printing a tuple of values
*/
template <typename... T, std::size_t... i>
auto& print_helper(std::ostream& out, const tuple<T...>& A,
std::integer_sequence<size_t, i...>)
{
out << "tuple{";
(..., (out << (i == 0 ? "" : ", ") << get<i>(A)));
out << "}";
return out;
}
/**
* @tparam T the types stored in the tuple
* @param out the ostream to write the output to
* @param A the tuple of values
* @brief print a tuple of values
*/
template <typename... T>
auto& operator<<(std::ostream& out, const tuple<T...>& A)
{
return print_helper(out, A, std::make_integer_sequence<size_t, sizeof...(T)>());
}
/**
* @brief A helper to apply a lambda to a tuple
*
* @tparam lambda The functor type
* @tparam T The tuple types
* @tparam i The integer sequence to i
* @param f The functor to apply to the tuple
* @param args The input tuple
* @return The functor output
*/
template <typename lambda, typename... T, int... i>
MFEM_HOST_DEVICE auto apply_helper(lambda f, tuple<T...>& args,
std::integer_sequence<int, i...>)
{
return f(get<i>(args)...);
}
/**
* @tparam lambda a callable type
* @tparam T the types of arguments to be passed in to f
* @param f the callable object
* @param args a tuple of arguments
* @brief a way of passing an n-tuple to a function that expects n separate arguments
*
* e.g. foo(bar, baz) is equivalent to apply(foo, mfem::tuple(bar,baz));
*/
template <typename lambda, typename... T>
MFEM_HOST_DEVICE auto apply(lambda f, tuple<T...>& args)
{
return apply_helper(f, std::move(args),
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @overload
*/
template <typename lambda, typename... T, int... i>
MFEM_HOST_DEVICE auto apply_helper(lambda f, const tuple<T...>& args,
std::integer_sequence<int, i...>)
{
return f(get<i>(args)...);
}
/**
* @tparam lambda a callable type
* @tparam T the types of arguments to be passed in to f
* @param f the callable object
* @param args a tuple of arguments
* @brief a way of passing an n-tuple to a function that expects n separate arguments
*
* e.g. foo(bar, baz) is equivalent to apply(foo, mfem::tuple(bar,baz));
*/
template <typename lambda, typename... T>
MFEM_HOST_DEVICE auto apply(lambda f, const tuple<T...>& args)
{
return apply_helper(f, std::move(args),
std::make_integer_sequence<int, static_cast<int>(sizeof...(T))>());
}
/**
* @brief a struct used to determine the type at index I of a tuple
*
* @note see: https://en.cppreference.com/w/cpp/utility/tuple/tuple_element
*
* @tparam I the index of the desired type
* @tparam T a tuple of different types
*/
template <size_t I, class T>
struct tuple_element;
// recursive case
/// @overload
template <size_t I, class Head, class... Tail>
struct tuple_element<I, tuple<Head, Tail...>> : tuple_element<I - 1,
tuple<Tail...>>
{
};
// base case
/// @overload
template <class Head, class... Tail>
struct tuple_element<0, tuple<Head, Tail...>>
{
using type = Head; ///< the type at the specified index
};
/**
* @brief Trait for checking if a type is a @p mfem::tuple
*/
template <typename T>
struct is_tuple : std::false_type
{
};
/// @overload
template <typename... T>
struct is_tuple<tuple<T...>> : std::true_type
{
};
/**
* @brief Trait for checking if a type if a @p mfem::tuple containing only @p mfem::tuple
*/
template <typename T>
struct is_tuple_of_tuples : std::false_type
{
};
/**
* @brief Trait for checking if a type if a @p mfem::tuple containing only @p mfem::tuple
*/
template <typename... T>
struct is_tuple_of_tuples<tuple<T...>>
{
static constexpr bool value = (is_tuple<T>::value &&
...); ///< true/false result of type check
};
/** @brief Auxiliary template function that merges (concatenates) two
mfem::future::tuple types into a single std::tuple that is empty, i.e. it is
value initialized. */
template <typename... T1s, typename... T2s>
constexpr auto merge_mfem_tuples_as_empty_std_tuple(
const mfem::future::tuple<T1s...> &,
const mfem::future::tuple<T2s...> &)
{
return std::tuple<T1s..., T2s...> {};
}
} // namespace mfem::future
+2256
View File
File diff suppressed because it is too large Load Diff
+16 -24
View File
@@ -16,9 +16,7 @@ namespace mfem
void DofTransformation::TransformPrimal(real_t *v) const
{
MFEM_ASSERT(dof_trans_,
"DofTransformation has no local transformation, call "
"SetDofTransformation first!");
if (IsIdentity()) { return; }
int size = dof_trans_->Size();
if (vdim_ == 1 || (Ordering::Type)ordering_ == Ordering::byNODES)
@@ -48,9 +46,7 @@ void DofTransformation::TransformPrimal(real_t *v) const
void DofTransformation::InvTransformPrimal(real_t *v) const
{
MFEM_ASSERT(dof_trans_,
"DofTransformation has no local transformation, call "
"SetDofTransformation first!");
if (IsIdentity()) { return; }
int size = dof_trans_->Height();
if (vdim_ == 1 || (Ordering::Type)ordering_ == Ordering::byNODES)
@@ -80,9 +76,7 @@ void DofTransformation::InvTransformPrimal(real_t *v) const
void DofTransformation::TransformDual(real_t *v) const
{
MFEM_ASSERT(dof_trans_,
"DofTransformation has no local transformation, call "
"SetDofTransformation first!");
if (IsIdentity()) { return; }
int size = dof_trans_->Size();
if (vdim_ == 1 || (Ordering::Type)ordering_ == Ordering::byNODES)
@@ -112,9 +106,7 @@ void DofTransformation::TransformDual(real_t *v) const
void DofTransformation::InvTransformDual(real_t *v) const
{
MFEM_ASSERT(dof_trans_,
"DofTransformation has no local transformation, call "
"SetDofTransformation first!");
if (IsIdentity()) { return; }
int size = dof_trans_->Size();
if (vdim_ == 1 || (Ordering::Type)ordering_ == Ordering::byNODES)
@@ -142,33 +134,33 @@ void DofTransformation::InvTransformDual(real_t *v) const
}
}
void TransformPrimal(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
void TransformPrimal(const DofTransformation &ran_dof_trans,
const DofTransformation &dom_dof_trans,
DenseMatrix &elmat)
{
// No action if both transformations are NULL
if (ran_dof_trans)
if (!ran_dof_trans.IsIdentity())
{
ran_dof_trans->TransformPrimalCols(elmat);
ran_dof_trans.TransformPrimalCols(elmat);
}
if (dom_dof_trans)
if (!dom_dof_trans.IsIdentity())
{
dom_dof_trans->TransformDualRows(elmat);
dom_dof_trans.TransformDualRows(elmat);
}
}
void TransformDual(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
void TransformDual(const DofTransformation &ran_dof_trans,
const DofTransformation &dom_dof_trans,
DenseMatrix &elmat)
{
// No action if both transformations are NULL
if (ran_dof_trans)
if (!ran_dof_trans.IsIdentity())
{
ran_dof_trans->TransformDualCols(elmat);
ran_dof_trans.TransformDualCols(elmat);
}
if (dom_dof_trans)
if (!dom_dof_trans.IsIdentity())
{
dom_dof_trans->TransformDualRows(elmat);
dom_dof_trans.TransformDualRows(elmat);
}
}
+9 -7
View File
@@ -201,19 +201,19 @@ public:
inline int NumRows() const { return dof_trans_->NumRows(); }
inline int Width() const { return dof_trans_->Width(); }
inline int NumCols() const { return dof_trans_->NumCols(); }
inline bool IsIdentity() const { return dof_trans_->IsIdentity(); }
inline bool IsIdentity() const { return !dof_trans_ || dof_trans_->IsIdentity(); }
/** Transform local DoFs to align with the global DoFs. For example, this
transformation can be used to map the local vector computed by
FiniteElement::Project() to the transformed vector stored within a
GridFunction object. */
void TransformPrimal(real_t *v) const;
inline void TransformPrimal(Vector &v) const
{ TransformPrimal(v.GetData()); }
inline void TransformPrimal(Vector &v) const { TransformPrimal(v.GetData()); }
/// Transform groups of DoFs stored as dense matrices
inline void TransformPrimalCols(DenseMatrix &V) const
{
if (IsIdentity()) { return; }
for (int c=0; c<V.Width(); c++)
{
TransformPrimal(V.GetColumn(c));
@@ -251,6 +251,7 @@ public:
/// Transform rows of a dense matrix containing dual DoFs
inline void TransformDualRows(DenseMatrix &V) const
{
if (IsIdentity()) { return; }
Vector row;
for (int r=0; r<V.Height(); r++)
{
@@ -263,6 +264,7 @@ public:
/// Transform columns of a dense matrix containing dual DoFs
inline void TransformDualCols(DenseMatrix &V) const
{
if (IsIdentity()) { return; }
for (int c=0; c<V.Width(); c++)
{
TransformDual(V.GetColumn(c));
@@ -274,16 +276,16 @@ public:
computed by a DiscreteInterpolator before copying into a
DiscreteLinearOperator.
*/
void TransformPrimal(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
void TransformPrimal(const DofTransformation &ran_dof_trans,
const DofTransformation &dom_dof_trans,
DenseMatrix &elmat);
/** Transform a matrix of dual DoFs entries from different finite element spaces
as computed by a BilinearFormIntegrator before summing into a
MixedBilinearForm object.
*/
void TransformDual(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
void TransformDual(const DofTransformation &ran_dof_trans,
const DofTransformation &dom_dof_trans,
DenseMatrix &elmat);
/** Abstract base class for high-order Nedelec spaces on elements with
+10
View File
@@ -20,6 +20,16 @@ namespace mfem
using namespace std;
DofToQuad DofToQuad::Abs() const
{
DofToQuad d2q(*this);
d2q.B.Abs();
d2q.Bt.Abs();
d2q.G.Abs();
d2q.Gt.Abs();
return d2q;
}
FiniteElement::FiniteElement(int D, Geometry::Type G,
int Do, int O, int F)
: Nodes(Do)
+3
View File
@@ -219,6 +219,9 @@ public:
- #ndof x #nqpt, for H(div) vector elements, or
- #ndof x #nqpt x cdim, for H(curl) vector elements. */
Array<real_t> Gt;
/// Returns absolute value of the maps
DofToQuad Abs() const;
};
/// Describes the function space on each element
+30 -24
View File
@@ -1891,31 +1891,38 @@ L2Pos_PyramidElement::L2Pos_PyramidElement(const int p)
Index idx;
// interior
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
{
int i1 = p - j - k;
int i2 = 0;
int i3 = -1;
int i4 = j + 1;
const int i5 = k;
if (p == 0)
{
dof_map[idx(0,0,0,0,0)] = 0;
Nodes.IntPoint(0).Set3(0.375, 0.375, 0.25);
}
else
{
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
{
int i1 = p - j - k;
int i2 = 0;
int i3 = -1;
int i4 = j + 1;
const int i5 = k;
for (int i = 0; i <= j; i++)
{
i3++;
i4--;
dof_map[idx(i1,i2,i3,i4,i5)] = o;
Nodes.IntPoint(o++).Set3(real_t(i)/p, real_t(j)/p, 0);
for (int i = 0; i <= j; i++)
{
i3++;
i4--;
dof_map[idx(i1,i2,i3,i4,i5)] = o;
Nodes.IntPoint(o++).Set3(real_t(i)/p, real_t(j)/p, 0);
}
for (int i = j + 1; i + k <= p; i++)
{
i1--;
i2++;
dof_map[idx(i1,i2,i3,i4,i5)] = o;
Nodes.IntPoint(o++).Set3(real_t(i)/p, real_t(j)/p, 0);
}
}
for (int i = j + 1; i + k <= p; i++)
{
i1--;
i2++;
dof_map[idx(i1,i2,i3,i4,i5)] = o;
Nodes.IntPoint(o++).Set3(real_t(i)/p, real_t(j)/p, 0);
}
}
}
}
// static method
@@ -2197,7 +2204,6 @@ void L2Pos_PyramidElement::CalcDShape(const IntegrationPoint &ip,
{
dshape(it.second, d) = m_dshape(it.first, d);
}
}
}
+3
View File
@@ -49,6 +49,9 @@
#include "lor/lor.hpp"
#include "dgmassinv.hpp"
#include "hyperbolic.hpp"
#include "bounds.hpp"
#include "dfem/doperator.hpp"
#ifdef MFEM_USE_MPI
#include "pfespace.hpp"
+16 -17
View File
@@ -331,7 +331,6 @@ void FiniteElementSpace::GetElementVDofs(int i, Array<int> &vdofs,
DofTransformation *
FiniteElementSpace::GetElementVDofs(int i, Array<int> &vdofs) const
{
DoFTrans.SetDofTransformation(NULL);
GetElementVDofs(i, vdofs, DoFTrans);
return DoFTrans.GetDofTransformation() ? &DoFTrans : NULL;
}
@@ -347,7 +346,6 @@ void FiniteElementSpace::GetBdrElementVDofs(int i, Array<int> &vdofs,
DofTransformation *
FiniteElementSpace::GetBdrElementVDofs(int i, Array<int> &vdofs) const
{
DoFTrans.SetDofTransformation(NULL);
GetBdrElementVDofs(i, vdofs, DoFTrans);
return DoFTrans.GetDofTransformation() ? &DoFTrans : NULL;
}
@@ -1936,6 +1934,7 @@ void FiniteElementSpace::RefinementOperator::Mult(const Vector &x,
DenseMatrix eP;
IsoparametricTransformation isotr;
DofTransformation doftrans;
for (int k = 0; k < mesh_ref->GetNE(); k++)
{
@@ -1956,10 +1955,10 @@ void FiniteElementSpace::RefinementOperator::Mult(const Vector &x,
subY.SetSize(lP.Height());
DofTransformation *doftrans = fespace->GetElementDofs(k, dofs);
fespace->GetElementDofs(k, dofs, doftrans);
old_elem_dof->GetRow(emb.parent, old_dofs);
if (!doftrans)
if (doftrans.IsIdentity())
{
for (int vd = 0; vd < rvdim; vd++)
{
@@ -1979,7 +1978,7 @@ void FiniteElementSpace::RefinementOperator::Mult(const Vector &x,
old_DoFTrans.SetDofTransformation(*old_DoFTransArray[geom]);
old_DoFTrans.SetFaceOrientations(old_Fo);
doftrans->SetVDim();
doftrans.SetVDim();
for (int vd = 0; vd < rvdim; vd++)
{
dofs.Copy(vdofs);
@@ -1990,10 +1989,10 @@ void FiniteElementSpace::RefinementOperator::Mult(const Vector &x,
x.GetSubVector(old_vdofs, subX);
old_DoFTrans.InvTransformPrimal(subX);
lP.Mult(subX, subY);
doftrans->TransformPrimal(subY);
doftrans.TransformPrimal(subY);
y.SetSubVector(vdofs, subY);
}
doftrans->SetVDim(rvdim, fespace->GetOrdering());
doftrans.SetVDim(rvdim, fespace->GetOrdering());
}
}
}
@@ -2020,6 +2019,7 @@ void FiniteElementSpace::RefinementOperator::MultTranspose(const Vector &x,
DenseMatrix eP;
IsoparametricTransformation isotr;
const FiniteElement *fe = nullptr;
DofTransformation doftrans;
for (int k = 0; k < mesh_ref->GetNE(); k++)
{
@@ -2040,10 +2040,10 @@ void FiniteElementSpace::RefinementOperator::MultTranspose(const Vector &x,
const DenseMatrix &lP = (fespace->IsVariableOrder()) ? eP : localP[geom](
emb.matrix);
DofTransformation *doftrans = fespace->GetElementDofs(k, f_dofs);
fespace->GetElementDofs(k, f_dofs, doftrans);
old_elem_dof->GetRow(emb.parent, c_dofs);
if (!doftrans)
if (doftrans.IsIdentity())
{
subY.SetSize(lP.Width());
@@ -2074,7 +2074,7 @@ void FiniteElementSpace::RefinementOperator::MultTranspose(const Vector &x,
old_DoFTrans.SetDofTransformation(*old_DoFTransArray[geom]);
old_DoFTrans.SetFaceOrientations(old_Fo);
doftrans->SetVDim();
doftrans.SetVDim();
for (int vd = 0; vd < rvdim; vd++)
{
f_dofs.Copy(f_vdofs);
@@ -2083,7 +2083,7 @@ void FiniteElementSpace::RefinementOperator::MultTranspose(const Vector &x,
fespace->DofsToVDofs(vd, c_vdofs, old_ndofs);
x.GetSubVector(f_vdofs, subX);
doftrans->InvTransformDual(subX);
doftrans.InvTransformDual(subX);
for (int p = 0; p < f_dofs.Size(); ++p)
{
if (processed[DecodeDof(f_dofs[p])])
@@ -2095,7 +2095,7 @@ void FiniteElementSpace::RefinementOperator::MultTranspose(const Vector &x,
old_DoFTrans.TransformDual(subYt);
y.AddElementVector(c_vdofs, subYt);
}
doftrans->SetVDim(rvdim, fespace->GetOrdering());
doftrans.SetVDim(rvdim, fespace->GetOrdering());
}
for (int p = 0; p < f_dofs.Size(); ++p)
@@ -3407,6 +3407,8 @@ void FiniteElementSpace::GetElementDofs(int elem, Array<int> &dofs,
{
MFEM_VERIFY(!orders_changed, msg_orders_changed);
doftrans.SetDofTransformation(nullptr);
if (elem_dof)
{
elem_dof->GetRow(elem, dofs);
@@ -3513,7 +3515,6 @@ void FiniteElementSpace::GetElementDofs(int elem, Array<int> &dofs,
DofTransformation *FiniteElementSpace::GetElementDofs(int elem,
Array<int> &dofs) const
{
DoFTrans.SetDofTransformation(NULL);
GetElementDofs(elem, dofs, DoFTrans);
return DoFTrans.GetDofTransformation() ? &DoFTrans : NULL;
}
@@ -3523,6 +3524,8 @@ void FiniteElementSpace::GetBdrElementDofs(int bel, Array<int> &dofs,
{
MFEM_VERIFY(!orders_changed, msg_orders_changed);
doftrans.SetDofTransformation(nullptr);
if (bdr_elem_dof)
{
bdr_elem_dof->GetRow(bel, dofs);
@@ -3617,7 +3620,6 @@ void FiniteElementSpace::GetBdrElementDofs(int bel, Array<int> &dofs,
DofTransformation *FiniteElementSpace::GetBdrElementDofs(int bel,
Array<int> &dofs) const
{
DoFTrans.SetDofTransformation(NULL);
GetBdrElementDofs(bel, dofs, DoFTrans);
return DoFTrans.GetDofTransformation() ? &DoFTrans : NULL;
}
@@ -4276,9 +4278,6 @@ void FiniteElementSpace::Update(bool want_transform)
void FiniteElementSpace::PRefineAndUpdate(const Array<pRefinement> & refs,
bool want_transfer)
{
MFEM_VERIFY(PRefinementSupported(),
"p-refinement is not supported in this space");
if (want_transfer)
{
fesPrev.reset(new FiniteElementSpace(mesh, fec, vdim, ordering));
+42 -30
View File
@@ -946,8 +946,8 @@ public:
/// could be used to produce the appropriate offsets from these local dofs.
///@{
/// @brief Returns indices of degrees of freedom of element 'elem'.
/// The returned indices are offsets into an @ref ldof vector. See also
/// @brief Returns indices of degrees of freedom of element 'elem'. The
/// returned indices are offsets into an @ref ldof vector. See also
/// GetElementVDofs().
///
/// @note In many cases the returned DofTransformation object will be NULL.
@@ -957,15 +957,18 @@ public:
/// needed for Nedelec basis functions of order 2 and above on 3D elements
/// with triangular faces.
///
/// @note The returned object should NOT be deleted by the caller.
/// @deprecated Use of the returned object is deprecated. The returned object
/// should @b not be deleted by the caller. If the DofTransformation is
/// needed, use GetElementDofs(int, Array<int> &, DofTransformation &)
/// instead.
DofTransformation *GetElementDofs(int elem, Array<int> &dofs) const;
/// @brief The same as GetElementDofs(), but with a user-allocated
/// DofTransformation object. @a doftrans must be allocated in advance and
/// will be owned by the caller. The user can use the
/// DofTransformation::GetDofTransformation method on the returned
/// @a doftrans object to detect if the DofTransformation should actually be
/// used.
/// @brief The same as GetElementDofs(), but with a user-provided
/// DofTransformation object.
///
/// The user can use DofTransformation::IsIdentity on the returned @a
/// doftrans object to determine if the DofTransformation needs to actually
/// be used.
virtual void GetElementDofs(int elem, Array<int> &dofs,
DofTransformation &doftrans) const;
@@ -980,15 +983,18 @@ public:
/// needed for Nedelec basis functions of order 2 and above on 3D elements
/// with triangular faces.
///
/// @note The returned object should NOT be deleted by the caller.
/// @deprecated Use of the returned object is deprecated. The returned object
/// should @b not be deleted by the caller. If the DofTransformation is
/// needed, use GetBdrElementDofs(int, Array<int> &, DofTransformation &)
/// instead.
DofTransformation *GetBdrElementDofs(int bel, Array<int> &dofs) const;
/// @brief The same as GetBdrElementDofs(), but with a user-allocated
/// DofTransformation object. @a doftrans must be allocated in advance and
/// will be owned by the caller. The user can use the
/// DofTransformation::GetDofTransformation method on the returned
/// @a doftrans object to detect if the DofTransformation should actually be
/// used.
/// @brief The same as GetBdrElementDofs(), but with a user-provided
/// DofTransformation object.
///
/// The user can use DofTransformation::IsIdentity on the returned @a
/// doftrans object to determine if the DofTransformation needs to actually
/// be used.
virtual void GetBdrElementDofs(int bel, Array<int> &dofs,
DofTransformation &doftrans) const;
@@ -1192,15 +1198,18 @@ public:
/// needed for Nedelec basis functions of order 2 and above on 3D elements
/// with triangular faces.
///
/// @note The returned object should NOT be deleted by the caller.
/// @deprecated Use of the returned object is deprecated. The returned object
/// should @b not be deleted by the caller. If the DofTransformation is
/// needed, use GetElementVDofs(int, Array<int> &, DofTransformation &)
/// instead.
DofTransformation *GetElementVDofs(int i, Array<int> &vdofs) const;
/// @brief The same as GetElementVDofs(), but with a user-allocated
/// DofTransformation object. @a doftrans must be allocated in advance and
/// will be owned by the caller. The user can use the
/// DofTransformation::GetDofTransformation method on the returned
/// @a doftrans object to detect if the DofTransformation should actually be
/// used.
/// @brief The same as GetElementVDofs(), but with a user-provided
/// DofTransformation object.
///
/// The user can use DofTransformation::IsIdentity on the returned @a
/// doftrans object to determine if the DofTransformation needs to actually
/// be used.
void GetElementVDofs(int i, Array<int> &vdofs,
DofTransformation &doftrans) const;
@@ -1216,15 +1225,18 @@ public:
/// needed for Nedelec basis functions of order 2 and above on 3D elements
/// with triangular faces.
///
/// @note The returned object should NOT be deleted by the caller.
/// @deprecated Use of the returned object is deprecated. The returned object
/// should @b not be deleted by the caller. If the DofTransformation is
/// needed, use GetBdrElementVDofs(int, Array<int> &, DofTransformation &)
/// instead.
DofTransformation *GetBdrElementVDofs(int i, Array<int> &vdofs) const;
/// @brief The same as GetBdrElementVDofs(), but with a user-allocated
/// DofTransformation object. @a doftrans must be allocated in advance and
/// will be owned by the caller. The user can use the
/// DofTransformation::GetDofTransformation method on the returned
/// @a doftrans object to detect if the DofTransformation should actually be
/// used.
/// @brief The same as GetBdrElementVDofs(), but with a user-provided
/// DofTransformation object.
///
/// The user can use DofTransformation::IsIdentity on the returned @a
/// doftrans object to determine if the DofTransformation needs to actually
/// be used.
void GetBdrElementVDofs(int i, Array<int> &vdofs,
DofTransformation &doftrans) const;
+233 -173
View File
@@ -288,8 +288,6 @@ void GridFunction::SumFluxAndCount(BilinearFormIntegrator &blfi,
GridFunction &u = *this;
ElementTransformation *Transf;
DofTransformation *udoftrans;
DofTransformation *fdoftrans;
FiniteElementSpace *ufes = u.FESpace();
FiniteElementSpace *ffes = flux.FESpace();
@@ -302,6 +300,7 @@ void GridFunction::SumFluxAndCount(BilinearFormIntegrator &blfi,
flux = 0.0;
count = 0;
DofTransformation udoftrans, fdoftrans;
for (int i = 0; i < nfe; i++)
{
if (subdomain >= 0 && ufes->GetAttribute(i) != subdomain)
@@ -309,23 +308,17 @@ void GridFunction::SumFluxAndCount(BilinearFormIntegrator &blfi,
continue;
}
udoftrans = ufes->GetElementVDofs(i, udofs);
fdoftrans = ffes->GetElementVDofs(i, fdofs);
ufes->GetElementVDofs(i, udofs, udoftrans);
ffes->GetElementVDofs(i, fdofs, fdoftrans);
u.GetSubVector(udofs, ul);
if (udoftrans)
{
udoftrans->InvTransformPrimal(ul);
}
udoftrans.InvTransformPrimal(ul);
Transf = ufes->GetElementTransformation(i);
blfi.ComputeElementFlux(*ufes->GetFE(i), *Transf, ul,
*ffes->GetFE(i), fl, wcoef);
if (fdoftrans)
{
fdoftrans->TransformPrimal(fl);
}
fdoftrans.TransformPrimal(fl);
flux.AddElementVector(fdofs, fl);
FiniteElementSpace::AdjustVDofs(fdofs);
@@ -353,12 +346,23 @@ void GridFunction::ComputeFlux(BilinearFormIntegrator &blfi,
int GridFunction::VectorDim() const
{
return fes->GetVectorDim();
const FiniteElement *fe = fes->GetTypicalFE();
if (!fe || fe->GetRangeType() == FiniteElement::SCALAR)
{
return fes->GetVDim();
}
return fes->GetVDim()*std::max(fes->GetMesh()->SpaceDimension(),
fe->GetRangeDim());
}
int GridFunction::CurlDim() const
{
return fes->GetCurlDim();
const FiniteElement *fe = fes->GetTypicalFE();
if (!fe || fe->GetRangeType() == FiniteElement::SCALAR)
{
return 2 * fes->GetMesh()->SpaceDimension() - 3;
}
return fes->GetVDim()*fe->GetCurlDim();
}
void GridFunction::GetTrueDofs(Vector &tv) const
@@ -394,7 +398,8 @@ void GridFunction::GetNodalValues(int i, Array<real_t> &nval, int vdim) const
{
Array<int> vdofs;
DofTransformation * doftrans = fes->GetElementVDofs(i, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(i, vdofs, doftrans);
const FiniteElement *FElem = fes->GetFE(i);
const IntegrationRule *ElemVert =
Geometries.GetVertices(FElem->GetGeomType());
@@ -404,10 +409,7 @@ void GridFunction::GetNodalValues(int i, Array<real_t> &nval, int vdim) const
vdim--;
Vector loc_data;
GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
if (FElem->GetRangeType() == FiniteElement::SCALAR)
{
@@ -448,7 +450,8 @@ real_t GridFunction::GetValue(int i, const IntegrationPoint &ip, int vdim)
const
{
Array<int> dofs;
DofTransformation * doftrans = fes->GetElementDofs(i, dofs);
DofTransformation doftrans;
fes->GetElementDofs(i, dofs, doftrans);
fes->DofsToVDofs(vdim-1, dofs);
Vector DofVal(dofs.Size()), LocVec;
const FiniteElement *fe = fes->GetFE(i);
@@ -463,10 +466,7 @@ const
fe->CalcPhysShape(*Tr, DofVal);
}
GetSubVector(dofs, LocVec);
if (doftrans)
{
doftrans->InvTransformPrimal(LocVec);
}
doftrans.InvTransformPrimal(LocVec);
return (DofVal * LocVec);
}
@@ -477,13 +477,11 @@ void GridFunction::GetVectorValue(int i, const IntegrationPoint &ip,
const FiniteElement *FElem = fes->GetFE(i);
int dof = FElem->GetDof();
Array<int> vdofs;
DofTransformation * doftrans = fes->GetElementVDofs(i, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(i, vdofs, doftrans);
Vector loc_data;
GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
if (FElem->GetRangeType() == FiniteElement::SCALAR)
{
Vector shape(dof);
@@ -517,22 +515,19 @@ void GridFunction::GetVectorValue(int i, const IntegrationPoint &ip,
}
void GridFunction::GetValues(int i, const IntegrationRule &ir, Vector &vals,
int vdim)
const
int vdim) const
{
Array<int> dofs;
int n = ir.GetNPoints();
vals.SetSize(n);
DofTransformation * doftrans = fes->GetElementDofs(i, dofs);
DofTransformation doftrans;
fes->GetElementDofs(i, dofs, doftrans);
fes->DofsToVDofs(vdim-1, dofs);
const FiniteElement *FElem = fes->GetFE(i);
int dof = FElem->GetDof();
Vector DofVal(dof), loc_data(dof);
GetSubVector(dofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
if (FElem->GetMapType() == FiniteElement::VALUE)
{
for (int k = 0; k < n; k++)
@@ -865,12 +860,12 @@ void GridFunction::GetVectorValue(ElementTransformation &T,
Array<int> vdofs;
const FiniteElement *fe = NULL;
DofTransformation * doftrans = NULL;
DofTransformation doftrans;
switch (T.ElementType)
{
case ElementTransformation::ELEMENT:
doftrans = fes->GetElementVDofs(T.ElementNo, vdofs);
fes->GetElementVDofs(T.ElementNo, vdofs, doftrans);
fe = fes->GetFE(T.ElementNo);
break;
case ElementTransformation::EDGE:
@@ -960,10 +955,7 @@ void GridFunction::GetVectorValue(ElementTransformation &T,
int dof = fe->GetDof();
Vector loc_data;
GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
if (fe->GetRangeType() == FiniteElement::SCALAR)
{
Vector shape(dof);
@@ -1007,13 +999,11 @@ void GridFunction::GetVectorValues(ElementTransformation &T,
int dof = FElem->GetDof();
Array<int> vdofs;
DofTransformation * doftrans = fes->GetElementVDofs(T.ElementNo, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(T.ElementNo, vdofs, doftrans);
Vector loc_data;
GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
int nip = ir.GetNPoints();
@@ -1104,23 +1094,19 @@ void GridFunction::GetValuesFrom(const GridFunction &orig_func)
// Without averaging ...
const FiniteElementSpace *orig_fes = orig_func.FESpace();
DofTransformation * doftrans;
DofTransformation * orig_doftrans;
Array<int> vdofs, orig_vdofs;
Vector shape, loc_values, orig_loc_values;
int i, j, d, ne, dof, odof, vdim;
ne = fes->GetNE();
vdim = fes->GetVDim();
DofTransformation doftrans, orig_doftrans;
for (i = 0; i < ne; i++)
{
doftrans = fes->GetElementVDofs(i, vdofs);
orig_doftrans = orig_fes->GetElementVDofs(i, orig_vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
orig_fes->GetElementVDofs(i, orig_vdofs, orig_doftrans);
orig_func.GetSubVector(orig_vdofs, orig_loc_values);
if (orig_doftrans)
{
orig_doftrans->InvTransformPrimal(orig_loc_values);
}
orig_doftrans.InvTransformPrimal(orig_loc_values);
const FiniteElement *fe = fes->GetFE(i);
const FiniteElement *orig_fe = orig_fes->GetFE(i);
dof = fe->GetDof();
@@ -1137,10 +1123,7 @@ void GridFunction::GetValuesFrom(const GridFunction &orig_func)
loc_values(d*dof+j) = shape * (&orig_loc_values[d * odof]);
}
}
if (doftrans)
{
doftrans->TransformPrimal(loc_values);
}
doftrans.TransformPrimal(loc_values);
SetSubVector(vdofs, loc_values);
}
}
@@ -1150,8 +1133,6 @@ void GridFunction::GetBdrValuesFrom(const GridFunction &orig_func)
// Without averaging ...
const FiniteElementSpace *orig_fes = orig_func.FESpace();
// DofTransformation * doftrans;
// DofTransformation * orig_doftrans;
Array<int> vdofs, orig_vdofs;
Vector shape, loc_values, loc_values_t, orig_loc_values, orig_loc_values_t;
int i, j, d, nbe, dof, odof, vdim;
@@ -1191,7 +1172,8 @@ void GridFunction::GetVectorFieldValues(
ElementTransformation *transf;
const int n = ir.GetNPoints();
DofTransformation * doftrans = fes->GetElementVDofs(i, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(i, vdofs, doftrans);
const FiniteElement *fe = fes->GetFE(i);
const int dof = fe->GetDof();
const int sdim = fes->GetMesh()->SpaceDimension();
@@ -1203,10 +1185,7 @@ void GridFunction::GetVectorFieldValues(
DenseMatrix vshape(dof, vdim);
Vector loc_data, val(vdim);
GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
for (int k = 0; k < n; k++)
{
const IntegrationPoint &ip = ir.IntPoint(k);
@@ -1397,6 +1376,7 @@ void GridFunction::GetVectorGradientHat(
real_t GridFunction::GetDivergence(ElementTransformation &T) const
{
DofTransformation doftrans;
switch (T.ElementType)
{
case ElementTransformation::ELEMENT:
@@ -1424,13 +1404,10 @@ real_t GridFunction::GetDivergence(ElementTransformation &T) const
{
// Assuming RT-type space
Array<int> dofs;
DofTransformation * doftrans = fes->GetElementDofs(elNo, dofs);
fes->GetElementDofs(elNo, dofs, doftrans);
Vector loc_data, divshape(fe->GetDof());
GetSubVector(dofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
fe->CalcDivShape(T.GetIntPoint(), divshape);
return (loc_data * divshape) / T.Weight();
}
@@ -1483,6 +1460,7 @@ real_t GridFunction::GetDivergence(ElementTransformation &T) const
void GridFunction::GetCurl(ElementTransformation &T, Vector &curl) const
{
DofTransformation doftrans;
switch (T.ElementType)
{
case ElementTransformation::ELEMENT:
@@ -1517,13 +1495,10 @@ void GridFunction::GetCurl(ElementTransformation &T, Vector &curl) const
{
// Assuming ND-type space
Array<int> dofs;
DofTransformation * doftrans = fes->GetElementDofs(elNo, dofs);
fes->GetElementDofs(elNo, dofs, doftrans);
Vector loc_data;
GetSubVector(dofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
DenseMatrix curl_shape(fe->GetDof(), fe->GetCurlDim());
curl.SetSize(curl_shape.Width());
fe->CalcPhysCurlShape(T, curl_shape);
@@ -1724,11 +1699,10 @@ void GridFunction::GetElementAverages(GridFunction &avgs) const
{
MassIntegrator Mi;
DenseMatrix loc_mass;
DofTransformation * te_doftrans;
DofTransformation * tr_doftrans;
Array<int> te_dofs, tr_dofs;
Vector loc_avgs, loc_this;
Vector int_psi(avgs.Size());
DofTransformation tr_doftrans, te_doftrans;
avgs = 0.0;
int_psi = 0.0;
@@ -1736,19 +1710,13 @@ void GridFunction::GetElementAverages(GridFunction &avgs) const
{
Mi.AssembleElementMatrix2(*fes->GetFE(i), *avgs.FESpace()->GetFE(i),
*fes->GetElementTransformation(i), loc_mass);
tr_doftrans = fes->GetElementDofs(i, tr_dofs);
te_doftrans = avgs.FESpace()->GetElementDofs(i, te_dofs);
fes->GetElementDofs(i, tr_dofs, tr_doftrans);
avgs.FESpace()->GetElementDofs(i, te_dofs, te_doftrans);
GetSubVector(tr_dofs, loc_this);
if (tr_doftrans)
{
tr_doftrans->InvTransformPrimal(loc_this);
}
tr_doftrans.InvTransformPrimal(loc_this);
loc_avgs.SetSize(te_dofs.Size());
loc_mass.Mult(loc_this, loc_avgs);
if (te_doftrans)
{
te_doftrans->TransformPrimal(loc_avgs);
}
te_doftrans.TransformPrimal(loc_avgs);
avgs.AddElementVector(te_dofs, loc_avgs);
loc_this = 1.0; // assume the local basis for 'this' sums to 1
loc_mass.Mult(loc_this, loc_avgs);
@@ -1763,12 +1731,10 @@ void GridFunction::GetElementAverages(GridFunction &avgs) const
void GridFunction::GetElementDofValues(int el, Vector &dof_vals) const
{
Array<int> dof_idx;
DofTransformation * doftrans = fes->GetElementVDofs(el, dof_idx);
DofTransformation doftrans;
fes->GetElementVDofs(el, dof_idx, doftrans);
GetSubVector(dof_idx, dof_vals);
if (doftrans)
{
doftrans->InvTransformPrimal(dof_vals);
}
doftrans.InvTransformPrimal(dof_vals);
}
void GridFunction::ProjectGridFunction(const GridFunction &src)
@@ -1793,6 +1759,7 @@ void GridFunction::ProjectGridFunction(const GridFunction &src)
Array<int> src_vdofs, dest_vdofs;
Vector src_lvec, dest_lvec(vdim*P.Height());
DofTransformation src_doftrans, doftrans;
for (int i = 0; i < mesh->GetNE(); i++)
{
// Assuming the projection matrix P depends only on the element geometry
@@ -1804,21 +1771,15 @@ void GridFunction::ProjectGridFunction(const GridFunction &src)
cached_geom = geom;
}
DofTransformation * src_doftrans = src.fes->GetElementVDofs(i, src_vdofs);
src.fes->GetElementVDofs(i, src_vdofs, src_doftrans);
src.GetSubVector(src_vdofs, src_lvec);
if (src_doftrans)
{
src_doftrans->InvTransformPrimal(src_lvec);
}
src_doftrans.InvTransformPrimal(src_lvec);
for (int vd = 0; vd < vdim; vd++)
{
P.Mult(&src_lvec[vd*P.Width()], &dest_lvec[vd*P.Height()]);
}
DofTransformation * doftrans = fes->GetElementVDofs(i, dest_vdofs);
if (doftrans)
{
doftrans->TransformPrimal(dest_lvec);
}
fes->GetElementVDofs(i, dest_vdofs, doftrans);
doftrans.TransformPrimal(dest_lvec);
SetSubVector(dest_vdofs, dest_lvec);
}
}
@@ -1827,15 +1788,13 @@ void GridFunction::ImposeBounds(int i, const Vector &weights,
const Vector &lo_, const Vector &hi_)
{
Array<int> vdofs;
DofTransformation * doftrans = fes->GetElementVDofs(i, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(i, vdofs, doftrans);
int size = vdofs.Size();
Vector vals, new_vals(size);
GetSubVector(vdofs, vals);
if (doftrans)
{
doftrans->InvTransformPrimal(vals);
}
doftrans.InvTransformPrimal(vals);
MFEM_ASSERT(weights.Size() == size, "Different # of weights and dofs.");
MFEM_ASSERT(lo_.Size() == size, "Different # of lower bounds and dofs.");
@@ -1852,10 +1811,7 @@ void GridFunction::ImposeBounds(int i, const Vector &weights,
slbqp.SetPrintLevel(0); // print messages only if not converged
slbqp.Mult(vals, new_vals);
if (doftrans)
{
doftrans->TransformPrimal(new_vals);
}
doftrans.TransformPrimal(new_vals);
SetSubVector(vdofs, new_vals);
}
@@ -1863,14 +1819,12 @@ void GridFunction::ImposeBounds(int i, const Vector &weights,
real_t min_, real_t max_)
{
Array<int> vdofs;
DofTransformation * doftrans = fes->GetElementVDofs(i, vdofs);
DofTransformation doftrans;
fes->GetElementVDofs(i, vdofs, doftrans);
int size = vdofs.Size();
Vector vals, new_vals(size);
GetSubVector(vdofs, vals);
if (doftrans)
{
doftrans->InvTransformPrimal(vals);
}
doftrans.InvTransformPrimal(vals);
real_t max_val = vals.Max();
real_t min_val = vals.Min();
@@ -1878,10 +1832,7 @@ void GridFunction::ImposeBounds(int i, const Vector &weights,
if (max_val <= min_)
{
new_vals = min_;
if (doftrans)
{
doftrans->TransformPrimal(new_vals);
}
doftrans.TransformPrimal(new_vals);
SetSubVector(vdofs, new_vals);
return;
}
@@ -1913,7 +1864,6 @@ void GridFunction::RestrictConforming()
void GridFunction::GetNodalValues(Vector &nval, int vdim) const
{
int i, j;
Array<int> vertices;
Array<real_t> values;
Array<int> overlap(fes->GetNV());
@@ -1921,17 +1871,17 @@ void GridFunction::GetNodalValues(Vector &nval, int vdim) const
nval = 0.0;
overlap = 0;
nval.HostReadWrite();
for (i = 0; i < fes->GetNE(); i++)
for (int i = 0; i < fes->GetNE(); i++)
{
fes->GetElementVertices(i, vertices);
GetNodalValues(i, values, vdim);
for (j = 0; j < vertices.Size(); j++)
for (int j = 0; j < vertices.Size(); j++)
{
nval(vertices[j]) += values[j];
overlap[vertices[j]]++;
}
}
for (i = 0; i < overlap.Size(); i++)
for (int i = 0; i < overlap.Size(); i++)
{
nval(i) /= overlap[i];
}
@@ -2211,6 +2161,7 @@ void GridFunction::AccumulateAndCountBdrTangentValues(
ElementTransformation *T;
Array<int> dofs;
Vector lvec;
DofTransformation dof_tr;
values_counter.SetSize(Size());
values_counter = 0;
@@ -2225,10 +2176,10 @@ void GridFunction::AccumulateAndCountBdrTangentValues(
}
fe = fes->GetBE(i);
T = fes->GetBdrElementTransformation(i);
DofTransformation *dof_tr = fes->GetBdrElementDofs(i, dofs);
fes->GetBdrElementDofs(i, dofs, dof_tr);
lvec.SetSize(fe->GetDof());
fe->Project(vcoeff, *T, lvec);
if (dof_tr) { dof_tr->TransformPrimal(lvec); }
dof_tr.TransformPrimal(lvec);
accumulate_dofs(dofs, lvec, *this, values_counter);
}
@@ -2333,6 +2284,8 @@ void GridFunction::ProjectDeltaCoefficient(DeltaCoefficient &delta_coeff,
DenseMatrix loc_mass;
Array<int> vdofs, vertices;
Vector vals, loc_mass_vals;
DofTransformation doftrans;
for (int i = 0; i < mesh->GetNE(); i++)
{
mesh->GetElementVertices(i, vertices);
@@ -2344,11 +2297,8 @@ void GridFunction::ProjectDeltaCoefficient(DeltaCoefficient &delta_coeff,
loc_mass);
vals.SetSize(fe->GetDof());
fe->ProjectDelta(j, vals);
const DofTransformation* const doftrans = fes->GetElementVDofs(i, vdofs);
if (doftrans)
{
doftrans->TransformPrimal(vals);
}
fes->GetElementVDofs(i, vdofs, doftrans);
doftrans.TransformPrimal(vals);
SetSubVector(vdofs, vals);
loc_mass_vals.SetSize(vals.Size());
loc_mass.Mult(vals, loc_mass_vals);
@@ -2361,7 +2311,7 @@ void GridFunction::ProjectDeltaCoefficient(DeltaCoefficient &delta_coeff,
void GridFunction::ProjectCoefficient(Coefficient &coeff)
{
DeltaCoefficient *delta_c = dynamic_cast<DeltaCoefficient *>(&coeff);
DofTransformation * doftrans = NULL;
DofTransformation doftrans;
if (delta_c == NULL)
{
@@ -2372,13 +2322,10 @@ void GridFunction::ProjectCoefficient(Coefficient &coeff)
for (int i = 0; i < fes->GetNE(); i++)
{
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
vals.SetSize(vdofs.Size());
fes->GetFE(i)->Project(coeff, *fes->GetElementTransformation(i), vals);
if (doftrans)
{
doftrans->TransformPrimal(vals);
}
doftrans.TransformPrimal(vals);
SetSubVector(vdofs, vals);
}
}
@@ -2445,23 +2392,19 @@ void GridFunction::ProjectCoefficient(
void GridFunction::ProjectCoefficient(VectorCoefficient &vcoeff)
{
DofTransformation doftrans;
if (fes->GetNURBSext() == NULL)
{
int i;
Array<int> vdofs;
Vector vals;
DofTransformation * doftrans = NULL;
for (i = 0; i < fes->GetNE(); i++)
{
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
vals.SetSize(vdofs.Size());
fes->GetFE(i)->Project(vcoeff, *fes->GetElementTransformation(i), vals);
if (doftrans)
{
doftrans->TransformPrimal(vals);
}
doftrans.TransformPrimal(vals);
SetSubVector(vdofs, vals);
}
}
@@ -2528,8 +2471,7 @@ void GridFunction::ProjectCoefficient(VectorCoefficient &vcoeff, int attribute)
int i;
Array<int> vdofs;
Vector vals;
DofTransformation * doftrans = NULL;
DofTransformation doftrans;
for (i = 0; i < fes->GetNE(); i++)
{
@@ -2538,13 +2480,10 @@ void GridFunction::ProjectCoefficient(VectorCoefficient &vcoeff, int attribute)
continue;
}
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
vals.SetSize(vdofs.Size());
fes->GetFE(i)->Project(vcoeff, *fes->GetElementTransformation(i), vals);
if (doftrans)
{
doftrans->TransformPrimal(vals);
}
doftrans.TransformPrimal(vals);
SetSubVector(vdofs, vals);
}
}
@@ -2555,7 +2494,6 @@ void GridFunction::ProjectCoefficient(Coefficient *coeff[])
real_t val;
const FiniteElement *fe;
ElementTransformation *transf;
// DofTransformation * doftrans;
Array<int> vdofs;
vdim = fes->GetVDim();
@@ -2738,6 +2676,7 @@ void GridFunction::ProjectBdrCoefficientNormal(
Array<int> dofs;
int dim = vcoeff.GetVDim();
Vector vc(dim), nor(dim), lvec;
DofTransformation doftrans;
for (int i = 0; i < fes->GetNBE(); i++)
{
@@ -2757,11 +2696,8 @@ void GridFunction::ProjectBdrCoefficientNormal(
CalcOrtho(T->Jacobian(), nor);
lvec(j) = (vc * nor);
}
const DofTransformation* const doftrans = fes->GetBdrElementDofs(i, dofs);
if (doftrans)
{
doftrans->TransformPrimal(lvec);
}
fes->GetBdrElementDofs(i, dofs, doftrans);
doftrans.TransformPrimal(lvec);
SetSubVector(dofs, lvec);
}
#endif
@@ -4059,6 +3995,7 @@ real_t ZZErrorEstimator(BilinearFormIntegrator &blfi,
FiniteElementSpace *ufes = u.FESpace();
FiniteElementSpace *ffes = flux.FESpace();
ElementTransformation *Transf;
DofTransformation utrans, ftrans;
int dim = ufes->GetMesh()->Dimension();
int nfe = ufes->GetNE();
@@ -4090,19 +4027,13 @@ real_t ZZErrorEstimator(BilinearFormIntegrator &blfi,
{
if (with_subdomains && ufes->GetAttribute(i) != s) { continue; }
const DofTransformation* const utrans = ufes->GetElementVDofs(i, udofs);
const DofTransformation* const ftrans = ffes->GetElementVDofs(i, fdofs);
ufes->GetElementVDofs(i, udofs, utrans);
ffes->GetElementVDofs(i, fdofs, ftrans);
u.GetSubVector(udofs, ul);
flux.GetSubVector(fdofs, fla);
if (utrans)
{
utrans->InvTransformPrimal(ul);
}
if (ftrans)
{
ftrans->InvTransformPrimal(fla);
}
utrans.InvTransformPrimal(ul);
ftrans.InvTransformPrimal(fla);
Transf = ufes->GetElementTransformation(i);
blfi.ComputeElementFlux(*ufes->GetFE(i), *Transf, ul,
@@ -4317,6 +4248,7 @@ real_t LSZZErrorEstimator(BilinearFormIntegrator &blfi, // input
MFEM_VERIFY(tichonov_coeff >= 0.0, "tichonov_coeff cannot be negative");
FiniteElementSpace *ufes = u.FESpace();
ElementTransformation *Transf;
DofTransformation utrans;
Mesh *mesh = ufes->GetMesh();
int dim = mesh->Dimension();
@@ -4398,12 +4330,9 @@ real_t LSZZErrorEstimator(BilinearFormIntegrator &blfi, // input
flux_order));
int num_integration_pts = ir->GetNPoints();
const DofTransformation* const utrans = ufes->GetElementVDofs(ielem, udofs);
ufes->GetElementVDofs(ielem, udofs, utrans);
u.GetSubVector(udofs, ul);
if (utrans)
{
utrans->InvTransformPrimal(ul);
}
utrans.InvTransformPrimal(ul);
Transf = ufes->GetElementTransformation(ielem);
FiniteElement *dummy = nullptr;
blfi.ComputeElementFlux(*ufes->GetFE(ielem), *Transf, ul,
@@ -4634,4 +4563,135 @@ GridFunction *Extrude1DGridFunction(Mesh *mesh, Mesh *mesh2d,
return sol2d;
}
void GridFunction::GetElementBoundsAtControlPoints(const int elem,
const PLBound &plb,
Vector &lower, Vector &upper,
const int vdim)
{
const FiniteElement *fe = fes->GetFE(elem);
int fes_dim = fes->GetVDim();
int rdim = fe->GetDim();
const TensorBasisElement *tbe =
dynamic_cast<const TensorBasisElement *>(fe);
MFEM_VERIFY(tbe != NULL, "TensorBasis FiniteElement expected.");
const Array<int> &dof_map = tbe->GetDofMap();
Vector loc_data;
Array<int> dof_idx;
fes->GetElementDofs(elem, dof_idx);
int ndofs = dof_idx.Size();
int n_c_pts = std::pow(plb.GetNControlPoints(), rdim);
lower.SetSize(n_c_pts*(vdim > 0 ? 1 : fes_dim));
upper.SetSize(n_c_pts*(vdim > 0 ? 1 : fes_dim));
for (int d = 0; d < fes_dim; d++)
{
if (vdim > 0 && d != vdim-1) { continue; }
const int d_off = vdim > 0 ? 0 : d;
Array<int> dof_idx_c = dof_idx;
Vector lowerT(lower, d_off*n_c_pts, n_c_pts);
Vector upperT(upper, d_off*n_c_pts, n_c_pts);
fes->DofsToVDofs(vdim > 0 ? vdim-1 : d, dof_idx_c);
GetSubVector(dof_idx_c, loc_data);
Vector nodal_data;
if (dof_map.Size() == 0)
{
nodal_data.SetDataAndSize(loc_data.GetData(), ndofs);
}
else
{
nodal_data.SetSize(ndofs);
for (int j = 0; j < ndofs; j++)
{
nodal_data(j) = loc_data(dof_map[j]);
}
}
plb.GetNDBounds(rdim, nodal_data, lowerT, upperT);
}
}
void GridFunction::GetElementBounds(const int elem, const PLBound &plb,
Vector &lower, Vector &upper,
const int vdim)
{
Vector lowerC, upperC;
GetElementBoundsAtControlPoints(elem, plb, lowerC, upperC, vdim);
const FiniteElement *fe = fes->GetFE(elem);
int rdim = fe->GetDim();
int n_c_pts = std::pow(plb.GetNControlPoints(), rdim);
int fes_dim = fes->GetVDim();
lower.SetSize((vdim > 0 ? 1 :fes_dim));
upper.SetSize((vdim > 0 ? 1 :fes_dim));
for (int d = 0; d < fes_dim; d++)
{
if (vdim > 0 && d != vdim-1) { continue; }
const int d_off = vdim > 0 ? 0 : d;
Vector lowerT(lowerC, d_off*n_c_pts, n_c_pts);
Vector upperT(upperC, d_off*n_c_pts, n_c_pts);
lower(d_off) = lowerT.Min();
upper(d_off) = upperT.Max();
}
}
void GridFunction::GetElementBounds(const PLBound &plb,
Vector &lower, Vector &upper,
const int vdim)
{
int nel = fes->GetNE();
int fes_dim = fes->GetVDim();
lower.SetSize(nel*(vdim > 0 ? 1 :fes_dim));
upper.SetSize(nel*(vdim > 0 ? 1 :fes_dim));
for (int e = 0; e < nel; e++)
{
Vector lt, ut;
GetElementBounds(e, plb, lt, ut, vdim);
for (int d = 0; d < fes_dim ; d++)
{
if (vdim > 0 && d != vdim-1) { continue; }
const int d_off = vdim > 0 ? 0 : d;
lower(e + d_off*nel) = lt(d_off);
upper(e + d_off*nel) = ut(d_off);
}
}
}
PLBound GridFunction::GetElementBounds(Vector &lower,
Vector &upper,
const int ref_factor,
const int vdim)
{
int max_order = fes->GetMaxElementOrder();
PLBound plb(fes, ref_factor*(max_order+1));
GetElementBounds(plb, lower, upper, vdim);
return plb;
}
PLBound GridFunction::GetBounds(Vector &lower, Vector &upper,
const int ref_factor, const int vdim)
{
int max_order = fes->GetMaxElementOrder();
PLBound plb(fes, ref_factor*(max_order+1));
Vector lel, uel;
GetElementBounds(plb, lel, uel, vdim);
int nel = fes->GetNE();
int fes_dim = fes->GetVDim();
lower.SetSize(vdim > 0 ? 1 : fes_dim);
upper.SetSize(vdim > 0 ? 1 : fes_dim);
for (int d = 0; d < fes_dim; d++)
{
if (vdim > 0 && d != vdim-1) { continue; }
const int d_off = vdim > 0 ? 0 : d;
Vector lelt(lel, d_off*nel, nel);
Vector uelt(uel, d_off*nel, nel);
lower(d_off) = lelt.Min();
upper(d_off) = uelt.Max();
}
return plb;
}
}
+47 -1
View File
@@ -16,6 +16,7 @@
#include "fespace.hpp"
#include "coefficient.hpp"
#include "bilininteg.hpp"
#include "bounds.hpp"
#ifdef MFEM_USE_ADIOS2
#include "../general/adios2stream.hpp"
#endif
@@ -1561,11 +1562,56 @@ public:
must be 2 and that quad elements will be broken into two triangles.*/
void SaveSTL(std::ostream &out, int TimesToRefine = 1);
/** @name Methods to compute bounds on the grid function
\brief See bounds.hpp for \ref PLBound that constructs piecewise linear
bounds for a given set of bases. These piecewise bounds can be used to compute bounds on a grid function. Currently tensor-product elements are
supported with Lagrange interpolants on Gauss Legendre nodes and Gauss Lobatto Legendre nodes, and Bernstein bases.
*/
///@{
/// Computes the \ref PLBound for the gridfunction with number of control
/// points based on @a ref_factor, and returns the overall bounds for each
/// vdim (across all elements) in @b lower and @b upper. We also return the
/// PLBound object used to compute the bounds.
/// We compute the bounds for each vdim if @a vdim < 1.
/// Note: For most cases, this method/interface will be sufficient.
virtual PLBound GetBounds(Vector &lower, Vector &upper,
const int ref_factor=1, const int vdim=-1);
/// Computes the \ref PLBound for the gridfunction with number of control
/// points based on @a ref_factor, and returns the bounds for each element
/// ordered byVDim:
/// lower_{0,0}, lower_{1,0}, ..., lower_{ne-1,0},
/// lower_{0,1}, ..., lower_{ne-1,vdim-1}. We also return the
/// PLBound object used to compute the bounds.
/// We compute the bounds for each vdim if @a vdim < 1.
PLBound GetElementBounds(Vector &lower, Vector &upper,
const int ref_factor=1, const int vdim=-1);
/// Compute piecewise linear bounds on the given element at the grid of
/// [plb.ncp x plb.ncp x plb.ncp] control points for each of the vdim
/// components of the gridfunction.
void GetElementBoundsAtControlPoints(const int elem, const PLBound &plb,
Vector &lower, Vector &upper,
const int vdim = -1);
/// Compute bounds on the grid function for the given element.
/// The bounds are stored in @b lower and @b upper.
void GetElementBounds(const int elem, const PLBound &plb,
Vector &lower, Vector &upper,
const int vdim = -1);
/// Compute bounds on the grid function for all the elements. The bounds
/// are returned in @b lower and @b upper, ordered byVDim:
/// lower_{0,0}, lower_{1,0}, ..., lower_{ne-1,0},
/// lower_{0,1}, ..., lower_{ne-1,vdim-1}
void GetElementBounds(const PLBound &plb, Vector &lower, Vector &upper,
const int vdim=-1);
///@}
/// Destroys grid function.
virtual ~GridFunction() { Destroy(); }
};
/** Overload operator<< for std::ostream and GridFunction; valid also for the
derived class ParGridFunction */
std::ostream &operator<<(std::ostream &out, const GridFunction &sol);
+3 -1
View File
@@ -30,7 +30,9 @@ namespace mfem
{
/** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary
* collection of points.
* collection of points. See Mittal et al., "General Field Evaluation in
* High-Order Meshes on GPUs". (2025). Computers & Fluids. for technical
* details.
*
* There are three key functions in FindPointsGSLIB:
*
+64
View File
@@ -202,4 +202,68 @@ void CurlCurlIntegrator::AddMultPA(const Vector &x, Vector &y) const
}
}
void CurlCurlIntegrator::AddAbsMultPA(const Vector &x, Vector &y) const
{
Vector abs_pa_data(pa_data);
abs_pa_data.Abs();
auto absO = mapsO->Abs();
auto absC = mapsC->Abs();
if (dim == 3)
{
if (Device::Allows(Backend::DEVICE_MASK))
{
const int ID = (dofs1D << 4) | quad1D;
switch (ID)
{
case 0x23:
return internal::SmemPACurlCurlApply3D<2,3>(
dofs1D, quad1D,
symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
case 0x34:
return internal::SmemPACurlCurlApply3D<3,4>(
dofs1D, quad1D,
symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
case 0x45:
return internal::SmemPACurlCurlApply3D<4,5>(
dofs1D, quad1D,
symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
case 0x56:
return internal::SmemPACurlCurlApply3D<5,6>(
dofs1D, quad1D,
symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
default:
return internal::SmemPACurlCurlApply3D<0,0>(
dofs1D, quad1D, symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
}
}
else
{
internal::PACurlCurlApply3D<0,0>(
dofs1D, quad1D, symmetric, ne,
absO.B, absC.B, absO.Bt, absC.Bt, absC.G, absC.Gt,
abs_pa_data, x, y, true);
}
}
else if (dim == 2)
{
internal::PACurlCurlApply2D(dofs1D, quad1D, ne, absO.B, absO.Bt,
absC.G, absC.Gt, abs_pa_data, x, y, true);
}
else
{
MFEM_ABORT("Unsupported dimension!");
}
}
} // namespace mfem
+1 -1
View File
@@ -200,7 +200,7 @@ void PADiffusionSetup2D<3>(const int Q1D,
const real_t E = J11*J11 + J21*J21 + J31*J31;
const real_t G = J12*J12 + J22*J22 + J32*J32;
const real_t F = J11*J12 + J21*J22 + J31*J32;
const real_t iw = 1.0 / sqrt(E*G - F*F);
const real_t iw = 1.0 / std::sqrt(E*G - F*F);
const real_t coeff = const_c ? C(0,0,0) : C(qx,qy,e);
const real_t alpha = wq * coeff * iw;
D(qx,qy,0,e) = alpha * G; // 1,1
@@ -483,19 +483,6 @@ inline void SmemPADiffusionDiagonal3D(const int NE,
});
}
void PADiffusionApply(const int dim,
const int D1D,
const int Q1D,
const int NE,
const bool symm,
const Array<real_t> &B,
const Array<real_t> &G,
const Array<real_t> &Bt,
const Array<real_t> &Gt,
const Vector &D,
const Vector &X,
Vector &Y);
#ifdef MFEM_USE_OCCA
// OCCA PA Diffusion Apply 2D kernel
void OccaPADiffusionApply2D(const int D1D,
+30
View File
@@ -164,6 +164,36 @@ void DiffusionIntegrator::AssemblePatchPA(const int patch,
SetupPatchPA(patch, mesh); // For full quadrature, unitWeights = false
}
void DiffusionIntegrator::AddAbsMultPA(const Vector &x, Vector &y) const
{
if (DeviceCanUseCeed())
{
MFEM_ABORT("Ceed AbsMult not implemented yet");
}
Vector abs_pa_data(pa_data);
abs_pa_data.Abs();
auto abs_maps = maps->Abs();
ApplyPAKernels::Run(dim, dofs1D, quad1D, ne, symmetric,
abs_maps.B, abs_maps.G, abs_maps.Bt, abs_maps.Gt,
abs_pa_data, x, y, dofs1D, quad1D);
}
void DiffusionIntegrator::AddAbsMultTransposePA(const Vector &x,
Vector &y) const
{
if (symmetric)
{
AddAbsMultPA(x, y);
}
else
{
MFEM_ABORT("DiffusionIntegrator::AddAbsMultTransposePA only implemented "
"in the symmetric case.")
}
}
// This version uses full 1D quadrature rules, taking into account the
// minimum interaction between basis functions and integration points.
void DiffusionIntegrator::AddMultPatchPA(const int patch, const Vector &x,
+21 -5
View File
@@ -147,6 +147,11 @@ void ElasticityAddMultPA_(const int nDofs, const FiniteElementSpace &fespace,
const GeometricFactors &geom, const DofToQuad &maps, const Vector &x,
QuadratureFunction &QVec, Vector &y)
{
using future::tensor;
using future::make_tensor;
using future::det;
using future::inv;
static_assert((i_block < 0) == (j_block < 0),
"i_block and j_block must both be non-negative or strictly negative.");
static constexpr int d = dim;
@@ -207,7 +212,7 @@ void ElasticityAddMultPA_(const int nDofs, const FiniteElementSpace &fespace,
const int iIndex = isComponent ? 0 : i;
div += gradx(iIndex,i);
}
const real_t w = ipWeights[p] /det(invJ);
const real_t w = ipWeights[p]/det(invJ);
for (int m = 0; m < d; m++)
{
for (int q = qLower; q < qUpper; q++)
@@ -221,8 +226,8 @@ void ElasticityAddMultPA_(const int nDofs, const FiniteElementSpace &fespace,
{
for (int a = 0; a < d; a++)
{
contraction += 2*((a == q)*invJ(m,j_block) + (j_block==q)*invJ(m,a))*(gradx(0,
a));
contraction += 2*((a == q)*invJ(m,j_block)
+ (j_block==q)*invJ(m,a))*(gradx(0, a));
}
}
else
@@ -231,7 +236,7 @@ void ElasticityAddMultPA_(const int nDofs, const FiniteElementSpace &fespace,
{
for (int b = 0; b < d; b++)
{
contraction += ((a == q)*invJ(m,b) + (b==q)*invJ(m,a))
contraction += ((a == q)*invJ(m,b) + (b == q)*invJ(m,a))
*(gradx(a,b) + gradx(b, a));
}
}
@@ -239,7 +244,8 @@ void ElasticityAddMultPA_(const int nDofs, const FiniteElementSpace &fespace,
// lambda*div(u)*div(v) + 2*mu*sym(grad(u))*sym(grad(v))
// contraction = 4*sym(grad(u))sym(grad(v))
const int qIndex = isComponent ? 0 : q;
Q(p,m,qIndex,e) = w*(lamDev(p, e)*invJ(m,q)*div + 0.5*muDev(p, e)*contraction);
Q(p,m,qIndex,e) = w*(lamDev(p, e)*invJ(m,q)*div
+ 0.5*muDev(p, e)*contraction);
}
}
}
@@ -277,6 +283,11 @@ void ElasticityAssembleDiagonalPA_(const int nDofs,
const CoefficientVector &mu, const GeometricFactors &geom,
const DofToQuad &maps, QuadratureFunction &QVec, Vector &diag)
{
using future::tensor;
using future::make_tensor;
using future::det;
using future::inv;
// Assuming all elements are the same
const auto &ir = QVec.GetIntRule(0);
static constexpr int d = dim;
@@ -361,6 +372,11 @@ void ElasticityAssembleEA_(const int i_block,
const DofToQuad &maps,
Vector &emat)
{
using future::tensor;
using future::make_tensor;
using future::det;
using future::inv;
// Assuming all elements are the same
static constexpr int d = dim;
const int numPoints = ir.GetNPoints();
+6 -3
View File
@@ -662,7 +662,8 @@ void PACurlCurlApply2D(const int D1D,
const Array<real_t> &gct,
const Vector &pa_data,
const Vector &x,
Vector &y)
Vector &y,
const bool useAbs)
{
auto Bo = Reshape(bo.Read(), Q1D, D1D-1);
@@ -717,7 +718,8 @@ void PACurlCurlApply2D(const int D1D,
for (int qy = 0; qy < Q1D; ++qy)
{
const real_t wy = (c == 0) ? -Gc(qy,dy) : Bo(qy,dy);
const int sign = useAbs ? 1 : -1;
const real_t wy = (c == 0) ? (sign*Gc(qy,dy)) : Bo(qy,dy);
for (int qx = 0; qx < Q1D; ++qx)
{
curl[qy][qx] += gradX[qx] * wy;
@@ -760,7 +762,8 @@ void PACurlCurlApply2D(const int D1D,
}
for (int dy = 0; dy < D1Dy; ++dy)
{
const real_t wy = (c == 0) ? -Gct(dy,qy) : Bot(dy,qy);
const int sign = useAbs ? 1 : -1;
const real_t wy = (c == 0) ? (sign*Gct(dy,qy)) : Bot(dy,qy);
for (int dx = 0; dx < D1Dx; ++dx)
{
+132 -27
View File
@@ -828,7 +828,7 @@ inline void SmemPACurlCurlAssembleDiagonal3D(const int d1d,
}); // end of element loop
}
// PA H(curl) curl-curl Apply 2D kernel
// PA H(curl) curl-curl Apply/AbsApply 2D kernel
void PACurlCurlApply2D(const int D1D,
const int Q1D,
const int NE,
@@ -838,9 +838,10 @@ void PACurlCurlApply2D(const int D1D,
const Array<real_t> &gct,
const Vector &pa_data,
const Vector &x,
Vector &y);
Vector &y,
const bool useAbs = false);
// PA H(curl) curl-curl Apply 3D kernel
// PA H(curl) curl-curl Apply/AbsApply 3D kernel
template<int T_D1D = 0, int T_Q1D = 0>
inline void PACurlCurlApply3D(const int d1d,
const int q1d,
@@ -854,7 +855,8 @@ inline void PACurlCurlApply3D(const int d1d,
const Array<real_t> &gct,
const Vector &pa_data,
const Vector &x,
Vector &y)
Vector &y,
const bool useAbs = false)
{
MFEM_VERIFY(T_D1D || d1d <= DeviceDofQuadLimits::Get().HCURL_MAX_D1D,
"Error: d1d > HCURL_MAX_D1D");
@@ -970,7 +972,16 @@ inline void PACurlCurlApply3D(const int d1d,
{
// \hat{\nabla}\times\hat{u} is [0, (u_0)_{x_2}, -(u_0)_{x_1}]
curl[qz][qy][qx][1] += gradXY[qy][qx][1] * wDz; // (u_0)_{x_2}
curl[qz][qy][qx][2] -= gradXY[qy][qx][0] * wz; // -(u_0)_{x_1}
if (useAbs)
{
// +(u_0)_{x_1}
curl[qz][qy][qx][2] += gradXY[qy][qx][0] * wz;
}
else
{
// -(u_0)_{x_1}
curl[qz][qy][qx][2] -= gradXY[qy][qx][0] * wz;
}
}
}
}
@@ -1038,7 +1049,16 @@ inline void PACurlCurlApply3D(const int d1d,
for (int qx = 0; qx < Q1D; ++qx)
{
// \hat{\nabla}\times\hat{u} is [-(u_1)_{x_2}, 0, (u_1)_{x_0}]
curl[qz][qy][qx][0] -= gradXY[qy][qx][1] * wDz; // -(u_1)_{x_2}
if (useAbs)
{
// +(u_1)_{x_2}
curl[qz][qy][qx][0] += gradXY[qy][qx][1] * wDz;
}
else
{
// -(u_1)_{x_2}
curl[qz][qy][qx][0] -= gradXY[qy][qx][1] * wDz;
}
curl[qz][qy][qx][2] += gradXY[qy][qx][0] * wz; // (u_1)_{x_0}
}
}
@@ -1109,7 +1129,16 @@ inline void PACurlCurlApply3D(const int d1d,
{
// \hat{\nabla}\times\hat{u} is [(u_2)_{x_1}, -(u_2)_{x_0}, 0]
curl[qz][qy][qx][0] += gradYZ[qz][qy][1] * wx; // (u_2)_{x_1}
curl[qz][qy][qx][1] -= gradYZ[qz][qy][0] * wDx; // -(u_2)_{x_0}
if (useAbs)
{
// +(u_2)_{x_0}
curl[qz][qy][qx][1] += gradYZ[qz][qy][0] * wDx;
}
else
{
// -(u_2)_{x_0}
curl[qz][qy][qx][1] -= gradYZ[qz][qy][0] * wDx;
}
}
}
}
@@ -1209,9 +1238,21 @@ inline void PACurlCurlApply3D(const int d1d,
for (int dx = 0; dx < D1Dx; ++dx)
{
// \hat{\nabla}\times\hat{u} is [0, (u_0)_{x_2}, -(u_0)_{x_1}]
// (u_0)_{x_2} * (op * curl)_1 - (u_0)_{x_1} * (op * curl)_2
Y(dx + ((dy + (dz * D1Dy)) * D1Dx) + osc,
e) += (gradXY21[dy][dx] * wDz) - (gradXY12[dy][dx] * wz);
const int idx = dx + ((dy + (dz * D1Dy)) * D1Dx) + osc;
if (useAbs)
{
// (u_0)_{x_2} * (op * curl)_1 +
// (u_0)_{x_1} * (op * curl)_2
Y(idx, e) += (gradXY21[dy][dx] * wDz) +
(gradXY12[dy][dx] * wz);
}
else
{
// (u_0)_{x_2} * (op * curl)_1 -
// (u_0)_{x_1} * (op * curl)_2
Y(idx, e) += (gradXY21[dy][dx] * wDz) -
(gradXY12[dy][dx] * wz);
}
}
}
}
@@ -1278,10 +1319,22 @@ inline void PACurlCurlApply3D(const int d1d,
{
for (int dx = 0; dx < D1Dx; ++dx)
{
const int idx = dx + ((dy + (dz * D1Dy)) * D1Dx) + osc;
// \hat{\nabla}\times\hat{u} is [-(u_1)_{x_2}, 0, (u_1)_{x_0}]
// -(u_1)_{x_2} * (op * curl)_0 + (u_1)_{x_0} * (op * curl)_2
Y(dx + ((dy + (dz * D1Dy)) * D1Dx) + osc,
e) += (-gradXY20[dy][dx] * wDz) + (gradXY02[dy][dx] * wz);
if (useAbs)
{
// +(u_1)_{x_2} * (op * curl)_0 +
// (u_1)_{x_0} * (op * curl)_2
Y(idx, e) += (gradXY20[dy][dx] * wDz) +
(gradXY02[dy][dx] * wz);
}
else
{
// -(u_1)_{x_2} * (op * curl)_0 +
// (u_1)_{x_0} * (op * curl)_2
Y(idx, e) += (-gradXY20[dy][dx] * wDz) +
(gradXY02[dy][dx] * wz);
}
}
}
}
@@ -1351,10 +1404,22 @@ inline void PACurlCurlApply3D(const int d1d,
{
for (int dz = 0; dz < D1Dz; ++dz)
{
const int idx = dx + ((dy + (dz * D1Dy)) * D1Dx) + osc;
// \hat{\nabla}\times\hat{u} is [(u_2)_{x_1}, -(u_2)_{x_0}, 0]
// (u_2)_{x_1} * (op * curl)_0 - (u_2)_{x_0} * (op * curl)_1
Y(dx + ((dy + (dz * D1Dy)) * D1Dx) + osc,
e) += (gradYZ10[dz][dy] * wx) - (gradYZ01[dz][dy] * wDx);
if (useAbs)
{
// (u_2)_{x_1} * (op * curl)_0 +
// (u_2)_{x_0} * (op * curl)_1
Y(idx, e) += (gradYZ10[dz][dy] * wx) +
(gradYZ01[dz][dy] * wDx);
}
else
{
// (u_2)_{x_1} * (op * curl)_0 -
// (u_2)_{x_0} * (op * curl)_1
Y(idx, e) += (gradYZ10[dz][dy] * wx) -
(gradYZ01[dz][dy] * wDx);
}
}
}
}
@@ -1363,7 +1428,7 @@ inline void PACurlCurlApply3D(const int d1d,
}); // end of element loop
}
// Shared memory PA H(curl) curl-curl Apply 3D kernel
// Shared memory PA H(curl) curl-curl Apply/AbsApply 3D kernel
template<int T_D1D = 0, int T_Q1D = 0>
inline void SmemPACurlCurlApply3D(const int d1d,
const int q1d,
@@ -1377,7 +1442,8 @@ inline void SmemPACurlCurlApply3D(const int d1d,
const Array<real_t> &gct,
const Vector &pa_data,
const Vector &x,
Vector &y)
Vector &y,
const bool useAbs = false)
{
MFEM_VERIFY(T_D1D || d1d <= DeviceDofQuadLimits::Get().HCURL_MAX_D1D,
"Error: d1d > HCURL_MAX_D1D");
@@ -1531,7 +1597,8 @@ inline void SmemPACurlCurlApply3D(const int d1d,
}
curl[qy][qx][1] += v; // (u_0)_{x_2}
curl[qy][qx][2] -= u; // -(u_0)_{x_1}
if (useAbs) { curl[qy][qx][2] += u; } // +(u_0)_{x_1}
else { curl[qy][qx][2] -= u; } // -(u_0)_{x_1}
}
else if (c == 1) // y component
{
@@ -1558,7 +1625,8 @@ inline void SmemPACurlCurlApply3D(const int d1d,
}
}
curl[qy][qx][0] -= v; // -(u_1)_{x_2}
if (useAbs) { curl[qy][qx][0] += v; } // +(u_1)_{x_2}
else { curl[qy][qx][0] -= v; } // -(u_1)_{x_2}
curl[qy][qx][2] += u; // (u_1)_{x_0}
}
else // z component
@@ -1587,7 +1655,8 @@ inline void SmemPACurlCurlApply3D(const int d1d,
}
curl[qy][qx][0] += v; // (u_2)_{x_1}
curl[qy][qx][1] -= u; // -(u_2)_{x_0}
if (useAbs) { curl[qy][qx][1] += u; }// +(u_2)_{x_0}
else { curl[qy][qx][1] -= u; } // -(u_2)_{x_0}
}
} // qx
} // qy
@@ -1642,18 +1711,54 @@ inline void SmemPACurlCurlApply3D(const int d1d,
if (dx < D1D-1)
{
// \hat{\nabla}\times\hat{u} is [0, (u_0)_{x_2}, -(u_0)_{x_1}]
// (u_0)_{x_2} * (op * curl)_1 - (u_0)_{x_1} * (op * curl)_2
const real_t wx = sBo[dx][qx];
dxyz1 += (wx * c2 * wcy * wcDz) - (wx * c3 * wcDy * wcz);
if (useAbs)
{
// (u_0)_{x_2} * (op * curl)_1 +
// (u_0)_{x_1} * (op * curl)_2
dxyz1 += (wx * c2 * wcy * wcDz) +
(wx * c3 * wcDy * wcz);
}
else
{
// (u_0)_{x_2} * (op * curl)_1 -
// (u_0)_{x_1} * (op * curl)_2
dxyz1 += (wx * c2 * wcy * wcDz) -
(wx * c3 * wcDy * wcz);
}
}
// \hat{\nabla}\times\hat{u} is [-(u_1)_{x_2}, 0, (u_1)_{x_0}]
// -(u_1)_{x_2} * (op * curl)_0 + (u_1)_{x_0} * (op * curl)_2
dxyz2 += (-wy * c1 * wcx * wcDz) + (wy * c3 * wDx * wcz);
if (useAbs)
{
// +(u_1)_{x_2} * (op * curl)_0 +
// (u_1)_{x_0} * (op * curl)_2
dxyz2 += (wy * c1 * wcx * wcDz) +
(wy * c3 * wDx * wcz);
}
else
{
// -(u_1)_{x_2} * (op * curl)_0 +
// (u_1)_{x_0} * (op * curl)_2
dxyz2 += (-wy * c1 * wcx * wcDz) +
(wy * c3 * wDx * wcz);
}
// \hat{\nabla}\times\hat{u} is [(u_2)_{x_1}, -(u_2)_{x_0}, 0]
// (u_2)_{x_1} * (op * curl)_0 - (u_2)_{x_0} * (op * curl)_1
dxyz3 += (wcDy * wz * c1 * wcx) - (wcy * wz * c2 * wDx);
if (useAbs)
{
// (u_2)_{x_1} * (op * curl)_0 +
// (u_2)_{x_0} * (op * curl)_1
dxyz3 += (wcDy * wz * c1 * wcx) +
(wcy * wz * c2 * wDx);
}
else
{
// (u_2)_{x_1} * (op * curl)_0 -
// (u_2)_{x_0} * (op * curl)_1
dxyz3 += (wcDy * wz * c1 * wcx) -
(wcy * wz * c2 * wDx);
}
} // qx
} // qy
} // dx
+27
View File
@@ -199,10 +199,37 @@ void MassIntegrator::AddMultPA(const Vector &x, Vector &y) const
}
}
void MassIntegrator::AddAbsMultPA(const Vector &x, Vector &y) const
{
if (DeviceCanUseCeed())
{
MFEM_ABORT("AddAbsMultPA not implemented with CEED!");
ceedOp->AddMult(x, y);
}
else
{
Vector abs_pa_data(pa_data);
abs_pa_data.Abs();
Array<real_t> absB(maps->B);
Array<real_t> absBt(maps->Bt);
absB.Abs();
absBt.Abs();
ApplyPAKernels::Run(dim, dofs1D, quad1D, ne, absB, absBt, abs_pa_data,
x, y, dofs1D, quad1D);
}
}
void MassIntegrator::AddMultTransposePA(const Vector &x, Vector &y) const
{
// Mass integrator is symmetric
AddMultPA(x, y);
}
void MassIntegrator::AddAbsMultTransposePA(const Vector &x, Vector &y) const
{
// Mass integrator is symmetric
AddAbsMultPA(x, y);
}
} // namespace mfem
+123
View File
@@ -313,6 +313,129 @@ void VectorFEMassIntegrator::AddMultPA(const Vector &x, Vector &y) const
}
}
void VectorFEMassIntegrator::AddAbsMultPA(const Vector &x, Vector &y) const
{
const bool trial_curl = (trial_fetype == mfem::FiniteElement::CURL);
const bool trial_div = (trial_fetype == mfem::FiniteElement::DIV);
const bool test_curl = (test_fetype == mfem::FiniteElement::CURL);
const bool test_div = (test_fetype == mfem::FiniteElement::DIV);
Vector abs_pa_data(pa_data);
abs_pa_data.Abs();
Array<real_t> absBo(mapsO->B);
Array<real_t> absBc(mapsC->B);
Array<real_t> absBto(mapsO->Bt);
Array<real_t> absBtc(mapsC->Bt);
Array<real_t> absBto_t(mapsOtest->Bt);
Array<real_t> absBtc_t(mapsCtest->Bt);
absBo.Abs();
absBc.Abs();
absBto.Abs();
absBtc.Abs();
absBto_t.Abs();
absBtc_t.Abs();
if (dim == 3)
{
if (trial_curl && test_curl)
{
if (Device::Allows(Backend::DEVICE_MASK))
{
const int ID = (dofs1D << 4) | quad1D;
switch (ID)
{
case 0x23:
return internal::SmemPAHcurlMassApply3D<2,3>(
dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
case 0x34:
return internal::SmemPAHcurlMassApply3D<3,4>(
dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
case 0x45:
return internal::SmemPAHcurlMassApply3D<4,5>(
dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
case 0x56:
return internal::SmemPAHcurlMassApply3D<5,6>(
dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
default:
return internal::SmemPAHcurlMassApply3D(
dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
}
}
else
{
internal::PAHcurlMassApply3D(dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
}
}
else if (trial_div && test_div)
{
internal::PAHdivMassApply(3, dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
}
else if (trial_curl && test_div)
{
const bool scalarCoeff = !(DQ || MQ);
internal::PAHcurlHdivMassApply3D(dofs1D, dofs1Dtest, quad1D, ne,
scalarCoeff, true, false,
absBo, absBc, absBto_t, absBtc_t,
abs_pa_data, x, y);
}
else if (trial_div && test_curl)
{
const bool scalarCoeff = !(DQ || MQ);
internal::PAHcurlHdivMassApply3D(dofs1D, dofs1Dtest, quad1D, ne,
scalarCoeff, false, false,
absBo, absBc, absBto_t, absBtc_t,
abs_pa_data, x, y);
}
else
{
MFEM_ABORT("Unknown kernel.");
}
}
else // 2D
{
if (trial_curl && test_curl)
{
internal::PAHcurlMassApply2D(dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
}
else if (trial_div && test_div)
{
internal::PAHdivMassApply(2, dofs1D, quad1D, ne, symmetric,
absBo, absBc, absBto, absBtc,
abs_pa_data, x, y);
}
else if ((trial_curl && test_div) || (trial_div && test_curl))
{
const bool scalarCoeff = !(DQ || MQ);
internal::PAHcurlHdivMassApply2D(dofs1D, dofs1Dtest, quad1D, ne,
scalarCoeff, trial_curl, false,
absBo, absBc, absBto_t, absBtc_t,
abs_pa_data, x, y);
}
else
{
MFEM_ABORT("Unknown kernel.");
}
}
}
void VectorFEMassIntegrator::AddMultTransposePA(const Vector &x,
Vector &y) const
{
+6 -12
View File
@@ -173,7 +173,6 @@ void LinearForm::Assemble()
{
Array<int> vdofs;
ElementTransformation *eltrans;
DofTransformation *doftrans;
Vector elemvect;
Vector::operator=(0.0);
@@ -198,6 +197,7 @@ void LinearForm::Assemble()
}
}
DofTransformation doftrans;
for (int i = 0; i < fes -> GetNE(); i++)
{
int elem_attr = fes->GetMesh()->GetAttribute(i);
@@ -207,14 +207,11 @@ void LinearForm::Assemble()
if (markers) { markers->HostRead(); }
if ( markers == NULL || (*markers)[elem_attr-1] == 1 )
{
doftrans = fes -> GetElementVDofs (i, vdofs);
fes -> GetElementVDofs (i, vdofs, doftrans);
eltrans = fes -> GetElementTransformation (i);
domain_integs[k]->AssembleRHSElementVect(*fes->GetFE(i),
*eltrans, elemvect);
if (doftrans)
{
doftrans->TransformDual(elemvect);
}
doftrans.TransformDual(elemvect);
AddElementVector (vdofs, elemvect);
}
}
@@ -247,11 +244,12 @@ void LinearForm::Assemble()
}
}
DofTransformation doftrans;
for (int i = 0; i < fes -> GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
doftrans = fes -> GetBdrElementVDofs (i, vdofs);
fes -> GetBdrElementVDofs (i, vdofs, doftrans);
eltrans = fes -> GetBdrElementTransformation (i);
for (int k=0; k < boundary_integs.Size(); k++)
{
@@ -260,11 +258,7 @@ void LinearForm::Assemble()
boundary_integs[k]->AssembleRHSElementVect(*fes->GetBE(i),
*eltrans, elemvect);
if (doftrans)
{
doftrans->TransformDual(elemvect);
}
doftrans.TransformDual(elemvect);
AddElementVector (vdofs, elemvect);
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ void LORBase::AddIntegratorsAndMarkers(BilinearForm &a_from,
for (int i=0; i<integrators->Size(); ++i)
{
BilinearFormIntegrator *integrator = (*integrators)[i];
if (*markers[i])
if (markers[i] != nullptr)
{
(a_to.*add_integrator_marker)(integrator, *markers[i]);
}
+10 -3
View File
@@ -485,10 +485,17 @@ void BatchedLORAssembly::Assemble(
#endif
AssembleWithoutBC(a, A);
SparseMatrix *A_mat = A.As<SparseMatrix>();
A_mat->EliminateBC(ess_dofs,
Operator::DiagonalPolicy::DIAG_KEEP);
const SparseMatrix *P = fes_ho.GetConformingProlongation();
if (P)
{
std::unique_ptr<SparseMatrix> R(Transpose(*P));
std::unique_ptr<SparseMatrix> RA(mfem::Mult(*R, *A.As<SparseMatrix>()));
A.Reset(mfem::Mult(*RA, *P));
}
A.As<SparseMatrix>()->EliminateBC(ess_dofs,
Operator::DiagonalPolicy::DIAG_KEEP);
}
BatchedLORAssembly::BatchedLORAssembly(FiniteElementSpace &fes_ho_)
+43 -44
View File
@@ -96,7 +96,6 @@ real_t NonlinearForm::GetGridFunctionEnergy(const Vector &x) const
Vector el_x;
const FiniteElement *fe;
ElementTransformation *T;
DofTransformation *doftrans;
Mesh *mesh = fes->GetMesh();
real_t energy = 0.0;
@@ -123,16 +122,17 @@ real_t NonlinearForm::GetGridFunctionEnergy(const Vector &x) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNE(); i++)
{
const int attr = mesh->GetAttribute(i);
if (attr_marker[attr-1] == 0) { continue; }
fe = fes->GetFE(i);
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
T = fes->GetElementTransformation(i);
x.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < dnfi.Size(); k++)
{
if (dnfi_marker[k] &&
@@ -166,16 +166,17 @@ real_t NonlinearForm::GetGridFunctionEnergy(const Vector &x) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
fe = fes->GetBE(i);
doftrans = fes->GetBdrElementVDofs(i, vdofs);
fes->GetBdrElementVDofs(i, vdofs, doftrans);
T = fes->GetBdrElementTransformation(i);
x.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < bnfi.Size(); k++)
{
if (bnfi_marker[k] &&
@@ -240,7 +241,6 @@ void NonlinearForm::Mult(const Vector &x, Vector &y) const
Vector el_x, el_y;
const FiniteElement *fe;
ElementTransformation *T;
DofTransformation *doftrans;
Mesh *mesh = fes->GetMesh();
py = 0.0;
@@ -268,23 +268,24 @@ void NonlinearForm::Mult(const Vector &x, Vector &y) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNE(); i++)
{
const int attr = mesh->GetAttribute(i);
if (attr_marker[attr-1] == 0) { continue; }
fe = fes->GetFE(i);
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
T = fes->GetElementTransformation(i);
px.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < dnfi.Size(); k++)
{
if (dnfi_marker[k] &&
(*dnfi_marker[k])[attr-1] == 0) { continue; }
dnfi[k]->AssembleElementVector(*fe, *T, el_x, el_y);
if (doftrans) {doftrans->TransformDual(el_y); }
doftrans.TransformDual(el_y);
py.AddElementVector(vdofs, el_y);
}
}
@@ -313,23 +314,25 @@ void NonlinearForm::Mult(const Vector &x, Vector &y) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
fe = fes->GetBE(i);
doftrans = fes->GetBdrElementVDofs(i, vdofs);
fes->GetBdrElementVDofs(i, vdofs, doftrans);
T = fes->GetBdrElementTransformation(i);
px.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < bnfi.Size(); k++)
{
if (bnfi_marker[k] &&
(*bnfi_marker[k])[bdr_attr-1] == 0) { continue; }
bnfi[k]->AssembleElementVector(*fe, *T, el_x, el_y);
if (doftrans) {doftrans->TransformDual(el_y); }
doftrans.TransformDual(el_y);
py.AddElementVector(vdofs, el_y);
}
}
@@ -453,7 +456,6 @@ Operator &NonlinearForm::GetGradient(const Vector &x) const
DenseMatrix elmat;
const FiniteElement *fe;
ElementTransformation *T;
DofTransformation *doftrans;
Mesh *mesh = fes->GetMesh();
const Vector &px = Prolongate(x);
@@ -489,23 +491,24 @@ Operator &NonlinearForm::GetGradient(const Vector &x) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNE(); i++)
{
const int attr = mesh->GetAttribute(i);
if (attr_marker[attr-1] == 0) { continue; }
fe = fes->GetFE(i);
doftrans = fes->GetElementVDofs(i, vdofs);
fes->GetElementVDofs(i, vdofs, doftrans);
T = fes->GetElementTransformation(i);
px.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < dnfi.Size(); k++)
{
if (dnfi_marker[k] &&
(*dnfi_marker[k])[attr-1] == 0) { continue; }
dnfi[k]->AssembleElementGrad(*fe, *T, el_x, elmat);
if (doftrans) { doftrans->TransformDual(elmat); }
doftrans.TransformDual(elmat);
Grad->AddSubMatrix(vdofs, vdofs, elmat, skip_zeros);
// Grad->AddSubMatrix(vdofs, vdofs, elmat, 1);
}
@@ -535,23 +538,24 @@ Operator &NonlinearForm::GetGradient(const Vector &x) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes->GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
if (bdr_attr_marker[bdr_attr-1] == 0) { continue; }
fe = fes->GetBE(i);
doftrans = fes->GetBdrElementVDofs(i, vdofs);
fes->GetBdrElementVDofs(i, vdofs, doftrans);
T = fes->GetBdrElementTransformation(i);
px.GetSubVector(vdofs, el_x);
if (doftrans) {doftrans->InvTransformPrimal(el_x); }
doftrans.InvTransformPrimal(el_x);
for (int k = 0; k < bnfi.Size(); k++)
{
if (bnfi_marker[k] &&
(*bnfi_marker[k])[bdr_attr-1] == 0) { continue; }
bnfi[k]->AssembleElementGrad(*fe, *T, el_x, elmat);
if (doftrans) { doftrans->TransformDual(elmat); }
doftrans.TransformDual(elmat);
Grad->AddSubMatrix(vdofs, vdofs, elmat, skip_zeros);
}
}
@@ -806,7 +810,6 @@ real_t BlockNonlinearForm::GetEnergyBlocked(const BlockVector &bx) const
Array<const Vector *> el_x_const(fes.Size());
Array<const FiniteElement *> fe(fes.Size());
ElementTransformation *T;
DofTransformation *doftrans;
Mesh *mesh = fes[0]->GetMesh();
real_t energy = 0.0;
@@ -839,6 +842,7 @@ real_t BlockNonlinearForm::GetEnergyBlocked(const BlockVector &bx) const
}
}
DofTransformation doftrans;
for (int i = 0; i < fes[0]->GetNE(); ++i)
{
const int attr = mesh->GetAttribute(i);
@@ -848,9 +852,9 @@ real_t BlockNonlinearForm::GetEnergyBlocked(const BlockVector &bx) const
for (int s=0; s<fes.Size(); ++s)
{
fe[s] = fes[s]->GetFE(i);
doftrans = fes[s]->GetElementVDofs(i, *vdofs[s]);
fes[s]->GetElementVDofs(i, *vdofs[s], doftrans);
bx.GetBlock(s).GetSubVector(*vdofs[s], *el_x[s]);
if (doftrans) {doftrans->InvTransformPrimal(*el_x[s]); }
doftrans.InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < dnfi.Size(); ++k)
@@ -886,6 +890,7 @@ real_t BlockNonlinearForm::GetEnergyBlocked(const BlockVector &bx) const
}
}
DofTransformation doftrans;
for (int i = 0; i < mesh->GetNBE(); i++)
{
const int bdr_attr = mesh->GetBdrAttribute(i);
@@ -895,9 +900,9 @@ real_t BlockNonlinearForm::GetEnergyBlocked(const BlockVector &bx) const
for (int s = 0; s < fes.Size(); ++s)
{
fe[s] = fes[s]->GetBE(i);
doftrans = fes[s]->GetBdrElementVDofs(i, *(vdofs[s]));
fes[s]->GetBdrElementVDofs(i, *(vdofs[s]), doftrans);
bx.GetBlock(s).GetSubVector(*(vdofs[s]), *el_x[s]);
if (doftrans) {doftrans->InvTransformPrimal(*el_x[s]); }
doftrans.InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < bnfi.Size(); k++)
@@ -947,7 +952,7 @@ void BlockNonlinearForm::MultBlocked(const BlockVector &bx,
Array<const FiniteElement *> fe(fes.Size());
Array<const FiniteElement *> fe2(fes.Size());
ElementTransformation *T;
Array<DofTransformation *> doftrans(fes.Size()); doftrans = nullptr;
std::vector<DofTransformation> doftrans(fes.Size());
Mesh *mesh = fes[0]->GetMesh();
by.UseDevice(true);
@@ -992,10 +997,10 @@ void BlockNonlinearForm::MultBlocked(const BlockVector &bx,
T = fes[0]->GetElementTransformation(i);
for (int s = 0; s < fes.Size(); ++s)
{
doftrans[s] = fes[s]->GetElementVDofs(i, *(vdofs[s]));
fes[s]->GetElementVDofs(i, *(vdofs[s]), doftrans[s]);
fe[s] = fes[s]->GetFE(i);
bx.GetBlock(s).GetSubVector(*(vdofs[s]), *el_x[s]);
if (doftrans[s]) {doftrans[s]->InvTransformPrimal(*el_x[s]); }
doftrans[s].InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < dnfi.Size(); ++k)
@@ -1009,7 +1014,7 @@ void BlockNonlinearForm::MultBlocked(const BlockVector &bx,
for (int s=0; s<fes.Size(); ++s)
{
if (el_y[s]->Size() == 0) { continue; }
if (doftrans[s]) {doftrans[s]->TransformDual(*el_y[s]); }
doftrans[s].TransformDual(*el_y[s]);
by.GetBlock(s).AddElementVector(*(vdofs[s]), *el_y[s]);
}
}
@@ -1047,10 +1052,10 @@ void BlockNonlinearForm::MultBlocked(const BlockVector &bx,
T = fes[0]->GetBdrElementTransformation(i);
for (int s = 0; s < fes.Size(); ++s)
{
doftrans[s] = fes[s]->GetBdrElementVDofs(i, *(vdofs[s]));
fes[s]->GetBdrElementVDofs(i, *(vdofs[s]), doftrans[s]);
fe[s] = fes[s]->GetBE(i);
bx.GetBlock(s).GetSubVector(*(vdofs[s]), *el_x[s]);
if (doftrans[s]) {doftrans[s]->InvTransformPrimal(*el_x[s]); }
doftrans[s].InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < bnfi.Size(); k++)
@@ -1063,7 +1068,7 @@ void BlockNonlinearForm::MultBlocked(const BlockVector &bx,
for (int s=0; s<fes.Size(); ++s)
{
if (el_y[s]->Size() == 0) { continue; }
if (doftrans[s]) {doftrans[s]->TransformDual(*el_y[s]); }
doftrans[s].TransformDual(*el_y[s]);
by.GetBlock(s).AddElementVector(*(vdofs[s]), *el_y[s]);
}
}
@@ -1231,7 +1236,7 @@ void BlockNonlinearForm::ComputeGradientBlocked(const BlockVector &bx) const
Array<const FiniteElement *>fe(fes.Size());
Array<const FiniteElement *>fe2(fes.Size());
ElementTransformation * T;
Array<DofTransformation *> doftrans(fes.Size()); doftrans = nullptr;
std::vector<DofTransformation> doftrans(fes.Size());
Mesh *mesh = fes[0]->GetMesh();
for (int i=0; i<fes.Size(); ++i)
@@ -1293,9 +1298,9 @@ void BlockNonlinearForm::ComputeGradientBlocked(const BlockVector &bx) const
for (int s = 0; s < fes.Size(); ++s)
{
fe[s] = fes[s]->GetFE(i);
doftrans[s] = fes[s]->GetElementVDofs(i, *vdofs[s]);
fes[s]->GetElementVDofs(i, *vdofs[s], doftrans[s]);
bx.GetBlock(s).GetSubVector(*vdofs[s], *el_x[s]);
if (doftrans[s]) {doftrans[s]->InvTransformPrimal(*el_x[s]); }
doftrans[s].InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < dnfi.Size(); ++k)
@@ -1310,10 +1315,7 @@ void BlockNonlinearForm::ComputeGradientBlocked(const BlockVector &bx) const
for (int l=0; l<fes.Size(); ++l)
{
if (elmats(j,l)->Height() == 0) { continue; }
if (doftrans[j] || doftrans[l])
{
TransformDual(doftrans[j], doftrans[l], *elmats(j,l));
}
TransformDual(doftrans[j], doftrans[l], *elmats(j,l));
Grads(j,l)->AddSubMatrix(*vdofs[j], *vdofs[l],
*elmats(j,l), skip_zeros);
}
@@ -1354,9 +1356,9 @@ void BlockNonlinearForm::ComputeGradientBlocked(const BlockVector &bx) const
for (int s = 0; s < fes.Size(); ++s)
{
fe[s] = fes[s]->GetBE(i);
doftrans[s] = fes[s]->GetBdrElementVDofs(i, *(vdofs[s]));
fes[s]->GetBdrElementVDofs(i, *(vdofs[s]), doftrans[s]);
bx.GetBlock(s).GetSubVector(*(vdofs[s]), *el_x[s]);
if (doftrans[s]) {doftrans[s]->InvTransformPrimal(*el_x[s]); }
doftrans[s].InvTransformPrimal(*el_x[s]);
}
for (int k = 0; k < bnfi.Size(); k++)
@@ -1371,10 +1373,7 @@ void BlockNonlinearForm::ComputeGradientBlocked(const BlockVector &bx) const
for (int l=0; l<fes.Size(); ++l)
{
if (elmats(j,l)->Height() == 0) { continue; }
if (doftrans[j] || doftrans[l])
{
TransformDual(doftrans[j], doftrans[l], *elmats(j,l));
}
TransformDual(doftrans[j], doftrans[l], *elmats(j,l));
Grads(j,l)->AddSubMatrix(*vdofs[j], *vdofs[l],
*elmats(j,l), skip_zeros);
}
+6 -1
View File
@@ -561,6 +561,8 @@ void ParFiniteElementSpace::ApplyLDofSigns(Table &el_dof) const
void ParFiniteElementSpace::GetElementDofs(int i, Array<int> &dofs,
DofTransformation &doftrans) const
{
doftrans.SetDofTransformation(nullptr);
if (elem_dof)
{
elem_dof->GetRow(i, dofs);
@@ -586,6 +588,8 @@ void ParFiniteElementSpace::GetElementDofs(int i, Array<int> &dofs,
void ParFiniteElementSpace::GetBdrElementDofs(int i, Array<int> &dofs,
DofTransformation &doftrans) const
{
doftrans.SetDofTransformation(nullptr);
if (bdr_elem_dof)
{
bdr_elem_dof->GetRow(i, dofs);
@@ -1687,6 +1691,8 @@ void ParFiniteElementSpace::ExchangeFaceNbrData()
void ParFiniteElementSpace::GetFaceNbrElementVDofs(
int i, Array<int> &vdofs, DofTransformation &doftrans) const
{
doftrans.SetDofTransformation(nullptr);
face_nbr_element_dof.GetRow(i, vdofs);
if (DoFTransArray[GetFaceNbrFE(i)->GetGeomType()])
@@ -1703,7 +1709,6 @@ void ParFiniteElementSpace::GetFaceNbrElementVDofs(
DofTransformation *ParFiniteElementSpace::GetFaceNbrElementVDofs(
int i, Array<int> &vdofs) const
{
DoFTrans.SetDofTransformation(NULL);
GetFaceNbrElementVDofs(i, vdofs, DoFTrans);
return DoFTrans.GetDofTransformation() ? &DoFTrans : NULL;
}
+12
View File
@@ -577,7 +577,13 @@ public:
void Mult(const Vector &x, Vector &y) const override;
void AbsMult(const Vector &x, Vector &y) const override
{ Mult(x,y); }
void MultTranspose(const Vector &x, Vector &y) const override;
void AbsMultTranspose(const Vector &x, Vector &y) const override
{ MultTranspose(x,y); }
};
/// Auxiliary device class used by ParFiniteElementSpace.
@@ -628,7 +634,13 @@ public:
void Mult(const Vector &x, Vector &y) const override;
void AbsMult(const Vector &x, Vector &y) const override
{ Mult(x,y); }
void MultTranspose(const Vector &x, Vector &y) const override;
void AbsMultTranspose(const Vector &x, Vector &y) const override
{ MultTranspose(x,y); }
};
}
+36 -50
View File
@@ -55,22 +55,16 @@ ParGridFunction::ParGridFunction(ParMesh *pmesh, const GridFunction *gf,
int element_counter = 0;
const int MyRank = pfes->GetMyRank();
const int glob_ne = glob_fes->GetNE();
DofTransformation ltrans, gtrans;
for (int i = 0; i < glob_ne; i++)
{
if (partitioning[i] == MyRank)
{
const DofTransformation* const ltrans = pfes->GetElementVDofs(element_counter,
lvdofs);
const DofTransformation* const gtrans = glob_fes->GetElementVDofs(i, gvdofs);
pfes->GetElementVDofs(element_counter, lvdofs, ltrans);
glob_fes->GetElementVDofs(i, gvdofs, gtrans);
gf->GetSubVector(gvdofs, lnodes);
if (gtrans)
{
gtrans->InvTransformPrimal(lnodes);
}
if (ltrans)
{
ltrans->TransformPrimal(lnodes);
}
gtrans.InvTransformPrimal(lnodes);
ltrans.TransformPrimal(lnodes);
SetSubVector(lvdofs, lnodes);
element_counter++;
}
@@ -279,11 +273,11 @@ const
Array<int> dofs;
Vector DofVal, LocVec;
const int nbr_el_no = i - pfes->GetParMesh()->GetNE();
DofTransformation doftrans;
if (nbr_el_no >= 0)
{
int fes_vdim = pfes->GetVDim();
const DofTransformation* const doftrans = pfes->GetFaceNbrElementVDofs(
nbr_el_no, dofs);
pfes->GetFaceNbrElementVDofs(nbr_el_no, dofs, doftrans);
// Choose fe to be of the order whose number of DOFs matches dofs.Size(),
// in the variable order case.
const int ndofs = pfes->IsVariableOrder() ? dofs.Size() : 0;
@@ -302,10 +296,7 @@ const
face_nbr_data.GetSubVector(dofs, LocVec);
DofVal.SetSize(dofs.Size());
}
if (doftrans)
{
doftrans->InvTransformPrimal(LocVec);
}
doftrans.InvTransformPrimal(LocVec);
if (fe->GetMapType() == FiniteElement::VALUE)
{
@@ -321,7 +312,7 @@ const
}
else
{
const DofTransformation* const doftrans = fes->GetElementDofs(i, dofs);
fes->GetElementDofs(i, dofs, doftrans);
fes->DofsToVDofs(vdim-1, dofs);
DofVal.SetSize(dofs.Size());
const FiniteElement *fe = fes->GetFE(i);
@@ -336,10 +327,7 @@ const
fe->CalcPhysShape(*Tr, DofVal);
}
GetSubVector(dofs, LocVec);
if (doftrans)
{
doftrans->InvTransformPrimal(LocVec);
}
doftrans.InvTransformPrimal(LocVec);
}
return (DofVal * LocVec);
@@ -352,15 +340,11 @@ void ParGridFunction::GetVectorValue(int i, const IntegrationPoint &ip,
if (nbr_el_no >= 0)
{
Array<int> dofs;
const DofTransformation* const doftrans = pfes->GetFaceNbrElementVDofs(
nbr_el_no,
dofs);
DofTransformation doftrans;
pfes->GetFaceNbrElementVDofs(nbr_el_no, dofs, doftrans);
Vector loc_data;
face_nbr_data.GetSubVector(dofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
const FiniteElement *FElem = pfes->GetFaceNbrFE(nbr_el_no);
int dof = FElem->GetDof();
if (FElem->GetRangeType() == FiniteElement::SCALAR)
@@ -428,8 +412,8 @@ real_t ParGridFunction::GetValue(ElementTransformation &T,
Array<int> dofs;
const FiniteElement * fe = pfes->GetFaceNbrFE(nbr_el_no);
const DofTransformation* const doftrans = pfes->GetFaceNbrElementVDofs(
nbr_el_no, dofs);
DofTransformation doftrans;
pfes->GetFaceNbrElementVDofs(nbr_el_no, dofs, doftrans);
pfes->DofsToVDofs(comp-1, dofs);
Vector DofVal(dofs.Size()), LocVec;
@@ -442,10 +426,7 @@ real_t ParGridFunction::GetValue(ElementTransformation &T,
fe->CalcPhysShape(T, DofVal);
}
face_nbr_data.GetSubVector(dofs, LocVec);
if (doftrans)
{
doftrans->InvTransformPrimal(LocVec);
}
doftrans.InvTransformPrimal(LocVec);
return (DofVal * LocVec);
@@ -476,13 +457,11 @@ void ParGridFunction::GetVectorValue(ElementTransformation &T,
}
Array<int> vdofs;
DofTransformation * doftrans = pfes->GetFaceNbrElementVDofs(nbr_el_no, vdofs);
DofTransformation doftrans;
pfes->GetFaceNbrElementVDofs(nbr_el_no, vdofs, doftrans);
Vector loc_data;
face_nbr_data.GetSubVector(vdofs, loc_data);
if (doftrans)
{
doftrans->InvTransformPrimal(loc_data);
}
doftrans.InvTransformPrimal(loc_data);
const FiniteElement *fe = pfes->GetFaceNbrFE(nbr_el_no);
const int dof = fe->GetDof();
@@ -1335,25 +1314,20 @@ real_t L2ZZErrorEstimator(BilinearFormIntegrator &flux_integrator,
ParFiniteElementSpace *xfes = x.ParFESpace();
Array<int> xdofs, fdofs;
Vector el_x, el_f;
DofTransformation xtrans, ftrans;
for (int i = 0; i < xfes->GetNE(); i++)
{
const DofTransformation* const xtrans = xfes->GetElementVDofs(i, xdofs);
xfes->GetElementVDofs(i, xdofs, xtrans);
x.GetSubVector(xdofs, el_x);
if (xtrans)
{
xtrans->InvTransformPrimal(el_x);
}
xtrans.InvTransformPrimal(el_x);
ElementTransformation *Transf = xfes->GetElementTransformation(i);
flux_integrator.ComputeElementFlux(*xfes->GetFE(i), *Transf, el_x,
*flux_fes.GetFE(i), el_f, false);
const DofTransformation* const ftrans = flux_fes.GetElementVDofs(i, fdofs);
if (ftrans)
{
ftrans->TransformPrimal(el_f);
}
flux_fes.GetElementVDofs(i, fdofs, ftrans);
ftrans.TransformPrimal(el_f);
flux.SetSubVector(fdofs, el_f);
}
@@ -1432,6 +1406,18 @@ real_t L2ZZErrorEstimator(BilinearFormIntegrator &flux_integrator,
return pow(glob_error, 1.0/norm_p);
}
PLBound ParGridFunction::GetBounds(Vector &lower, Vector &upper,
const int ref_factor, const int vdim)
{
PLBound plb = GridFunction::GetBounds(lower, upper, ref_factor, vdim);
int siz = vdim > 0 ? 1 : fes->GetVDim();
MPI_Allreduce(MPI_IN_PLACE, lower.HostReadWrite(), siz,
MFEM_MPI_REAL_T, MPI_MIN, pfes->GetComm());
MPI_Allreduce(MPI_IN_PLACE, upper.HostReadWrite(), siz,
MFEM_MPI_REAL_T, MPI_MAX, pfes->GetComm());
return plb;
}
} // namespace mfem
#endif // MFEM_USE_MPI
+12
View File
@@ -300,12 +300,16 @@ public:
real_t ComputeL1Error(Coefficient *exsol[],
const IntegrationRule *irs[] = NULL) const override
{
#ifdef MFEM_HAVE_GCC_PRAGMA_DIAGNOSTIC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
real_t glb_err = GlobalLpNorm(1.0,
GridFunction::ComputeL1Error(exsol, irs),
pfes->GetComm());
#ifdef MFEM_HAVE_GCC_PRAGMA_DIAGNOSTIC
#pragma GCC diagnostic pop
#endif
return glb_err;
}
@@ -577,6 +581,14 @@ public:
GridFunction &flux,
bool wcoef = true, int subdomain = -1) override;
/// Computes the PLBound for the gridfunction with number of control
/// points based on @a ref_factor, and returns the bounds for each
/// vdim across all elements in @b lower and @b upper. We also return the
/// PLBound object used to compute the bounds. Note: if vdim < 1, we compute
/// the bounds for each vector dimension.
PLBound GetBounds(Vector &lower, Vector &upper,
const int ref_factor=1, const int vdim=-1) override;
/** Save the local portion of the ParGridFunction. This differs from the
serial GridFunction::Save in that it takes into account the signs of
the local dofs. */
+1 -1
View File
@@ -200,7 +200,7 @@ static void Det2DSurface(const int NE,
const real_t E = J(0,0)*J(0,0) + J(1,0)*J(1,0) + J(2,0)*J(2,0);
const real_t F = J(0,0)*J(0,1) + J(1,0)*J(1,1) + J(2,0)*J(2,1);
const real_t G = J(0,1)*J(0,1) + J(1,1)*J(1,1) + J(2,1)*J(2,1);
Y(qx,qy,e) = sqrt(E*G - F*F);
Y(qx,qy,e) = std::sqrt(E*G - F*F);
}
}
});
+3 -3
View File
@@ -326,7 +326,7 @@ static void Eval2D(const int NE,
const double E = j(0,0)*j(0,0) + j(1,0)*j(1,0) + j(2,0)*j(2,0);
const double F = j(0,0)*j(0,1) + j(1,0)*j(1,1) + j(2,0)*j(2,1);
const double G = j(0,1)*j(0,1) + j(1,1)*j(1,1) + j(2,1)*j(2,1);
det(q,e) = sqrt(E*G - F*F);
det(q,e) = std::sqrt(E*G - F*F);
}
}
}
@@ -566,8 +566,8 @@ void QuadratureInterpolator::Mult(const Vector &e_vec,
}
else // use_tensor_eval == false
{
EvalKernels::Run(dim, vdim, maps.ndof, maps.nqpt, ne,vdim,q_layout,
geom, maps,e_vec, q_val,q_der,q_det,eval_flags);
EvalKernels::Run(dim, vdim, maps.ndof, maps.nqpt, ne,vdim, q_layout,
geom, maps, e_vec, q_val, q_der, q_det, eval_flags);
}
}
+6 -5
View File
@@ -128,7 +128,7 @@ void ElementRestriction::Mult(const Vector& x, Vector& y) const
});
}
void ElementRestriction::MultUnsigned(const Vector& x, Vector& y) const
void ElementRestriction::AbsMult(const Vector& x, Vector& y) const
{
// Assumes all elements have the same number of dofs
const int nd = dof;
@@ -193,7 +193,7 @@ void ElementRestriction::AddMultTranspose(const Vector& x, Vector& y,
TAddMultTranspose<ADD>(x, y);
}
void ElementRestriction::MultTransposeUnsigned(const Vector& x, Vector& y) const
void ElementRestriction::AbsMultTranspose(const Vector& x, Vector& y) const
{
// Assumes all elements have the same number of dofs
const int nd = dof;
@@ -653,7 +653,8 @@ ConformingFaceRestriction::ConformingFaceRestriction(
: ConformingFaceRestriction(fes, f_ordering, type, true)
{ }
void ConformingFaceRestriction::Mult(const Vector& x, Vector& y) const
void ConformingFaceRestriction::MultInternal(const Vector& x, Vector& y,
const bool useAbs) const
{
if (nf==0) { return; }
// Assumes all elements have the same number of dofs
@@ -666,7 +667,7 @@ void ConformingFaceRestriction::Mult(const Vector& x, Vector& y) const
mfem::forall(nfdofs, [=] MFEM_HOST_DEVICE (int i)
{
const int s_idx = d_indices[i];
const int sgn = (s_idx >= 0) ? 1 : -1;
const int sgn = (useAbs || s_idx >= 0) ? 1 : -1;
const int idx = (s_idx >= 0) ? s_idx : -1 - s_idx;
const int dof = i % nface_dofs;
const int face = i / nface_dofs;
@@ -724,7 +725,7 @@ void ConformingFaceRestriction::AddMultTranspose(
true, a);
}
void ConformingFaceRestriction::AddMultTransposeUnsigned(
void ConformingFaceRestriction::AddAbsMultTranspose(
const Vector& x, Vector& y, const real_t a) const
{
ConformingFaceRestriction_AddMultTranspose(
+55 -7
View File
@@ -59,9 +59,18 @@ public:
const real_t a = 1.0) const override;
/// Compute Mult without applying signs based on DOF orientations.
void MultUnsigned(const Vector &x, Vector &y) const;
void AbsMult(const Vector &x, Vector &y) const override;
/// Compute MultTranspose without applying signs based on DOF orientations.
void MultTransposeUnsigned(const Vector &x, Vector &y) const;
void AbsMultTranspose(const Vector &x, Vector &y) const override;
/// @deprecated Use AbsMult() instead.
MFEM_DEPRECATED void MultUnsigned(const Vector &x, Vector &y) const
{ AbsMult(x, y); }
/// @deprecated Use AbsMultTranspose() instead.
MFEM_DEPRECATED void MultTransposeUnsigned(const Vector &x, Vector &y) const
{ AbsMultTranspose(x, y); }
/// Compute MultTranspose by setting (rather than adding) element
/// contributions; this is a left inverse of the Mult() operation
@@ -184,12 +193,19 @@ public:
/** @brief Add the face degrees of freedom @a x to the element degrees of
freedom @a y ignoring the signs from DOF orientation. */
virtual void AddMultTransposeUnsigned(const Vector &x, Vector &y,
const real_t a = 1.0) const
virtual void AddAbsMultTranspose(const Vector &x, Vector &y,
const real_t a = 1.0) const
{
AddMultTranspose(x, y, a);
}
/// @deprecated Use AddAbsMultTranspose() instead.
MFEM_DEPRECATED void AddMultTransposeUnsigned(const Vector &x, Vector &y,
const real_t a = 1.0) const
{
AddAbsMultTranspose(x, y, a);
}
/** @brief Add the face degrees of freedom @a x to the element degrees of
freedom @a y. Perform the same computation as AddMultTranspose, but
@a x is invalid after calling this method.
@@ -219,6 +235,12 @@ public:
AddMultTranspose(x, y);
}
void AbsMultTranspose(const Vector &x, Vector &y) const override
{
y = 0.0;
AddAbsMultTranspose(x, y);
}
/** @brief For each face, sets @a y to the partial derivative of @a x with
respect to the reference coordinate whose direction is
perpendicular to the face on the reference element.
@@ -319,7 +341,16 @@ public:
requested by @a type in the constructor.
The face_dofs are ordered according to the given
ElementDofOrdering. */
void Mult(const Vector &x, Vector &y) const override;
void Mult(const Vector &x, Vector &y) const override
{ MultInternal(x, y); }
/// Compute Mult without applying signs based on DOF orientations.
void AbsMult(const Vector &x, Vector &y) const override
{ MultInternal(x, y, true); }
/// @deprecated Use AbsMult() instead.
MFEM_DEPRECATED void MultUnsigned(const Vector &x, Vector &y) const
{ AbsMult(x, y); }
using FaceRestriction::AddMultTransposeInPlace;
@@ -341,8 +372,20 @@ public:
L-Vector @b not taking into account signs from DOF orientations.
@sa AddMultTranspose(). */
void AddMultTransposeUnsigned(const Vector &x, Vector &y,
const real_t a = 1.0) const override;
void AddAbsMultTranspose(const Vector &x, Vector &y,
const real_t a = 1.0) const override;
/// @deprecated Use AddAbsMultTranspose() instead.
MFEM_DEPRECATED void AddMultTransposeUnsigned(const Vector &x, Vector &y) const
{
AddAbsMultTranspose(x, y);
}
void AbsMultTranspose(const Vector &x, Vector &y) const override
{
y = 0.0;
AddAbsMultTranspose(x, y);
}
private:
/** @brief Compute the scatter indices: L-vector to E-vector, and the offsets
@@ -395,6 +438,11 @@ protected:
void SetFaceDofsGatherIndices(const Mesh::FaceInformation &face,
const int face_index,
const ElementDofOrdering f_ordering);
public:
// This method needs to be public due to 'nvcc' restriction.
void MultInternal(const Vector &x, Vector &y,
const bool useAbs = false) const;
};
/// @brief Alias for ConformingFaceRestriction, for backwards compatibility and
+2 -2
View File
@@ -22,9 +22,9 @@ namespace mfem
/* AD related definitions below ========================================*/
/// MFEM native AD-type for first derivatives
using AD1Type = internal::dual<real_t, real_t>;
using AD1Type = future::dual<real_t, real_t>;
/// MFEM native AD-type for second derivatives
using AD2Type = internal::dual<AD1Type, AD1Type>;
using AD2Type = future::dual<AD1Type, AD1Type>;
/*
Functions for 2x2 DenseMatrix cast as std::vector<type>, assuming column-major storage
+11 -20
View File
@@ -2100,10 +2100,11 @@ void PRefinementTransferOperator::Mult(const Vector& x, Vector& y) const
y = 0.0;
DofTransformation doftrans_h, doftrans_l;
for (int i = 0; i < mesh->GetNE(); i++)
{
DofTransformation * doftrans_h = hFESpace.GetElementDofs(i, h_dofs);
DofTransformation * doftrans_l = lFESpace.GetElementDofs(i, l_dofs);
hFESpace.GetElementDofs(i, h_dofs, doftrans_h);
lFESpace.GetElementDofs(i, l_dofs, doftrans_l);
const Geometry::Type geom = mesh->GetElementBaseGeometry(i);
if (geom != cached_geom || isvar_order)
@@ -2123,15 +2124,9 @@ void PRefinementTransferOperator::Mult(const Vector& x, Vector& y) const
h_dofs.Copy(h_vdofs);
hFESpace.DofsToVDofs(vd, h_vdofs);
x.GetSubVector(l_vdofs, subX);
if (doftrans_l)
{
doftrans_l->InvTransformPrimal(subX);
}
doftrans_l.InvTransformPrimal(subX);
loc_prol.Mult(subX, subY);
if (doftrans_h)
{
doftrans_h->TransformPrimal(subY);
}
doftrans_h.TransformPrimal(subY);
y.SetSubVector(h_vdofs, subY);
}
}
@@ -2157,10 +2152,12 @@ void PRefinementTransferOperator::MultTranspose(const Vector& x,
int vdim = lFESpace.GetVDim();
DofTransformation doftrans_h, doftrans_l;
for (int i = 0; i < mesh->GetNE(); i++)
{
DofTransformation * doftrans_h = hFESpace.GetElementDofs(i, h_dofs);
DofTransformation * doftrans_l = lFESpace.GetElementDofs(i, l_dofs);
hFESpace.GetElementDofs(i, h_dofs, doftrans_h);
lFESpace.GetElementDofs(i, l_dofs, doftrans_l);
const Geometry::Type geom = mesh->GetElementBaseGeometry(i);
if (geom != cached_geom || isvar_order)
@@ -2182,10 +2179,7 @@ void PRefinementTransferOperator::MultTranspose(const Vector& x,
hFESpace.DofsToVDofs(vd, h_vdofs);
x.GetSubVector(h_vdofs, subX);
if (doftrans_h)
{
doftrans_h->InvTransformDual(subX);
}
doftrans_h.InvTransformDual(subX);
for (int p = 0; p < h_dofs.Size(); ++p)
{
if (processed[lFESpace.DecodeDof(h_dofs[p])])
@@ -2195,10 +2189,7 @@ void PRefinementTransferOperator::MultTranspose(const Vector& x,
}
loc_prol.Mult(subX, subY);
if (doftrans_l)
{
doftrans_l->TransformDual(subY);
}
doftrans_l.TransformDual(subY);
y.AddElementVector(l_vdofs, subY);
}
+14
View File
@@ -15,6 +15,7 @@
#include "array.hpp"
#include "../general/forall.hpp"
#include <fstream>
#include <type_traits>
namespace mfem
{
@@ -110,6 +111,19 @@ void Array<T>::PartialSum()
}
}
template <class T>
void Array<T>::Abs()
{
static_assert(std::is_arithmetic<T>::value, "Use with arithmetic types!");
const bool useDevice = UseDevice();
const int N = size;
auto y = ReadWrite(useDevice);
mfem::forall_switch(useDevice, N, [=] MFEM_HOST_DEVICE (int i)
{
y[i] = std::abs(y[i]);
});
}
// Sum
template <class T>
T Array<T>::Sum() const
+10
View File
@@ -56,6 +56,10 @@ protected:
static_assert(std::is_trivial<T>::value, "type T must be trivial");
public:
using value_type = T; ///< Type alias for stl.
using reference = T&; ///< Type alias for stl.
using const_reference = const T&; ///< Type alias for stl.
friend void Swap<T>(Array<T> &, Array<T> &);
/// Creates an empty array
@@ -174,6 +178,9 @@ public:
/// Append element 'el' to array, resize if necessary.
inline int Append(const T & el);
/// STL-like push_back. Append element 'el' to array, resize if necessary.
void push_back(const T &el) { Append(el); }
/// Append another array to this array, resize if necessary.
inline int Append(const T *els, int nels);
@@ -298,6 +305,9 @@ public:
/// Fill the entries of the array with the cumulative sum of the entries.
void PartialSum();
/// Replace each entry of the array with its absolute value.
void Abs();
/// Return the sum of all the array entries using the '+'' operator for class 'T'.
T Sum() const;
+2 -2
View File
@@ -186,7 +186,7 @@ void Device::Configure(const std::string &device, const int device_id)
// and avoid the 'singleton_device' to destroy the mm.
if (device_env)
{
std::memcpy(this, &Get(), sizeof(Device));
std::memcpy((void*)this, &Get(), sizeof(Device));
Get().destroy_mm = false;
return;
}
@@ -243,7 +243,7 @@ void Device::Configure(const std::string &device, const int device_id)
Get().UpdateMemoryTypeAndClass(device_option);
// Copy all data members from the global 'singleton_device' into '*this'.
if (this != &Get()) { std::memcpy(this, &Get(), sizeof(Device)); }
if (this != &Get()) { std::memcpy((void*)this, &Get(), sizeof(Device)); }
// Only '*this' will call the MemoryManager::Destroy() method.
destroy_mm = true;
+13 -13
View File
@@ -187,33 +187,33 @@ public:
/** The string parameter @a device must be a comma-separated list of backend
string names (see below). The @a device_id argument specifies the ID of
the actual devices (e.g. GPU) to use.
* The available backends are described by the Backend class.
* The string name of a backend is the lowercase version of the
- The available backends are described by the Backend class.
- The string name of a backend is the lowercase version of the
Backend::Id enumeration constant with '_' replaced by '-', e.g. the
string name of 'RAJA_CPU' is 'raja-cpu'. The string name of the debug
backend (Backend::Id 'DEBUG_DEVICE') is exceptionally set to 'debug'.
* The 'cpu' backend is always enabled with lowest priority.
* The current backend priority from highest to lowest is:
- The 'cpu' backend is always enabled with lowest priority.
- The current backend priority from highest to lowest is:
'ceed-cuda', 'occa-cuda', 'raja-cuda', 'cuda',
'ceed-hip', 'hip', 'debug',
'occa-omp', 'raja-omp', 'omp',
'ceed-cpu', 'occa-cpu', 'raja-cpu', 'cpu'.
* Multiple backends can be configured at the same time.
* Only one 'occa-*' backend can be configured at a time.
* The backend 'occa-cuda' enables the 'cuda' backend unless 'raja-cuda'
- Multiple backends can be configured at the same time.
- Only one 'occa-*' backend can be configured at a time.
- The backend 'occa-cuda' enables the 'cuda' backend unless 'raja-cuda'
is already enabled.
* The backend 'occa-omp' enables the 'omp' backend (if MFEM was built
- The backend 'occa-omp' enables the 'omp' backend (if MFEM was built
with MFEM_USE_OPENMP=YES) unless 'raja-omp' is already enabled.
* Only one 'ceed-*' backend can be configured at a time.
* The backend 'ceed-cpu' delegates to a libCEED CPU backend the setup and
- Only one 'ceed-*' backend can be configured at a time.
- The backend 'ceed-cpu' delegates to a libCEED CPU backend the setup and
evaluation of the operator.
* The backend 'ceed-cuda' delegates to a libCEED CUDA backend the setup
- The backend 'ceed-cuda' delegates to a libCEED CUDA backend the setup
and evaluation of operators and enables the 'cuda' backend to avoid
transfers between host and device.
* The backend 'ceed-hip' delegates to a libCEED HIP backend the setup
- The backend 'ceed-hip' delegates to a libCEED HIP backend the setup
and evaluation of operators and enables the 'hip' backend to avoid
transfers between host and device.
* The 'debug' backend should not be combined with other device backends.
- The 'debug' backend should not be combined with other device backends.
@note If the device is actually enabled, this method will also update the
current host/device MemoryType and MemoryClass. */
+18
View File
@@ -9,6 +9,7 @@
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../config/config.hpp"
#ifndef MFEM_ENZYME_HPP
#define MFEM_ENZYME_HPP
@@ -25,11 +26,28 @@ extern int enzyme_dup;
extern int enzyme_dupnoneed;
extern int enzyme_out;
extern int enzyme_const;
extern int enzyme_interleave;
#if defined(MFEM_USE_CUDA) || defined(MFEM_USE_HIP)
#define MFEM_DEVICE_EXTERN_STMT(name) extern __device__ int name;
#else
#define MFEM_DEVICE_EXTERN_STMT(name)
#endif
MFEM_DEVICE_EXTERN_STMT(enzyme_dup)
MFEM_DEVICE_EXTERN_STMT(enzyme_dupnoneed)
MFEM_DEVICE_EXTERN_STMT(enzyme_out)
MFEM_DEVICE_EXTERN_STMT(enzyme_const)
MFEM_DEVICE_EXTERN_STMT(enzyme_interleave)
// warning: if inlined, triggers function '__enzyme_autodiff' is not defined
template <typename return_type, typename... Args>
MFEM_HOST_DEVICE
return_type __enzyme_autodiff(Args...);
// warning: if inlined, triggers function '__enzyme_fwddiff' is not defined
template <typename return_type, typename... Args>
MFEM_HOST_DEVICE
return_type __enzyme_fwddiff(Args...);
#define MFEM_ENZYME_INACTIVENOFREE __attribute__((enzyme_inactive, enzyme_nofree))
+4 -156
View File
@@ -23,9 +23,6 @@
#include <_hypre_utilities.h>
#endif
#include "array.hpp"
#include "reducers.hpp"
namespace mfem
{
@@ -162,7 +159,11 @@ private:
// MFEM_UNROLL pragma macro that can be used inside MFEM_FORALL macros.
#if defined(MFEM_USE_CUDA) && defined(__CUDA_ARCH__)
#ifdef __NVCC__
#define MFEM_UNROLL(N) MFEM_PRAGMA(unroll(N))
#else // Assuming Clang CUDA
#define MFEM_UNROLL(N) MFEM_PRAGMA(unroll N)
#endif
#else
#define MFEM_UNROLL(N)
#endif
@@ -849,159 +850,6 @@ inline MemoryClass GetHypreForallMemoryClass()
#endif // MFEM_USE_MPI
namespace internal
{
/**
@brief Device portion of a reduction over a 1D sequence [0, N)
@tparam B Reduction body. Must be callable with the signature void(int i, value_type&
v), where i is the index to evaluate and v is the value to update.
@tparam R Reducer capable of combining values of type value_type. See reducers.hpp for
pre-defined reducers.
*/
template<class B, class R> struct reduction_kernel
{
/// value type body and reducer operate on.
using value_type = typename R::value_type;
/// workspace for the intermediate reduction results
mutable value_type *work;
B body;
R reducer;
/// Length of sequence to reduce over.
int N;
/// How many items is each thread responsible for during the serial phase
int items_per_thread;
constexpr static MFEM_HOST_DEVICE int max_blocksize() { return 256; }
/// helper for computing the reduction block size
static int block_log2(unsigned N)
{
#if defined(__GNUC__) or defined(__clang__)
return N ? (sizeof(unsigned) * 8 - __builtin_clz(N)) : 0;
#elif defined(_MSC_VER)
return sizeof(unsigned) * 8 - __lzclz(N);
#else
int res = 0;
while (N)
{
N >>= 1;
++res;
}
return res;
#endif
}
MFEM_HOST_DEVICE void operator()(int work_idx) const
{
MFEM_SHARED value_type buffer[max_blocksize()];
reducer.SetInitialValue(buffer[MFEM_THREAD_ID(x)]);
// serial part
for (int idx = 0; idx < items_per_thread; ++idx)
{
int i = MFEM_THREAD_ID(x) +
(idx + work_idx * items_per_thread) * MFEM_THREAD_SIZE(x);
if (i < N)
{
body(i, buffer[MFEM_THREAD_ID(x)]);
}
else
{
break;
}
}
// binary tree reduction
for (int i = (MFEM_THREAD_SIZE(x) >> 1); i > 0; i >>= 1)
{
MFEM_SYNC_THREAD;
if (MFEM_THREAD_ID(x) < i)
{
reducer.Join(buffer[MFEM_THREAD_ID(x)], buffer[MFEM_THREAD_ID(x) + i]);
}
}
if (MFEM_THREAD_ID(x) == 0)
{
work[work_idx] = buffer[0];
}
}
};
}
/**
@brief Performs a 1D reduction on the range [0,N).
@a res initial value and where the result will be written.
@a body reduction function body.
@a reducer helper for joining two reduced values.
@a use_dev true to perform the reduction on the device, if possible.
@a workspace temporary workspace used for device reductions. May be resized to
a larger capacity as needed. Preferably should have MemoryType::MANAGED or
MemoryType::HOST_PINNED. TODO: replace with internal temporary workspace
vectors once that's added to the memory manager.
@tparam T value_type to operate on
*/
template <class T, class B, class R>
void reduce(int N, T &res, B &&body, const R &reducer, bool use_dev,
Array<T> &workspace)
{
if (N == 0)
{
return;
}
#if defined(MFEM_USE_HIP) || defined(MFEM_USE_CUDA)
if (use_dev &&
mfem::Device::Allows(Backend::CUDA | Backend::HIP | Backend::RAJA_CUDA |
Backend::RAJA_HIP))
{
using red_type = internal::reduction_kernel<typename std::decay<B>::type,
typename std::decay<R>::type>;
// max block size is 256, but can be smaller
int block_size = std::min<int>(red_type::max_blocksize(),
1ll << red_type::block_log2(N));
int num_mp = Device::NumMultiprocessors(Device::GetId());
#if defined(MFEM_USE_CUDA)
// good value of mp_sat found experimentally on Lassen
constexpr int mp_sat = 8;
#elif defined(MFEM_USE_HIP)
// good value of mp_sat found experimentally on Tuolumne
constexpr int mp_sat = 4;
#else
num_mp = 1;
constexpr int mp_sat = 1;
#endif
// determine how many items each thread should sum during the serial
// portion
int nblocks = std::min(mp_sat * num_mp, (N + block_size - 1) / block_size);
int items_per_thread =
(N + block_size * nblocks - 1) / (block_size * nblocks);
red_type red{nullptr, std::forward<B>(body), reducer, N, items_per_thread};
// allocate res to fit block_size entries
auto mt = workspace.GetMemory().GetMemoryType();
if (mt != MemoryType::HOST_PINNED && mt != MemoryType::MANAGED)
{
mt = MemoryType::HOST_PINNED;
}
workspace.SetSize(nblocks, mt);
auto work = workspace.HostWrite();
red.work = work;
forall_2D(nblocks, block_size, 1, std::move(red));
// wait for results
MFEM_DEVICE_SYNC;
for (int i = 0; i < nblocks; ++i)
{
reducer.Join(res, work[i]);
}
return;
}
#endif
for (int i = 0; i < N; ++i)
{
body(i, res);
}
}
} // namespace mfem
#endif // MFEM_FORALL_HPP
+1 -1
View File
@@ -641,7 +641,7 @@ public:
UmpireMemorySpace(name, "DEVICE") {}
void Alloc(Memory &base) override
{ base.d_ptr = allocator.allocate(base.bytes); }
void Dealloc(Memory &base) override { rm.deallocate(base.d_ptr); }
void Dealloc(Memory &base) override { allocator.deallocate(base.d_ptr); }
void *HtoD(void *dst, const void *src, size_t bytes) override
{
#ifdef MFEM_USE_CUDA
+156 -3
View File
@@ -12,11 +12,10 @@
#ifndef MFEM_REDUCERS_HPP
#define MFEM_REDUCERS_HPP
#include "array.hpp"
#include "forall.hpp"
#include <climits>
#include <cmath>
#include <cstdint>
#include <limits>
#include <type_traits>
@@ -439,6 +438,160 @@ template <class I> struct ArgMinMaxReducer<double, I>
}
};
namespace internal
{
/**
@brief Device portion of a reduction over a 1D sequence [0, N)
@tparam B Reduction body. Must be callable with the signature void(int i, value_type&
v), where i is the index to evaluate and v is the value to update.
@tparam R Reducer capable of combining values of type value_type. See reducers.hpp for
pre-defined reducers.
*/
template<class B, class R> struct reduction_kernel
{
/// value type body and reducer operate on.
using value_type = typename R::value_type;
/// workspace for the intermediate reduction results
mutable value_type *work;
B body;
R reducer;
/// Length of sequence to reduce over.
int N;
/// How many items is each thread responsible for during the serial phase
int items_per_thread;
constexpr static MFEM_HOST_DEVICE int max_blocksize() { return 256; }
/// helper for computing the reduction block size
static int block_log2(unsigned N)
{
#if defined(__GNUC__) or defined(__clang__)
return N ? (sizeof(unsigned) * 8 - __builtin_clz(N)) : 0;
#elif defined(_MSC_VER)
return sizeof(unsigned) * 8 - __lzclz(N);
#else
int res = 0;
while (N)
{
N >>= 1;
++res;
}
return res;
#endif
}
MFEM_HOST_DEVICE void operator()(int work_idx) const
{
MFEM_SHARED value_type buffer[max_blocksize()];
reducer.SetInitialValue(buffer[MFEM_THREAD_ID(x)]);
// serial part
for (int idx = 0; idx < items_per_thread; ++idx)
{
int i = MFEM_THREAD_ID(x) +
(idx + work_idx * items_per_thread) * MFEM_THREAD_SIZE(x);
if (i < N)
{
body(i, buffer[MFEM_THREAD_ID(x)]);
}
else
{
break;
}
}
// binary tree reduction
for (int i = (MFEM_THREAD_SIZE(x) >> 1); i > 0; i >>= 1)
{
MFEM_SYNC_THREAD;
if (MFEM_THREAD_ID(x) < i)
{
reducer.Join(buffer[MFEM_THREAD_ID(x)], buffer[MFEM_THREAD_ID(x) + i]);
}
}
if (MFEM_THREAD_ID(x) == 0)
{
work[work_idx] = buffer[0];
}
}
};
}
/**
@brief Performs a 1D reduction on the range [0,N).
@a res initial value and where the result will be written.
@a body reduction function body.
@a reducer helper for joining two reduced values.
@a use_dev true to perform the reduction on the device, if possible.
@a workspace temporary workspace used for device reductions. May be resized to
a larger capacity as needed. Preferably should have MemoryType::MANAGED or
MemoryType::HOST_PINNED. TODO: replace with internal temporary workspace
vectors once that's added to the memory manager.
@tparam T value_type to operate on
*/
template <class T, class B, class R>
void reduce(int N, T &res, B &&body, const R &reducer, bool use_dev,
Array<T> &workspace)
{
if (N == 0)
{
return;
}
#if defined(MFEM_USE_HIP) || defined(MFEM_USE_CUDA)
if (use_dev &&
mfem::Device::Allows(Backend::CUDA | Backend::HIP | Backend::RAJA_CUDA |
Backend::RAJA_HIP))
{
using red_type = internal::reduction_kernel<typename std::decay<B>::type,
typename std::decay<R>::type>;
// max block size is 256, but can be smaller
int block_size = std::min<int>(red_type::max_blocksize(),
1ll << red_type::block_log2(N));
int num_mp = Device::NumMultiprocessors(Device::GetId());
#if defined(MFEM_USE_CUDA)
// good value of mp_sat found experimentally on Lassen
constexpr int mp_sat = 8;
#elif defined(MFEM_USE_HIP)
// good value of mp_sat found experimentally on Tuolumne
constexpr int mp_sat = 4;
#else
num_mp = 1;
constexpr int mp_sat = 1;
#endif
// determine how many items each thread should sum during the serial
// portion
int nblocks = std::min(mp_sat * num_mp, (N + block_size - 1) / block_size);
int items_per_thread =
(N + block_size * nblocks - 1) / (block_size * nblocks);
red_type red{nullptr, std::forward<B>(body), reducer, N, items_per_thread};
// allocate res to fit block_size entries
auto mt = workspace.GetMemory().GetMemoryType();
if (mt != MemoryType::HOST_PINNED && mt != MemoryType::MANAGED)
{
mt = MemoryType::HOST_PINNED;
}
workspace.SetSize(nblocks, mt);
auto work = workspace.HostWrite();
red.work = work;
forall_2D(nblocks, block_size, 1, std::move(red));
// wait for results
MFEM_DEVICE_SYNC;
for (int i = 0; i < nblocks; ++i)
{
reducer.Join(res, work[i]);
}
return;
}
#endif
for (int i = 0; i < N; ++i)
{
body(i, res);
}
}
} // namespace mfem
#endif
#endif // MFEM_REDUCERS_HPP
+6 -3
View File
@@ -73,9 +73,6 @@ const char *GetConfigStr()
#ifdef MFEM_USE_AMGX
"MFEM_USE_AMGX\n"
#endif
#ifdef MFEM_USE_MAGMA
"MFEM_USE_MAGMA\n"
#endif
#ifdef MFEM_USE_CEED
"MFEM_USE_CEED\n"
#endif
@@ -88,6 +85,9 @@ const char *GetConfigStr()
#ifdef MFEM_USE_DOUBLE
"MFEM_USE_DOUBLE\n"
#endif
#ifdef MFEM_USE_ENZYME
"MFEM_USE_ENZYME\n"
#endif
#ifdef MFEM_USE_EXCEPTIONS
"MFEM_USE_EXCEPTIONS\n"
#endif
@@ -118,6 +118,9 @@ const char *GetConfigStr()
#ifdef MFEM_USE_LIBUNWIND
"MFEM_USE_LIBUNWIND\n"
#endif
#ifdef MFEM_USE_MAGMA
"MFEM_USE_MAGMA\n"
#endif
#ifdef MFEM_USE_MEMALLOC
"MFEM_USE_MEMALLOC\n"
#endif
+25 -28
View File
@@ -124,24 +124,21 @@ const real_t &DenseMatrix::Elem(int i, int j) const
void DenseMatrix::Mult(const real_t *x, real_t *y) const
{
HostRead();
kernels::Mult(height, width, Data(), x, y);
kernels::Mult(height, width, HostRead(), x, y);
}
void DenseMatrix::Mult(const real_t *x, Vector &y) const
{
MFEM_ASSERT(height == y.Size(), "incompatible dimensions");
y.HostReadWrite();
Mult(x, y.GetData());
Mult(x, y.HostWrite());
}
void DenseMatrix::Mult(const Vector &x, real_t *y) const
{
MFEM_ASSERT(width == x.Size(), "incompatible dimensions");
x.HostRead();
Mult(x.GetData(), y);
Mult(x.HostRead(), y);
}
void DenseMatrix::Mult(const Vector &x, Vector &y) const
@@ -149,9 +146,15 @@ void DenseMatrix::Mult(const Vector &x, Vector &y) const
MFEM_ASSERT(height == y.Size() && width == x.Size(),
"incompatible dimensions");
x.HostRead();
y.HostReadWrite();
Mult(x.GetData(), y.GetData());
Mult(x.HostRead(), y.HostWrite());
}
void DenseMatrix::AbsMult(const Vector &x, Vector &y) const
{
MFEM_ASSERT(height == y.Size() && width == x.Size(),
"incompatible dimensions");
kernels::AbsMult(height, width, HostRead(), x.HostRead(), y.HostWrite());
}
real_t DenseMatrix::operator *(const DenseMatrix &m) const
@@ -171,34 +174,21 @@ real_t DenseMatrix::operator *(const DenseMatrix &m) const
void DenseMatrix::MultTranspose(const real_t *x, real_t *y) const
{
HostRead();
real_t *d_col = Data();
for (int col = 0; col < width; col++)
{
real_t y_col = 0.0;
for (int row = 0; row < height; row++)
{
y_col += x[row]*d_col[row];
}
y[col] = y_col;
d_col += height;
}
kernels::MultTranspose(height, width, HostRead(), x, y);
}
void DenseMatrix::MultTranspose(const real_t *x, Vector &y) const
{
MFEM_ASSERT(width == y.Size(), "incompatible dimensions");
y.HostReadWrite();
MultTranspose(x, y.GetData());
MultTranspose(x, y.HostWrite());
}
void DenseMatrix::MultTranspose(const Vector &x, real_t *y) const
{
MFEM_ASSERT(height == x.Size(), "incompatible dimensions");
x.HostRead();
MultTranspose(x.GetData(), y);
MultTranspose(x.HostRead(), y);
}
void DenseMatrix::MultTranspose(const Vector &x, Vector &y) const
@@ -206,9 +196,16 @@ void DenseMatrix::MultTranspose(const Vector &x, Vector &y) const
MFEM_ASSERT(height == x.Size() && width == y.Size(),
"incompatible dimensions");
x.HostRead();
y.HostReadWrite();
MultTranspose(x.GetData(), y.GetData());
MultTranspose(x.HostRead(), y.HostWrite());
}
void DenseMatrix::AbsMultTranspose(const Vector &x, Vector &y) const
{
MFEM_ASSERT(height == x.Size() && width == y.Size(),
"incompatible dimensions");
kernels::AbsMultTranspose(height, width, HostRead(),
x.HostRead(), y.HostWrite());
}
void DenseMatrix::AddMult(const Vector &x, Vector &y, const real_t a) const
+6
View File
@@ -153,6 +153,9 @@ public:
/// Matrix vector multiplication.
void Mult(const Vector &x, Vector &y) const override;
/// Absolute-value matrix vector multiplication.
void AbsMult(const Vector &x, Vector &y) const override;
/// Multiply a vector with the transpose matrix.
void MultTranspose(const real_t *x, real_t *y) const;
@@ -165,6 +168,9 @@ public:
/// Multiply a vector with the transpose matrix.
void MultTranspose(const Vector &x, Vector &y) const override;
/// Multiply a vector with the absolute-value transpose matrix.
void AbsMultTranspose(const Vector &x, Vector &y) const override;
using Operator::Mult;
using Operator::MultTranspose;
+9 -2
View File
@@ -13,6 +13,7 @@
#define MFEM_DTENSOR
#include "../general/backends.hpp"
#include <array>
namespace mfem
{
@@ -42,7 +43,8 @@ public:
static inline int result(const int* sizes, T first, Args... args)
{
#if !(defined(MFEM_USE_CUDA) || defined(MFEM_USE_HIP))
MFEM_ASSERT(first<sizes[Dim-1],"Trying to access out of boundary.");
MFEM_ASSERT(first<static_cast<T>(sizes[Dim-1]),
"Trying to access out of boundary.");
#endif
return static_cast<int>(first);
}
@@ -87,7 +89,9 @@ protected:
public:
/// Default constructor
DeviceTensor() = delete;
// DeviceTensor() = delete;
MFEM_HOST_DEVICE
DeviceTensor() {}
/// Constructor to initialize a tensor from the Scalar array data_
template <typename... Args> MFEM_HOST_DEVICE
@@ -122,6 +126,9 @@ public:
{
return data[i];
}
/// Returns the shape of the tensor.
MFEM_HOST_DEVICE inline auto &GetShape() const { return sizes; }
};
+7 -9
View File
@@ -15,8 +15,7 @@
* @brief This file contains the declaration of a dual number class
*/
#ifndef MFEM_INTERNAL_DUAL_HPP
#define MFEM_INTERNAL_DUAL_HPP
#pragma once
#include <type_traits> // for is_arithmetic
#include <cmath>
@@ -24,7 +23,7 @@
namespace mfem
{
namespace internal
namespace future
{
/**
@@ -40,8 +39,9 @@ struct dual
/// the partial derivatives of value w.r.t. some other quantity
gradient_type gradient;
/** @brief assignment of a double to a value of a dual. Promotes a double to
/** @brief assignment of a real_t to a value of a dual. Promotes a real_t to
* a dual with a zero gradient value. */
MFEM_HOST_DEVICE
auto operator=(real_t a) -> dual<value_type, gradient_type>&
{
value = a;
@@ -258,7 +258,7 @@ dual<value_type, gradient_type>& operator-=(dual<value_type, gradient_type>& a,
return a;
}
/** @brief compound assignment (+) for dual numbers with `double` righthand side */
/** @brief compound assignment (+) for dual numbers with `real_t` righthand side */
template <typename value_type, typename gradient_type> MFEM_HOST_DEVICE
dual<value_type, gradient_type>& operator+=(dual<value_type, gradient_type>& a,
real_t b)
@@ -267,7 +267,7 @@ dual<value_type, gradient_type>& operator+=(dual<value_type, gradient_type>& a,
return a;
}
/** @brief compound assignment (-) for dual numbers with `double` righthand side */
/** @brief compound assignment (-) for dual numbers with `real_t` righthand side */
template <typename value_type, typename gradient_type> MFEM_HOST_DEVICE
dual<value_type, gradient_type>& operator-=(dual<value_type, gradient_type>& a,
real_t b)
@@ -435,7 +435,5 @@ MFEM_HOST_DEVICE gradient_type get_gradient(dual<value_type, gradient_type> arg)
return arg.gradient;
}
} // namespace internal
} // namespace future
} // namespace mfem
#endif
+9
View File
@@ -778,10 +778,19 @@ public:
of the matrix A. */
void AbsMult(real_t a, const Vector &x, real_t b, Vector &y) const;
/// @brief Computes y = |A| * x, using entry-wise absolute values of the matrix A.
void AbsMult(const Vector &x, Vector &y) const override
{ AbsMult(1.0, x, 0.0, y); }
/** @brief Computes y = a * |At| * x + b * y, using entry-wise absolute
values of the transpose of the matrix A. */
void AbsMultTranspose(real_t a, const Vector &x, real_t b, Vector &y) const;
/** @brief Computes y = |At| * x, using entry-wise absolute values of the
matrix A. */
void AbsMultTranspose(const Vector &x, Vector &y) const override
{ AbsMultTranspose(1.0, x, 0.0, y); }
/** @brief The "Boolean" analog of y = alpha * A * x + beta * y, where
elements in the sparsity pattern of the matrix are treated as "true". */
void BooleanMult(int alpha, const int *x, int beta, int *y)
+63
View File
@@ -188,6 +188,40 @@ void Mult(const int height, const int width, const TA *data, const TX *x, TY *y)
}
}
/** @brief Absolute-value matrix vector multiplication: y = |A| x, where the
matrix A is of size @a height x @a width with given @a data, while @a x and
@a y specify the data of the input and output vectors. */
template<typename TA, typename TX, typename TY>
MFEM_HOST_DEVICE inline
void AbsMult(const int height, const int width, const TA *data,
const TX *x, TY *y)
{
if (width == 0)
{
for (int row = 0; row < height; row++)
{
y[row] = 0.0;
}
return;
}
const TA *d_col = data;
TX x_col = x[0];
for (int row = 0; row < height; row++)
{
y[row] = x_col*std::fabs(d_col[row]);
}
d_col += height;
for (int col = 1; col < width; col++)
{
x_col = x[col];
for (int row = 0; row < height; row++)
{
y[row] += x_col*std::fabs(d_col[row]);
}
d_col += height;
}
}
/** @brief Matrix transpose vector multiplication: y = At x, where the matrix A
is of size @a height x @a width with given @a data, while @a x and @a y
specify the data of the input and output vectors. */
@@ -217,6 +251,35 @@ void MultTranspose(const int height, const int width, const TA *data,
}
}
/** @brief Absolute-value matrix transpose vector multiplication: y = |At| x,
where the matrix A is of size @a height x @a width with given @a data, while
@a x and @a y specify the data of the input and output vectors. */
template<typename TA, typename TX, typename TY>
MFEM_HOST_DEVICE inline
void AbsMultTranspose(const int height, const int width, const TA *data,
const TX *x, TY *y)
{
if (height == 0)
{
for (int row = 0; row < width; row++)
{
y[row] = 0.0;
}
return;
}
TY *y_off = y;
for (int i = 0; i < width; ++i)
{
TY val = 0.0;
for (int j = 0; j < height; ++j)
{
val += x[j] * std::fabs(data[i * height + j]);
}
*y_off = val;
y_off++;
}
}
/// Symmetrize a square matrix with given @a size and @a data: A -> (A+A^T)/2.
template<typename T>
MFEM_HOST_DEVICE inline
+1
View File
@@ -36,6 +36,7 @@
#include "batched/batched.hpp"
#include "batched/gpu_blas.hpp"
#include "batched/solver.hpp"
#include "tensor.hpp"
#ifdef MFEM_USE_AMGX
#include "amgxsolver.hpp"
+74
View File
@@ -645,18 +645,92 @@ void ConstrainedOperator::ConstrainedMult(const Vector &x, Vector &y,
}
}
void ConstrainedOperator::ConstrainedAbsMult(const Vector &x, Vector &y,
const bool transpose) const
{
const int csz = constraint_list.Size();
if (csz == 0)
{
if (transpose)
{
A->AbsMultTranspose(x, y);
}
else
{
A->AbsMult(x, y);
}
return;
}
z = x;
auto idx = constraint_list.Read();
// Use read+write access - we are modifying sub-vector of z
auto d_z = z.ReadWrite();
mfem::forall(csz, [=] MFEM_HOST_DEVICE (int i) { d_z[idx[i]] = 0.0; });
if (transpose)
{
A->AbsMultTranspose(z, y);
}
else
{
A->AbsMult(z, y);
}
auto d_x = x.Read();
// Use read+write access - we are modifying sub-vector of y
auto d_y = y.ReadWrite();
switch (diag_policy)
{
case DIAG_ONE:
mfem::forall(csz, [=] MFEM_HOST_DEVICE (int i)
{
const int id = idx[i];
d_y[id] = d_x[id];
});
break;
case DIAG_ZERO:
mfem::forall(csz, [=] MFEM_HOST_DEVICE (int i)
{
const int id = idx[i];
d_y[id] = 0.0;
});
break;
case DIAG_KEEP:
// Needs action of the operator diagonal on vector
mfem_error("ConstrainedOperator::AbsMult #1");
break;
default:
mfem_error("ConstrainedOperator::AbsMult #2");
break;
}
}
void ConstrainedOperator::Mult(const Vector &x, Vector &y) const
{
constexpr bool transpose = false;
ConstrainedMult(x, y, transpose);
}
void ConstrainedOperator::AbsMult(const Vector &x, Vector &y) const
{
constexpr bool transpose = false;
ConstrainedAbsMult(x, y, transpose);
}
void ConstrainedOperator::MultTranspose(const Vector &x, Vector &y) const
{
constexpr bool transpose = true;
ConstrainedMult(x, y, transpose);
}
void ConstrainedOperator::AbsMultTranspose(const Vector &x, Vector &y) const
{
constexpr bool transpose = true;
ConstrainedAbsMult(x, y, transpose);
}
void ConstrainedOperator::AddMult(const Vector &x, Vector &y,
const real_t a) const
{
+38 -6
View File
@@ -88,10 +88,22 @@ public:
/// Operator application: `y=A(x)`.
virtual void Mult(const Vector &x, Vector &y) const = 0;
/** @brief Action of the absolute-value operator: `y=|A|(x)`. The default
behavior in class Operator is to generate an error. If the Operator is a
composition of several operators, the composition unfold into a product
of absolute-value operators too. */
virtual void AbsMult(const Vector &x, Vector &y) const
{ MFEM_ABORT("Operator::AbsMult() is not overridden!"); }
/** @brief Action of the transpose operator: `y=A^t(x)`. The default behavior
in class Operator is to generate an error. */
virtual void MultTranspose(const Vector &x, Vector &y) const
{ mfem_error("Operator::MultTranspose() is not overridden!"); }
{ MFEM_ABORT("Operator::MultTranspose() is not overridden!"); }
/** @brief Action of the transpose absolute-value operator: `y=|A|^t(x)`.
The default behavior in class Operator is to generate an error. */
virtual void AbsMultTranspose(const Vector &x, Vector &y) const
{ MFEM_ABORT("Operator::AbsMultTranspose() is not overridden!"); }
/// Operator application: `y+=A(x)` (default) or `y+=a*A(x)`.
virtual void AddMult(const Vector &x, Vector &y, const real_t a = 1.0) const;
@@ -121,7 +133,7 @@ public:
behavior in class Operator is to generate an error. */
virtual Operator &GetGradient(const Vector &x) const
{
mfem_error("Operator::GetGradient() is not overridden!");
MFEM_ABORT("Operator::GetGradient() is not overridden!");
return const_cast<Operator &>(*this);
}
@@ -691,7 +703,7 @@ public:
const Vector &xB, const Vector &fxB,
int jokB, int *jcurB, real_t gammaB)
{
mfem_error("TimeDependentAdjointOperator::SUNImplicitSetupB() is not "
MFEM_ABORT("TimeDependentAdjointOperator::SUNImplicitSetupB() is not "
"overridden!");
return (-1);
}
@@ -709,7 +721,7 @@ public:
see the SUNDIALS User Guides. */
virtual int SUNImplicitSolveB(Vector &x, const Vector &b, real_t tol)
{
mfem_error("TimeDependentAdjointOperator::SUNImplicitSolveB() is not "
MFEM_ABORT("TimeDependentAdjointOperator::SUNImplicitSolveB() is not "
"overridden!");
return (-1);
}
@@ -930,6 +942,10 @@ public:
void Mult(const Vector & x, Vector & y) const override
{ P.Mult(x, Px); A.Mult(Px, APx); Rt.MultTranspose(APx, y); }
/// Operator-wise absolute-value application.
void AbsMult(const Vector & x, Vector & y) const override
{ P.AbsMult(x, Px); A.AbsMult(Px, APx); Rt.AbsMultTranspose(APx, y); }
/// Approximate diagonal of the RAP Operator.
/** Returns the diagonal of A, as returned by its AssembleDiagonal method,
multiplied be P^T.
@@ -950,6 +966,14 @@ public:
/// Application of the transpose.
void MultTranspose(const Vector & x, Vector & y) const override
{ Rt.Mult(x, APx); A.MultTranspose(APx, Px); P.MultTranspose(Px, y); }
/// Operator-wise absolute-value application of the transpose
void AbsMultTranspose(const Vector & x, Vector & y) const override
{
Rt.AbsMult(x, APx);
A.AbsMultTranspose(APx, Px);
P.AbsMultTranspose(Px, y);
}
};
@@ -1045,13 +1069,21 @@ public:
void AddMult(const Vector &x, Vector &y, const real_t a = 1.0) const override;
void AbsMult(const Vector &x, Vector &y) const override;
void MultTranspose(const Vector &x, Vector &y) const override;
void AbsMultTranspose(const Vector &x, Vector &y) const override;
/** @brief Implementation of Mult or MultTranspose.
* TODO - Generalize to allow constraining rows and columns differently.
*/
TODO - Generalize to allow constraining rows and columns differently. */
void ConstrainedMult(const Vector &x, Vector &y, const bool transpose) const;
/** @brief Implementation of AbsMult or AbsMultTranspose.
TODO - Generalize to allow constraining rows and columns differently. */
void ConstrainedAbsMult(const Vector &x, Vector &y,
const bool transpose) const;
/// Destructor: destroys the unconstrained Operator, if owned.
~ConstrainedOperator() override { if (own_A) { delete A; } }
};
+8 -7
View File
@@ -624,7 +624,7 @@ void SLISolver::Mult(const Vector &b, Vector &x) const
}
r0 = std::max(nom*rel_tol, abs_tol);
if (nom <= r0)
if (Monitor(0, nom, r, x) || nom <= r0)
{
converged = true;
final_iter = 0;
@@ -665,18 +665,13 @@ void SLISolver::Mult(const Vector &b, Vector &x) const
nomold = nom;
bool done = false;
if (nom < r0)
if (Monitor(i, nom, r, x) || nom < r0)
{
converged = true;
final_iter = i;
done = true;
}
if (++i > max_iter)
{
done = true;
}
if (print_options.iterations || (done && print_options.first_and_last))
{
mfem::out << " Iteration : " << setw(3) << right << (i-1)
@@ -684,6 +679,11 @@ void SLISolver::Mult(const Vector &b, Vector &x) const
<< "\tConv. rate: " << cf << '\n';
}
if (++i > max_iter)
{
done = true;
}
if (done) { break; }
}
@@ -700,6 +700,7 @@ void SLISolver::Mult(const Vector &b, Vector &x) const
}
final_norm = nom;
Monitor(final_iter, final_norm, r, x, true);
}
void SLI(const Operator &A, const Vector &b, Vector &x,
+117 -60
View File
@@ -46,12 +46,6 @@
#define MFEM_GPUSPARSE_ALG HIPSPARSE_CSRMV_ALG1
#endif // defined(MFEM_USE_CUDA)
#if defined(MFEM_USE_SINGLE)
#define MFEM_REAL_T MFEM_CUDA_or_HIP(_R_32F)
#elif defined(MFEM_USE_DOUBLE)
#define MFEM_REAL_T MFEM_CUDA_or_HIP(_R_64F)
#endif
namespace mfem
{
@@ -470,66 +464,109 @@ void SparseMatrix::SortColumnIndices()
}
#ifdef MFEM_USE_CUDA_OR_HIP
if (Device::Allows(Backend::CUDA_MASK) || Device::Allows(Backend::HIP_MASK))
if ( Device::Allows( Backend::CUDA_MASK ))
{
const int m = Height();
const int n = Width();
#if defined(MFEM_USE_CUDA)
size_t pBufferSizeInBytes = 0;
void *pBuffer = NULL;
const int n = Height();
const int m = Width();
const int nnzA = J.Capacity();
const int *d_ia = ReadI();
int *d_ja = ReadWriteJ();
real_t * d_a_sorted = ReadWriteData();
const int * d_ia = ReadI();
int * d_ja_sorted = ReadWriteJ();
csru2csrInfo_t sortInfoA;
// Get size of temporary buffer needed to sort the column indices,
// allocate the temporary buffer.
size_t pBufferSizeInBytes;
MFEM_cu_or_hip(sparseXcsrsort_bufferSizeExt)(
handle, m, n, nnzA, d_ia, d_ja, &pBufferSizeInBytes);
void *pBuffer = MFEM_Cu_or_Hip(MemAlloc)(&pBuffer, pBufferSizeInBytes);
cusparseMatDescr_t matA_descr;
cusparseCreateMatDescr( &matA_descr );
cusparseSetMatIndexBase( matA_descr, CUSPARSE_INDEX_BASE_ZERO );
cusparseSetMatType( matA_descr, CUSPARSE_MATRIX_TYPE_GENERAL );
// Create matrix descriptor, will have default values
// CUSPARSE_INDEX_BASE_ZERO and CUSPARSE_MATRIX_TYPE_GENERAL.
MFEM_cu_or_hip(sparseMatDescr_t) matA_descr;
MFEM_cu_or_hip(sparseCreateMatDescr)(&matA_descr);
cusparseCreateCsru2csrInfo( &sortInfoA );
// Initialize permutation to identity
Array<int> P(nnzA);
int *d_P = P.Write();
mfem::forall(nnzA, [=] MFEM_HOST_DEVICE (int i) { d_P[i] = i; });
#ifdef MFEM_USE_SINGLE
cusparseScsru2csr_bufferSizeExt( handle, n, m, nnzA, d_a_sorted, d_ia,
d_ja_sorted, sortInfoA,
&pBufferSizeInBytes);
#elif defined MFEM_USE_DOUBLE
cusparseDcsru2csr_bufferSizeExt( handle, n, m, nnzA, d_a_sorted, d_ia,
d_ja_sorted, sortInfoA,
&pBufferSizeInBytes);
#else
MFEM_ABORT("Floating point type undefined");
#endif
// Sort the column indices. The array d_ja will now be sorted. The
// permutation required to sort the values will be returned in d_P.
MFEM_cu_or_hip(sparseXcsrsort)(handle, m, n, nnzA, matA_descr, d_ia, d_ja,
d_P, pBuffer);
CuMemAlloc( &pBuffer, pBufferSizeInBytes );
// Create a copy of the unsorted matrix values.
real_t *d_a = ReadWriteData();
void *d_a_unsorted = MFEM_Cu_or_Hip(MemAlloc)(
&d_a_unsorted, nnzA * sizeof(real_t));
MFEM_Cu_or_Hip(MemcpyDtoD)(d_a_unsorted, d_a, nnzA * sizeof(real_t));
#ifdef MFEM_USE_SINGLE
cusparseScsru2csr( handle, n, m, nnzA, matA_descr, d_a_sorted, d_ia,
d_ja_sorted, sortInfoA, pBuffer);
#elif defined MFEM_USE_DOUBLE
cusparseDcsru2csr( handle, n, m, nnzA, matA_descr, d_a_sorted, d_ia,
d_ja_sorted, sortInfoA, pBuffer);
#else
MFEM_ABORT("Floating point type undefined");
#endif
// Create the (input) dense vector with the unsorted values.
MFEM_cu_or_hip(sparseDnVecDescr_t) d_a_dense;
MFEM_cu_or_hip(sparseCreateDnVec)(&d_a_dense, nnzA, d_a_unsorted, MFEM_REAL_T);
// Create the (output) sparse vector that will have the sorted values.
MFEM_cu_or_hip(sparseSpVecDescr_t) d_a_sparse;
MFEM_cu_or_hip(sparseCreateSpVec)(&d_a_sparse, nnzA, nnzA, d_P, d_a,
MFEM_CU_or_HIP(SPARSE_INDEX_32I),
MFEM_CU_or_HIP(SPARSE_INDEX_BASE_ZERO),
MFEM_REAL_T);
// Sort the matrix values using the permutation vector.
MFEM_cu_or_hip(sparseGather)(handle, d_a_dense, d_a_sparse);
// The above calls may be asynchronous, so we need to wait for them to
// finish before we can free memory.
// The above call is (at least in some cases) asynchronous, so we need to
// wait for it to finish before we can free device temporaries.
MFEM_STREAM_SYNC;
MFEM_cu_or_hip(sparseDestroyDnVec)(d_a_dense);
MFEM_cu_or_hip(sparseDestroySpVec)(d_a_sparse);
MFEM_cu_or_hip(sparseDestroyMatDescr)(matA_descr);
cusparseDestroyCsru2csrInfo( sortInfoA );
cusparseDestroyMatDescr( matA_descr );
MFEM_Cu_or_Hip(MemFree)(d_a_unsorted);
MFEM_Cu_or_Hip(MemFree)(pBuffer);
CuMemFree( pBuffer );
#endif
}
else if ( Device::Allows( Backend::HIP_MASK ))
{
#if defined(MFEM_USE_HIP)
size_t pBufferSizeInBytes = 0;
void *pBuffer = NULL;
int *P = NULL;
const int n = Height();
const int m = Width();
const int nnzA = J.Capacity();
real_t * d_a_sorted = ReadWriteData();
const int * d_ia = ReadI();
int * d_ja_sorted = ReadWriteJ();
hipsparseMatDescr_t descrA;
hipsparseCreateMatDescr( &descrA );
// FIXME: There is not in-place version of csr sort in hipSPARSE currently, so we make
// a temporary copy of the data for gthr, sort that, and then copy the sorted values
// back to the array being returned. Where there is an in-place version available,
// we should use it.
Array< real_t > a_tmp( nnzA );
real_t *d_a_tmp = a_tmp.Write();
hipsparseXcsrsort_bufferSizeExt(handle, n, m, nnzA, d_ia, d_ja_sorted,
&pBufferSizeInBytes);
HipMemAlloc( &pBuffer, pBufferSizeInBytes );
HipMemAlloc( (void**)&P, nnzA * sizeof(int) );
hipsparseCreateIdentityPermutation(handle, nnzA, P);
hipsparseXcsrsort(handle, n, m, nnzA, descrA, d_ia, d_ja_sorted, P, pBuffer);
#if defined(MFEM_USE_SINGLE)
hipsparseSgthr(handle, nnzA, d_a_sorted, d_a_tmp, P,
HIPSPARSE_INDEX_BASE_ZERO);
#elif defined(MFEM_USE_DOUBLE)
hipsparseDgthr(handle, nnzA, d_a_sorted, d_a_tmp, P,
HIPSPARSE_INDEX_BASE_ZERO);
#else
MFEM_ABORT("Unsupported floating point type!");
#endif
A.CopyFrom( a_tmp.GetMemory(), nnzA );
hipsparseDestroyMatDescr( descrA );
HipMemFree( pBuffer );
HipMemFree( P );
#endif
}
else
#endif // MFEM_USE_CUDA_OR_HIP
@@ -784,15 +821,27 @@ void SparseMatrix::AddMult(const Vector &x, Vector &y, const real_t a) const
MFEM_CU_or_HIP(SPARSE_INDEX_32I),
MFEM_CU_or_HIP(SPARSE_INDEX_32I),
MFEM_CU_or_HIP(SPARSE_INDEX_BASE_ZERO),
MFEM_REAL_T);
#ifdef MFEM_USE_SINGLE
MFEM_CUDA_or_HIP(_R_32F));
#else
MFEM_CUDA_or_HIP(_R_64F));
#endif
// Create handles for input/output vectors
MFEM_cu_or_hip(sparseCreateDnVec)(&vecX_descr,
x.Size(),
const_cast<real_t *>(d_x),
MFEM_REAL_T);
#ifdef MFEM_USE_SINGLE
MFEM_CUDA_or_HIP(_R_32F));
#else
MFEM_CUDA_or_HIP(_R_64F));
#endif
MFEM_cu_or_hip(sparseCreateDnVec)(&vecY_descr, y.Size(), d_y,
MFEM_REAL_T);
#ifdef MFEM_USE_SINGLE
MFEM_CUDA_or_HIP(_R_32F));
#else
MFEM_CUDA_or_HIP(_R_64F));
#endif
#else
cusparseCreateMatDescr(&matA_descr);
cusparseSetMatIndexBase(matA_descr, CUSPARSE_INDEX_BASE_ZERO);
@@ -811,7 +860,11 @@ void SparseMatrix::AddMult(const Vector &x, Vector &y, const real_t a) const
vecX_descr,
&beta,
vecY_descr,
MFEM_REAL_T,
#ifdef MFEM_USE_SINGLE
MFEM_CUDA_or_HIP(_R_32F),
#else
MFEM_CUDA_or_HIP(_R_64F),
#endif
MFEM_GPUSPARSE_ALG,
&newBufferSize);
@@ -838,7 +891,11 @@ void SparseMatrix::AddMult(const Vector &x, Vector &y, const real_t a) const
vecX_descr,
&beta,
vecY_descr,
MFEM_REAL_T,
#ifdef MFEM_USE_SINGLE
MFEM_CUDA_or_HIP(_R_32F),
#else
MFEM_CUDA_or_HIP(_R_64F),
#endif
MFEM_GPUSPARSE_ALG,
dBuffer);
#else
+2 -2
View File
@@ -422,13 +422,13 @@ public:
void BooleanMultTranspose(const Array<int> &x, Array<int> &y) const;
/// y = |A| * x, using entry-wise absolute values of matrix A
void AbsMult(const Vector &x, Vector &y) const;
void AbsMult(const Vector &x, Vector &y) const override;
/// y = |At| * x, using entry-wise absolute values of the transpose of matrix A
/** If the matrix is modified, call ResetTranspose() and optionally
EnsureMultTranspose() to make sure this method uses the correct updated
transpose. */
void AbsMultTranspose(const Vector &x, Vector &y) const;
void AbsMultTranspose(const Vector &x, Vector &y) const override;
/// Compute y^t A x
real_t InnerProduct(const Vector &x, const Vector &y) const;
+231 -50
View File
@@ -15,27 +15,18 @@
* @brief Implementation of the tensor class
*/
#ifndef MFEM_INTERNAL_TENSOR_HPP
#define MFEM_INTERNAL_TENSOR_HPP
#pragma once
#include "../general/backends.hpp"
#include "dual.hpp"
#include <limits>
#include <type_traits> // for std::false_type
namespace mfem
{
namespace internal
namespace future
{
#if defined(__CUDACC__)
#if __CUDAVER__ >= 75000
#define MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING #pragma nv_exec_check_disable
#else
#define MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING #pragma hd_warning_disable
#endif
#else //__CUDACC__
#define MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
#endif
template <typename T, int... n>
struct tensor;
@@ -149,7 +140,7 @@ struct tensor<T, n0, n1, n2, n3, n4>
*/
struct zero
{
/** @brief `zero` is implicitly convertible to double with value 0.0 */
/** @brief `zero` is implicitly convertible to real_t with value 0.0 */
MFEM_HOST_DEVICE operator real_t() { return 0.0; }
/** @brief `zero` is implicitly convertible to a tensor of any shape */
@@ -304,7 +295,6 @@ using reduced_tensor = typename std::conditional<
* @note the different cases of 0D, 1D, 2D, 3D, and 4D are implemented separately
* to work around a limitation in nvcc involving __host__ __device__ lambdas with `auto` parameters.
*/
MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
template <typename lambda_type>
MFEM_HOST_DEVICE constexpr auto make_tensor(lambda_type f) ->
tensor<decltype(f())>
@@ -323,7 +313,6 @@ tensor<decltype(f())>
* @note the different cases of 0D, 1D, 2D, 3D, and 4D are implemented separately
* to work around a limitation in nvcc involving __host__ __device__ lambdas with `auto` parameters.
*/
MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
template <int n1, typename lambda_type>
MFEM_HOST_DEVICE auto make_tensor(lambda_type f) ->
tensor<decltype(f(n1)), n1>
@@ -349,7 +338,6 @@ tensor<decltype(f(n1)), n1>
* @note the different cases of 0D, 1D, 2D, 3D, and 4D are implemented separately
* to work around a limitation in nvcc involving __host__ __device__ lambdas with `auto` parameters.
*/
MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
template <int n1, int n2, typename lambda_type>
MFEM_HOST_DEVICE auto make_tensor(lambda_type f) ->
tensor<decltype(f(n1, n2)), n1, n2>
@@ -379,7 +367,6 @@ tensor<decltype(f(n1, n2)), n1, n2>
* @note the different cases of 0D, 1D, 2D, 3D, and 4D are implemented separately
* to work around a limitation in nvcc involving __host__ __device__ lambdas with `auto` parameters.
*/
MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
template <int n1, int n2, int n3, typename lambda_type>
MFEM_HOST_DEVICE auto make_tensor(lambda_type f) ->
tensor<decltype(f(n1, n2, n3)), n1, n2, n3>
@@ -413,7 +400,6 @@ tensor<decltype(f(n1, n2, n3)), n1, n2, n3>
* @note the different cases of 0D, 1D, 2D, 3D, and 4D are implemented separately
* to work around a limitation in nvcc involving __host__ __device__ lambdas with `auto` parameters.
*/
MFEM_SUPPRESS_NVCC_HOSTDEVICE_WARNING
template <int n1, int n2, int n3, int n4, typename lambda_type>
MFEM_HOST_DEVICE auto make_tensor(lambda_type f) ->
tensor<decltype(f(n1, n2, n3, n4)), n1, n2, n3, n4>
@@ -436,6 +422,23 @@ tensor<decltype(f(n1, n2, n3, n4)), n1, n2, n3, n4>
return A;
}
// needs to be generalized
template <typename T, int m, int n> MFEM_HOST_DEVICE
tensor<T, n> get_col(tensor<T, m, n> A, int j)
{
tensor<T, n> c{};
c(0) = A[0][j];
c(1) = A[1][j];
return c;
}
/// @overload
template <typename T> MFEM_HOST_DEVICE
tensor<T, 1> get_col(tensor<T, 1, 1> A, int j)
{
return tensor<T, 1> {A[0][0]};
}
/**
* @brief return the sum of two tensors
* @tparam S the underlying type of the lefthand argument
@@ -497,7 +500,7 @@ tensor<decltype(S {} + T{}), n...>
/**
* @brief multiply a tensor by a scalar value
* @tparam S the scalar value type. Must be arithmetic (e.g. float, double, int) or a dual number
* @tparam S the scalar value type. Must be arithmetic (e.g. float, real_t, int) or a dual number
* @tparam T the underlying type of the tensor (righthand) argument
* @tparam n integers describing the tensor shape
* @param[in] scale The scaling factor
@@ -519,7 +522,7 @@ tensor<decltype(S {} * T{}), n...>
/**
* @brief multiply a tensor by a scalar value
* @tparam S the scalar value type. Must be arithmetic (e.g. float, double, int) or a dual number
* @tparam S the scalar value type. Must be arithmetic (e.g. float, real_t, int) or a dual number
* @tparam T the underlying type of the tensor (righthand) argument
* @tparam n integers describing the tensor shape
* @param[in] A The tensor to be scaled
@@ -541,7 +544,7 @@ tensor<decltype(T {} * S{}), n...>
/**
* @brief divide a scalar by each element in a tensor
* @tparam S the scalar value type. Must be arithmetic (e.g. float, double, int) or a dual number
* @tparam S the scalar value type. Must be arithmetic (e.g. float, real_t, int) or a dual number
* @tparam T the underlying type of the tensor (righthand) argument
* @tparam n integers describing the tensor shape
* @param[in] scale The numerator
@@ -563,7 +566,7 @@ tensor<decltype(S {} * T{}), n...>
/**
* @brief divide a tensor by a scalar
* @tparam S the scalar value type. Must be arithmetic (e.g. float, double, int) or a dual number
* @tparam S the scalar value type. Must be arithmetic (e.g. float, real_t, int) or a dual number
* @tparam T the underlying type of the tensor (righthand) argument
* @tparam n integers describing the tensor shape
* @param[in] A The tensor of numerators
@@ -697,6 +700,20 @@ auto outer(S A, T B) -> decltype(A * B)
return A * B;
}
template <typename T, int n, int m> MFEM_HOST_DEVICE
tensor<T, n + m> flatten(tensor<T, n, m> A)
{
tensor<T, n + m> B{};
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
B(i + j * m) = A(i, j);
}
}
return B;
}
/**
* @overload
* @note this overload implements the case where the left argument is a scalar, and the right argument is a tensor
@@ -1051,13 +1068,25 @@ decltype(S {} * T{})
return AB;
}
template <typename S, typename T, int m, int... n> MFEM_HOST_DEVICE
auto dot(const tensor<S, m>& A, const tensor<T, m, n...>& B) ->
tensor<decltype(S {} * T{}), n...>
template <typename T, int m> MFEM_HOST_DEVICE
auto dot(const tensor<T, m>& A, const tensor<T, m>& B) ->
decltype(T {})
{
constexpr int dimensions[] = {n...};
tensor<decltype(S{} * T{}), n...> AB{};
for (int i = 0; i < dimensions[0]; i++)
decltype(T{}) AB{};
for (int i = 0; i < m; i++)
{
AB += A[i] * B[i];
}
return AB;
}
template <typename S, typename T, int m, int n0, int n1, int... n>
MFEM_HOST_DEVICE
auto dot(const tensor<S, m>& A, const tensor<T, m, n0, n1, n...>& B) ->
tensor<decltype(S {} * T{}), n0, n1, n...>
{
tensor<decltype(S{} * T{}), n0, n1, n...> AB{};
for (int i = 0; i < n0; i++)
{
for (int j = 0; j < m; j++)
{
@@ -1088,7 +1117,7 @@ decltype(S {} * T{} * U{})
}
/**
* @brief double dot product, contracting over the two "middle" indices
* @brief real_t dot product, contracting over the two "middle" indices
* @tparam S the underlying type of the tensor (lefthand) argument
* @tparam T the underlying type of the tensor (righthand) argument
* @tparam m first dimension of A
@@ -1285,7 +1314,7 @@ tensor<T, n, n> dev(const tensor<T, n, n>& A)
* @return I_dim
*/
template <int dim>
MFEM_HOST_DEVICE tensor<real_t, dim, dim> Identity()
MFEM_HOST_DEVICE tensor<real_t, dim, dim> IdentityMatrix()
{
tensor<real_t, dim, dim> I{};
for (int i = 0; i < dim; i++)
@@ -1321,6 +1350,12 @@ tensor<T, n, m> transpose(const tensor<T, m, n>& A)
* @param[in] A The matrix to obtain the determinant of
*/
template <typename T> MFEM_HOST_DEVICE
T det(const tensor<T, 1, 1>& A)
{
return A[0][0];
}
/// @overload
template <typename T> MFEM_HOST_DEVICE
T det(const tensor<T, 2, 2>& A)
{
return A[0][0] * A[1][1] - A[0][1] * A[1][0];
@@ -1335,6 +1370,145 @@ T det(const tensor<T, 3, 3>& A)
A[2][0];
}
template <typename T> MFEM_HOST_DEVICE
std::tuple<tensor<T, 1>, tensor<T, 1, 1>> eig(tensor<T, 1, 1> &A)
{
return {tensor<T, 1>{A[0][0]}, tensor<T, 1, 1>{{{1.0}}}};
}
template <typename T> MFEM_HOST_DEVICE
std::tuple<tensor<T, 2>, tensor<T, 2, 2>> eig(tensor<T, 2, 2> &A)
{
tensor<T, 2> e;
tensor<T, 2, 2> v;
real_t d0 = A(0, 0);
real_t d2 = A(0, 1);
real_t d3 = A(1, 1);
real_t c, s;
if (d2 == 0.0)
{
c = 1.0;
s = 0.0;
}
else
{
real_t t;
const real_t zeta = (d3 - d0) / (2.0 * d2);
const real_t azeta = fabs(zeta);
if (azeta < std::sqrt(1.0/std::numeric_limits<T>::epsilon()))
{
t = copysign(1./(azeta + std::sqrt(1. + zeta*zeta)), zeta);
}
else
{
t = copysign(0.5/azeta, zeta);
}
c = std::sqrt(1./(1. + t*t));
s = c*t;
t *= d2;
d0 -= t;
d3 += t;
}
if (d0 <= d3)
{
e(0) = d0;
e(1) = d3;
v(0, 0) = c;
v(1, 0) = -s;
v(0, 1) = s;
v(1, 1) = c;
}
else
{
e(0) = d3;
e(1) = d0;
v(0, 0) = s;
v(1, 0) = c;
v(0, 1) = c;
v(1, 1) = -s;
}
return {e, v};
}
template <typename T> MFEM_HOST_DEVICE
void GetScalingFactor(const T &d_max, T &mult)
{
int d_exp;
if (d_max > 0.)
{
mult = frexp(d_max, &d_exp);
if (d_exp == std::numeric_limits<T>::max_exponent)
{
mult *= std::numeric_limits<T>::radix;
}
mult = d_max/mult;
}
else
{
mult = 1.;
}
}
template <typename T> MFEM_HOST_DEVICE
T calcsv(const tensor<T, 1, 1> A, const int i)
{
return A[0][0];
}
/**
* @brief Compute the i-th singular value of a 2x2 matrix A
*/
template <typename T> MFEM_HOST_DEVICE
T calcsv(const tensor<T, 2, 2> A, const int i)
{
real_t mult;
real_t d0, d1, d2, d3;
d0 = A(0, 0);
d1 = A(1, 0);
d2 = A(0, 1);
d3 = A(1, 1);
real_t d_max = fabs(d0);
if (d_max < fabs(d1)) { d_max = fabs(d1); }
if (d_max < fabs(d2)) { d_max = fabs(d2); }
if (d_max < fabs(d3)) { d_max = fabs(d3); }
GetScalingFactor(d_max, mult);
d0 /= mult;
d1 /= mult;
d2 /= mult;
d3 /= mult;
real_t t = 0.5*((d0+d2)*(d0-d2)+(d1-d3)*(d1+d3));
real_t s = d0*d2 + d1*d3;
s = std::sqrt(0.5*(d0*d0 + d1*d1 + d2*d2 + d3*d3) + std::sqrt(t*t + s*s));
if (s == 0.0)
{
return 0.0;
}
t = fabs(d0*d3 - d1*d2) / s;
if (t > s)
{
if (i == 0)
{
return t*mult;
}
return s*mult;
}
if (i == 0)
{
return s*mult;
}
return t*mult;
}
/**
* @brief Return whether a square rank 2 tensor is symmetric
*
@@ -1474,13 +1648,20 @@ tensor<T, n> linear_solve(tensor<T, n, n> A, const tensor<T, n> b)
/**
* @brief Inverts a matrix
* @param[in] A The matrix to invert
* @note Uses a shortcut for inverting a 2-by-2 matrix
* @note Uses a shortcut for inverting a 1x1, 2x2 and 3x3 matrix
*/
inline MFEM_HOST_DEVICE tensor<real_t, 2, 2> inv(const tensor<real_t, 2, 2>& A)
template <typename T>
inline MFEM_HOST_DEVICE tensor<T, 1, 1> inv(const tensor<T, 1, 1>& A)
{
real_t inv_detA(1.0 / det(A));
return tensor<T, 1, 1> {{{T{1.0} / A[0][0]}}};
}
tensor<real_t, 2, 2> invA{};
template <typename T>
inline MFEM_HOST_DEVICE tensor<T, 2, 2> inv(const tensor<T, 2, 2>& A)
{
T inv_detA(1.0 / det(A));
tensor<T, 2, 2> invA{};
invA[0][0] = A[1][1] * inv_detA;
invA[0][1] = -A[0][1] * inv_detA;
@@ -1494,11 +1675,12 @@ inline MFEM_HOST_DEVICE tensor<real_t, 2, 2> inv(const tensor<real_t, 2, 2>& A)
* @overload
* @note Uses a shortcut for inverting a 3-by-3 matrix
*/
inline MFEM_HOST_DEVICE tensor<real_t, 3, 3> inv(const tensor<real_t, 3, 3>& A)
template <typename T>
inline MFEM_HOST_DEVICE tensor<T, 3, 3> inv(const tensor<T, 3, 3>& A)
{
real_t inv_detA(1.0 / det(A));
T inv_detA(1.0 / det(A));
tensor<real_t, 3, 3> invA{};
tensor<T, 3, 3> invA{};
invA[0][0] = (A[1][1] * A[2][2] - A[1][2] * A[2][1]) * inv_detA;
invA[0][1] = (A[0][2] * A[2][1] - A[0][1] * A[2][2]) * inv_detA;
@@ -1517,10 +1699,12 @@ inline MFEM_HOST_DEVICE tensor<real_t, 3, 3> inv(const tensor<real_t, 3, 3>& A)
* @note For N-by-N matrices with N > 3, requires Gaussian elimination
* with partial pivoting
*/
template <typename T, int n> MFEM_HOST_DEVICE
tensor<T, n, n> inv(const tensor<T, n, n>& A)
template <typename T, int n>
MFEM_HOST_DEVICE
typename std::enable_if<(n > 3), tensor<T, n, n>>::type
inv(const tensor<T, n, n>& A)
{
auto abs = [](real_t x) { return (x < 0) ? -x : x; };
auto abs = [](T x) { return (x < 0) ? -x : x; };
auto swap = [](tensor<T, n>& x, tensor<T, n>& y)
{
auto tmp = x;
@@ -1528,12 +1712,12 @@ tensor<T, n, n> inv(const tensor<T, n, n>& A)
y = tmp;
};
tensor<real_t, n, n> B = Identity<n>();
tensor<T, n, n> B = IdentityMatrix<n>();
for (int i = 0; i < n; i++)
{
// Search for maximum in this column
real_t max_val = abs(A[i][i]);
T max_val = abs(A[i][i]);
int max_row = i;
for (int j = i + 1; j < n; j++)
@@ -1553,7 +1737,7 @@ tensor<T, n, n> inv(const tensor<T, n, n>& A)
{
if (A[j][i] != 0.0)
{
real_t c = -A[j][i] / A[i][i];
T c = -A[j][i] / A[i][i];
A[j] += c * A[i];
B[j] += c * B[i];
A[j][i] = 0;
@@ -1716,7 +1900,7 @@ template <typename T1, typename T2>
using outer_product_t = typename detail::outer_prod<T1, T2>::type;
/**
* @brief Retrieves the gradient component of a double (which is nothing)
* @brief Retrieves the gradient component of a real_t (which is nothing)
* @return The sentinel, @see zero
*/
inline MFEM_HOST_DEVICE zero get_gradient(real_t /* arg */) { return zero{}; }
@@ -2046,11 +2230,8 @@ auto ddot(const isotropic_tensor<S, m, m, m, m>& I,
const tensor<T, m, m>& A)
-> tensor<decltype(S {} * T{}), m, m>
{
return I.c1 * tr(A) * Identity<m>() + I.c2 * sym(A) + I.c3 * antisym(A);
return I.c1 * tr(A) * IdentityMatrix<m>() + I.c2 * sym(A) + I.c3 * antisym(A);
}
} // namespace internal
} // namespace future
} // namespace mfem
#endif
+219 -194
View File
@@ -11,19 +11,18 @@
// Implementation of data type vector
#include "kernels.hpp"
#include "vector.hpp"
#include "../general/forall.hpp"
#include "../general/reducers.hpp"
#include "../general/hash.hpp"
#include "vector.hpp"
#ifdef MFEM_USE_OPENMP
#include <omp.h>
#endif
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <limits>
namespace mfem
{
@@ -207,7 +206,7 @@ Vector &Vector::operator=(const Vector &v)
UseDevice(v.UseDevice());
#else
SetSize(v.Size());
bool vuse = v.UseDevice();
const bool vuse = v.UseDevice();
const bool use_dev = UseDevice() || vuse;
v.UseDevice(use_dev);
// keep 'data' where it is, unless 'use_dev' is true
@@ -249,8 +248,8 @@ Vector &Vector::operator*=(const Vector &v)
const bool use_dev = UseDevice() || v.UseDevice();
const int N = size;
const auto x = v.Read(use_dev);
auto y = ReadWrite(use_dev);
auto x = v.Read(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] *= x[i]; });
return *this;
}
@@ -271,8 +270,8 @@ Vector &Vector::operator/=(const Vector &v)
const bool use_dev = UseDevice() || v.UseDevice();
const int N = size;
const auto x = v.Read(use_dev);
auto y = ReadWrite(use_dev);
auto x = v.Read(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] /= x[i]; });
return *this;
}
@@ -292,8 +291,8 @@ Vector &Vector::operator-=(const Vector &v)
const bool use_dev = UseDevice() || v.UseDevice();
const int N = size;
const auto x = v.Read(use_dev);
auto y = ReadWrite(use_dev);
auto x = v.Read(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] -= x[i]; });
return *this;
}
@@ -313,8 +312,8 @@ Vector &Vector::operator+=(const Vector &v)
const bool use_dev = UseDevice() || v.UseDevice();
const int N = size;
const auto x = v.Read(use_dev);
auto y = ReadWrite(use_dev);
auto x = v.Read(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] += x[i]; });
return *this;
}
@@ -327,8 +326,8 @@ Vector &Vector::Add(const real_t a, const Vector &Va)
{
const int N = size;
const bool use_dev = UseDevice() || Va.UseDevice();
const auto x = Va.Read(use_dev);
auto y = ReadWrite(use_dev);
auto x = Va.Read(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] += a * x[i]; });
}
return *this;
@@ -340,7 +339,7 @@ Vector &Vector::Set(const real_t a, const Vector &Va)
const bool use_dev = UseDevice() || Va.UseDevice();
const int N = size;
auto x = Va.Read(use_dev);
const auto x = Va.Read(use_dev);
auto y = Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] = a * x[i]; });
return *this;
@@ -352,9 +351,9 @@ void Vector::SetVector(const Vector &v, int offset)
const bool use_dev = UseDevice() || v.UseDevice();
const int vs = v.Size();
const real_t *vp = v.Read(use_dev);
const auto vp = v.Read(use_dev);
// Use read+write access for *this - we only modify some of its entries
real_t *p = ReadWrite(use_dev) + offset;
auto p = ReadWrite(use_dev) + offset;
mfem::forall_switch(use_dev, vs, [=] MFEM_HOST_DEVICE (int i) { p[i] = vp[i]; });
}
@@ -364,8 +363,8 @@ void Vector::AddSubVector(const Vector &v, int offset)
const bool use_dev = UseDevice() || v.UseDevice();
const int vs = v.Size();
const real_t *vp = v.Read(use_dev);
real_t *p = ReadWrite(use_dev) + offset;
const auto vp = v.Read(use_dev);
auto p = ReadWrite(use_dev) + offset;
mfem::forall_switch(use_dev, vs, [=] MFEM_HOST_DEVICE (int i) { p[i] += vp[i]; });
}
@@ -385,6 +384,28 @@ void Vector::Reciprocal()
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] = 1.0/y[i]; });
}
void Vector::Abs()
{
const bool use_dev = UseDevice();
const int N = size;
auto y = ReadWrite(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
y[i] = std::abs(y[i]);
});
}
void Vector::Pow(const real_t p)
{
const bool use_dev = UseDevice();
const int N = size;
auto y = ReadWrite(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
y[i] = std::pow(y[i], p);
});
}
void add(const Vector &v1, const Vector &v2, Vector &v)
{
MFEM_ASSERT(v.size == v1.size && v.size == v2.size,
@@ -394,8 +415,8 @@ void add(const Vector &v1, const Vector &v2, Vector &v)
const bool use_dev = v1.UseDevice() || v2.UseDevice() || v.UseDevice();
const int N = v.size;
// Note: get read access first, in case v is the same as v1/v2.
auto x1 = v1.Read(use_dev);
auto x2 = v2.Read(use_dev);
const auto x1 = v1.Read(use_dev);
const auto x2 = v2.Read(use_dev);
auto y = v.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { y[i] = x1[i] + x2[i]; });
#else
@@ -426,8 +447,8 @@ void add(const Vector &v1, real_t alpha, const Vector &v2, Vector &v)
const bool use_dev = v1.UseDevice() || v2.UseDevice() || v.UseDevice();
const int N = v.size;
// Note: get read access first, in case v is the same as v1/v2.
auto d_x = v1.Read(use_dev);
auto d_y = v2.Read(use_dev);
const auto d_x = v1.Read(use_dev);
const auto d_y = v2.Read(use_dev);
auto d_z = v.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -465,8 +486,8 @@ void add(const real_t a, const Vector &x, const Vector &y, Vector &z)
const bool use_dev = x.UseDevice() || y.UseDevice() || z.UseDevice();
const int N = x.size;
// Note: get read access first, in case z is the same as x/y.
auto xd = x.Read(use_dev);
auto yd = y.Read(use_dev);
const auto xd = x.Read(use_dev);
const auto yd = y.Read(use_dev);
auto zd = z.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -520,8 +541,8 @@ void add(const real_t a, const Vector &x,
const bool use_dev = x.UseDevice() || y.UseDevice() || z.UseDevice();
const int N = x.size;
// Note: get read access first, in case z is the same as x/y.
auto xd = x.Read(use_dev);
auto yd = y.Read(use_dev);
const auto xd = x.Read(use_dev);
const auto yd = y.Read(use_dev);
auto zd = z.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -550,8 +571,8 @@ void subtract(const Vector &x, const Vector &y, Vector &z)
const bool use_dev = x.UseDevice() || y.UseDevice() || z.UseDevice();
const int N = x.size;
// Note: get read access first, in case z is the same as x/y.
auto xd = x.Read(use_dev);
auto yd = y.Read(use_dev);
const auto xd = x.Read(use_dev);
const auto yd = y.Read(use_dev);
auto zd = z.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -589,8 +610,8 @@ void subtract(const real_t a, const Vector &x, const Vector &y, Vector &z)
const bool use_dev = x.UseDevice() || y.UseDevice() || z.UseDevice();
const int N = x.size;
// Note: get read access first, in case z is the same as x/y.
auto xd = x.Read(use_dev);
auto yd = y.Read(use_dev);
const auto xd = x.Read(use_dev);
const auto yd = y.Read(use_dev);
auto zd = z.Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -631,8 +652,8 @@ void Vector::median(const Vector &lo, const Vector &hi)
const bool use_dev = UseDevice() || lo.UseDevice() || hi.UseDevice();
const int N = size;
// Note: get read access first, in case *this is the same as lo/hi.
auto l = lo.Read(use_dev);
auto h = hi.Read(use_dev);
const auto l = lo.Read(use_dev);
const auto h = hi.Read(use_dev);
auto m = Write(use_dev);
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i)
{
@@ -652,9 +673,9 @@ void Vector::GetSubVector(const Array<int> &dofs, Vector &elemvect) const
const int n = dofs.Size();
elemvect.SetSize(n);
const bool use_dev = dofs.UseDevice() || elemvect.UseDevice();
const auto d_X = Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
auto d_y = elemvect.Write(use_dev);
auto d_X = Read(use_dev);
auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i)
{
const int dof_i = d_dofs[i];
@@ -664,7 +685,7 @@ void Vector::GetSubVector(const Array<int> &dofs, Vector &elemvect) const
void Vector::GetSubVector(const Array<int> &dofs, real_t *elem_data) const
{
data.Read(MemoryClass::HOST, size);
HostRead();
const int n = dofs.Size();
for (int i = 0; i < n; i++)
{
@@ -679,7 +700,7 @@ void Vector::SetSubVector(const Array<int> &dofs, const real_t value)
const int n = dofs.Size();
// Use read+write access for *this - we only modify some of its entries
auto d_X = ReadWrite(use_dev);
auto d_dofs = dofs.Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i)
{
const int j = d_dofs[i];
@@ -721,8 +742,8 @@ void Vector::SetSubVector(const Array<int> &dofs, const Vector &elemvect)
const int n = dofs.Size();
// Use read+write access for X - we only modify some of its entries
auto d_X = ReadWrite(use_dev);
auto d_y = elemvect.Read(use_dev);
auto d_dofs = dofs.Read(use_dev);
const auto d_y = elemvect.Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i)
{
const int dof_i = d_dofs[i];
@@ -740,7 +761,7 @@ void Vector::SetSubVector(const Array<int> &dofs, const Vector &elemvect)
void Vector::SetSubVector(const Array<int> &dofs, real_t *elem_data)
{
// Use read+write access because we overwrite only part of the data.
data.ReadWrite(MemoryClass::HOST, size);
HostReadWrite();
const int n = dofs.Size();
for (int i = 0; i < n; i++)
{
@@ -764,9 +785,9 @@ void Vector::AddElementVector(const Array<int> &dofs, const Vector &elemvect)
const bool use_dev = dofs.UseDevice() || elemvect.UseDevice();
const int n = dofs.Size();
auto d_y = elemvect.Read(use_dev);
const auto d_y = elemvect.Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
auto d_X = ReadWrite(use_dev);
auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i)
{
const int j = d_dofs[i];
@@ -783,7 +804,7 @@ void Vector::AddElementVector(const Array<int> &dofs, const Vector &elemvect)
void Vector::AddElementVector(const Array<int> &dofs, real_t *elem_data)
{
data.ReadWrite(MemoryClass::HOST, size);
HostReadWrite();
const int n = dofs.Size();
for (int i = 0; i < n; i++)
{
@@ -808,9 +829,9 @@ void Vector::AddElementVector(const Array<int> &dofs, const real_t a,
const bool use_dev = dofs.UseDevice() || elemvect.UseDevice();
const int n = dofs.Size();
const auto d_x = elemvect.Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
auto d_y = ReadWrite(use_dev);
auto d_x = elemvect.Read(use_dev);
auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i)
{
const int j = d_dofs[i];
@@ -835,7 +856,7 @@ void Vector::SetSubVectorComplement(const Array<int> &dofs, const real_t val)
Device::GetHostMemoryType());
auto d_data = ReadWrite(use_dev);
auto d_dofs_vals = dofs_vals.Write(use_dev);
auto d_dofs = dofs.Read(use_dev);
const auto d_dofs = dofs.Read(use_dev);
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i) { d_dofs_vals[i] = d_data[d_dofs[i]]; });
mfem::forall_switch(use_dev, N, [=] MFEM_HOST_DEVICE (int i) { d_data[i] = val; });
mfem::forall_switch(use_dev, n, [=] MFEM_HOST_DEVICE (int i) { d_data[d_dofs[i]] = d_dofs_vals[i]; });
@@ -844,7 +865,7 @@ void Vector::SetSubVectorComplement(const Array<int> &dofs, const real_t val)
void Vector::Print(std::ostream &os, int width) const
{
if (!size) { return; }
data.Read(MemoryClass::HOST, size);
HostRead();
for (int i = 0; 1; )
{
os << ZeroSubnormal(data[i]);
@@ -870,7 +891,7 @@ void Vector::Print(adios2stream &os,
const std::string& variable_name) const
{
if (!size) { return; }
data.Read(MemoryClass::HOST, size);
HostRead();
os.engine.Put(variable_name, &data[0] );
}
#endif
@@ -928,10 +949,7 @@ void Vector::PrintHash(std::ostream &os) const
void Vector::Randomize(int seed)
{
if (seed == 0)
{
seed = (int)time(0);
}
if (seed == 0) { seed = (int)time(0); }
srand((unsigned)seed);
@@ -947,20 +965,15 @@ real_t Vector::Norml2() const
// Scale entries of Vector on the fly, using algorithms from
// std::hypot() and LAPACK's drm2. This scaling ensures that the
// argument of each call to std::pow is <= 1 to avoid overflow.
if (size == 0)
{
return 0.0;
}
if (size == 0) { return 0.0; }
auto m_data = Read(UseDevice());
const auto m_data = Read(UseDevice());
using value_type = DevicePair<real_t, real_t>;
value_type res;
res.first = 0;
res.second = 0;
// first compute sum (|m_data|/scale)^2
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, value_type &r)
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, value_type &r)
{
real_t n = fabs(m_data[i]);
if (n > 0)
@@ -987,11 +1000,12 @@ real_t Vector::Normlinf() const
{
if (size == 0) { return 0; }
auto m_data = Read(UseDevice());
real_t res = 0;
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, real_t &r) { r = fmax(r, fabs(m_data[i])); },
const auto m_data = Read(UseDevice());
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r)
{
r = fmax(r, fabs(m_data[i]));
},
MaxReducer<real_t> {}, UseDevice(), vector_workspace());
return res;
}
@@ -1000,11 +1014,12 @@ real_t Vector::Norml1() const
{
if (size == 0) { return 0.0; }
auto m_data = Read(UseDevice());
real_t res = 0;
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, real_t &r) { r += fabs(m_data[i]); },
const auto m_data = Read(UseDevice());
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r)
{
r += fabs(m_data[i]);
},
SumReducer<real_t> {}, UseDevice(), vector_workspace());
return res;
}
@@ -1013,33 +1028,24 @@ real_t Vector::Normlp(real_t p) const
{
MFEM_ASSERT(p > 0.0, "Vector::Normlp");
if (p == 1.0)
{
return Norml1();
}
if (p == 2.0)
{
return Norml2();
}
if (p == 1.0) { return Norml1(); }
if (p == 2.0) { return Norml2(); }
if (p < infinity())
{
// Scale entries of Vector on the fly, using algorithms from
// std::hypot() and LAPACK's drm2. This scaling ensures that the
// argument of each call to std::pow is <= 1 to avoid overflow.
if (size == 0)
{
return 0.0;
}
if (size == 0) { return 0.0; }
auto m_data = Read(UseDevice());
using value_type = DevicePair<real_t, real_t>;
value_type res;
res.first = 0;
res.second = 0;
const auto m_data = Read(UseDevice());
// first compute sum (|m_data|/scale)^p
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, value_type &r)
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, value_type &r)
{
real_t n = fabs(m_data[i]);
if (n > 0)
@@ -1068,163 +1074,182 @@ real_t Vector::Normlp(real_t p) const
real_t Vector::operator*(const Vector &v) const
{
MFEM_ASSERT(size == v.size, "incompatible Vectors!");
if (size == 0) { return 0.0; }
const bool use_dev = UseDevice() || v.UseDevice();
const auto m_data = Read(use_dev), v_data = v.Read(use_dev);
auto m_data = Read(use_dev);
auto v_data = v.Read(use_dev);
if (use_dev)
{
// special path for OCCA and OpenMP
// If OCCA is enabled, it handles all selected backends
#ifdef MFEM_USE_OCCA
if (DeviceCanUseOcca())
{
return occa::linalg::dot<real_t, real_t, real_t>(
OccaMemoryRead(data, size), OccaMemoryRead(v.data, size));
}
if (use_dev && DeviceCanUseOcca())
{
return occa::linalg::dot<real_t, real_t, real_t>(
OccaMemoryRead(data, size), OccaMemoryRead(v.data, size));
}
#endif
#ifdef MFEM_USE_OPENMP
if (Device::Allows(Backend::OMP_MASK))
const auto compute_dot = [&]()
{
real_t res = 0;
reduce(size, res, [=] MFEM_HOST_DEVICE (int i, real_t &r)
{
r += m_data[i] * v_data[i];
},
SumReducer<real_t> {}, use_dev, vector_workspace());
return res;
};
// Device backends have top priority
if (Device::Allows(Backend::DEVICE_MASK)) { return compute_dot(); }
// Special path for OpenMP
#ifdef MFEM_USE_OPENMP
if (use_dev && Device::Allows(Backend::OMP_MASK))
{
// By default, use a deterministic way of computing the dot product
#define MFEM_USE_OPENMP_DETERMINISTIC_DOT
#ifdef MFEM_USE_OPENMP_DETERMINISTIC_DOT
// By default, use a deterministic way of computing the dot product
static Vector th_dot;
#pragma omp parallel
static Vector th_dot;
#pragma omp parallel
{
const int nt = omp_get_num_threads();
#pragma omp master
th_dot.SetSize(nt);
const int tid = omp_get_thread_num();
const int stride = (size + nt - 1) / nt;
const int start = tid * stride;
const int stop = std::min(start + stride, size);
real_t my_dot = 0.0;
for (int i = start; i < stop; i++)
{
const int nt = omp_get_num_threads();
#pragma omp master
th_dot.SetSize(nt);
const int tid = omp_get_thread_num();
const int stride = (size + nt - 1) / nt;
const int start = tid * stride;
const int stop = std::min(start + stride, size);
real_t my_dot = 0.0;
for (int i = start; i < stop; i++)
{
my_dot += m_data[i] * v_data[i];
}
#pragma omp barrier
th_dot(tid) = my_dot;
my_dot += m_data[i] * v_data[i];
}
return th_dot.Sum();
#else
// The standard way of computing the dot product is non-deterministic
real_t prod = 0.0;
#pragma omp parallel for reduction(+ : prod)
for (int i = 0; i < size; i++)
{
prod += m_data[i] * v_data[i];
}
return prod;
#endif // MFEM_USE_OPENMP_DETERMINISTIC_DOT
#pragma omp barrier
th_dot(tid) = my_dot;
}
#endif // MFEM_USE_OPENMP
return th_dot.Sum();
#else
// The standard way of computing the dot product is non-deterministic
real_t prod = 0.0;
#pragma omp parallel for reduction(+ : prod)
for (int i = 0; i < size; i++)
{
prod += m_data[i] * v_data[i];
}
return prod;
#endif // MFEM_USE_OPENMP_DETERMINISTIC_DOT
}
#endif // MFEM_USE_OPENMP
// normal path for everything else (cuda, hip, debug, cpu)
real_t res = 0;
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, real_t &r) { r += m_data[i] * v_data[i]; },
SumReducer<real_t> {}, use_dev, vector_workspace());
return res;
// All other CPU backends
return compute_dot();
}
real_t Vector::Min() const
{
if (size == 0) { return infinity(); }
const bool use_dev = UseDevice();
auto m_data = Read(use_dev);
if (use_dev)
{
// special case for OCCA and OpenMP
const auto use_dev = UseDevice();
const auto m_data = Read(use_dev);
#ifdef MFEM_USE_OCCA
if (DeviceCanUseOcca())
{
return occa::linalg::min<real_t,real_t>(OccaMemoryRead(data, size));
}
#endif
#ifdef MFEM_USE_OPENMP
if (Device::Allows(Backend::OMP_MASK))
{
real_t minimum = m_data[0];
#pragma omp parallel for reduction(min:minimum)
for (int i = 0; i < size; i++)
{
minimum = std::min(minimum, m_data[i]);
}
return minimum;
}
#endif
if (use_dev && DeviceCanUseOcca())
{
return occa::linalg::min<real_t,real_t>(OccaMemoryRead(data, size));
}
#endif
// normal path for everything else (cuda, hip, debug, cpu)
real_t res = infinity();
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, real_t &r) { r = fmin(r, m_data[i]); },
MinReducer<real_t> {}, use_dev, vector_workspace());
return res;
const auto compute_min = [&]()
{
real_t res = infinity();
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r)
{
r = fmin(r, m_data[i]);
},
MinReducer<real_t> {}, use_dev, vector_workspace());
return res;
};
// Device backends have top priority
if (Device::Allows(Backend::DEVICE_MASK)) { return compute_min(); }
// Special path for OpenMP
#ifdef MFEM_USE_OPENMP
if (use_dev && Device::Allows(Backend::OMP_MASK))
{
real_t minimum = m_data[0];
#pragma omp parallel for reduction(min:minimum)
for (int i = 0; i < size; i++)
{
minimum = std::min(minimum, m_data[i]);
}
return minimum;
}
#endif
// All other CPU backends
return compute_min();
}
real_t Vector::Max() const
{
if (size == 0) { return -infinity(); }
const bool use_dev = UseDevice();
auto m_data = Read(use_dev);
const auto use_dev = UseDevice();
const auto m_data = Read(use_dev);
if (use_dev)
{
// special cases where OCCA or OenMP are used
#ifdef MFEM_USE_OCCA
if (DeviceCanUseOcca())
{
return occa::linalg::max<real_t, real_t>(OccaMemoryRead(data, size));
}
#endif
#ifdef MFEM_USE_OPENMP
if (Device::Allows(Backend::OMP_MASK))
{
real_t maximum = m_data[0];
#pragma omp parallel for reduction(max : maximum)
for (int i = 0; i < size; i++)
{
maximum = fmax(maximum, m_data[i]);
}
return maximum;
}
#endif
if (use_dev && DeviceCanUseOcca())
{
return occa::linalg::max<real_t, real_t>(OccaMemoryRead(data, size));
}
#endif
// normal path for everything else (cuda, hip, debug, cpu)
real_t res = -infinity();
reduce(
size, res,
[=] MFEM_HOST_DEVICE(int i, real_t &r) { r = fmax(r, m_data[i]); },
MaxReducer<real_t> {}, use_dev, vector_workspace());
return res;
const auto compute_max = [&]()
{
real_t res = -infinity();
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r)
{
r = fmax(r, m_data[i]);
},
MaxReducer<real_t> {}, use_dev, vector_workspace());
return res;
};
// Device backends have top priority
if (Device::Allows(Backend::DEVICE_MASK)) { return compute_max(); }
// Special path for OpenMP
#ifdef MFEM_USE_OPENMP
if (use_dev && Device::Allows(Backend::OMP_MASK))
{
real_t maximum = m_data[0];
#pragma omp parallel for reduction(max : maximum)
for (int i = 0; i < size; i++)
{
maximum = fmax(maximum, m_data[i]);
}
return maximum;
}
#endif
// All other CPU backends
return compute_max();
}
real_t Vector::Sum() const
{
if (size == 0) { return 0.0; }
auto m_data = Read(UseDevice());
real_t res = 0;
reduce(
size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r) { r += m_data[i]; },
const auto m_data = Read(UseDevice());
reduce(size, res, [=] MFEM_HOST_DEVICE(int i, real_t &r)
{
r += m_data[i];
},
SumReducer<real_t> {}, UseDevice(), vector_workspace());
return res;
}
}
} // namespace mfem
+6
View File
@@ -360,6 +360,12 @@ public:
/// (*this)(i) = 1.0 / (*this)(i)
void Reciprocal();
/// (*this)(i) = abs((*this)(i))
void Abs();
/// (*this)(i) = pow((*this)(i), p)
void Pow(const real_t p);
/// Swap the contents of two Vectors
inline void Swap(Vector &other);
+23 -10
View File
@@ -124,12 +124,12 @@ EXAMPLE_DIRS := examples $(addprefix examples/,$(EXAMPLE_SUBDIRS))
EXAMPLE_TEST_DIRS := examples
MINIAPP_SUBDIRS = common electromagnetics meshing navier performance tools \
toys nurbs gslib adjoint solvers shifted mtop parelag tribol autodiff hooke \
multidomain dpg hdiv-linear-solver spde
toys nurbs gslib adjoint solvers shifted mtop parelag tribol autodiff dfem \
hooke multidomain dpg hdiv-linear-solver spde diag-smoothers
MINIAPP_DIRS := $(addprefix miniapps/,$(MINIAPP_SUBDIRS))
MINIAPP_TEST_DIRS := $(filter-out %/common,$(MINIAPP_DIRS))
MINIAPP_USE_COMMON := $(addprefix miniapps/,electromagnetics meshing tools \
toys shifted dpg)
toys shifted dpg diag-smoothers)
EM_DIRS = $(EXAMPLE_DIRS) $(MINIAPP_DIRS)
@@ -243,10 +243,23 @@ endif
ifeq ($(MFEM_USE_CUDA),YES)
MFEM_CXX ?= $(CUDA_CXX)
MFEM_HOST_CXX ?= $(HOST_CXX)
CXXFLAGS += $(CUDA_FLAGS) -ccbin $(MFEM_HOST_CXX)
XCOMPILER = $(CUDA_XCOMPILER)
XLINKER = $(CUDA_XLINKER)
ifeq ($(shell $(MFEM_CXX) --version 2>&1 | grep "NVIDIA"),)
# assume clang
MFEM_HOST_CXX ?= $(MFEM_CXX)
CXXFLAGS += $(CLANG_CUDA_FLAGS)
XCOMPILER = $(CXX_XCOMPILER)
XLINKER = $(CXX_XLINKER)
CUDA_LIB := $(CLANG_CUDA_LIB) $(CUDA_LIB)
else
ifeq ($(MFEM_USE_ENZYME),YES)
$(error Cannot use nvcc with Enzyme! Set CUDA_CXX to CUDA-enabled \
clang++ or an MPI wrapper of that)
endif
MFEM_HOST_CXX ?= $(HOST_CXX)
CXXFLAGS += $(NVCC_FLAGS) -ccbin $(MFEM_HOST_CXX)
XCOMPILER = $(CUDA_XCOMPILER)
XLINKER = $(CUDA_XLINKER)
endif
# CUDA_OPT and CUDA_LIB are added below
# Compatibility test against MFEM_USE_HIP
ifeq ($(MFEM_USE_HIP),YES)
@@ -285,7 +298,7 @@ ifeq ($(MFEM_USE_LEGACY_OPENMP),YES)
endif
# List of MFEM dependencies, that require the *_LIB variable to be non-empty
MFEM_REQ_LIB_DEPS = ENZYME SUPERLU MUMPS METIS FMS CONDUIT SIDRE LAPACK SUNDIALS\
MFEM_REQ_LIB_DEPS = SUPERLU MUMPS METIS FMS CONDUIT SIDRE LAPACK SUNDIALS\
SUITESPARSE STRUMPACK GINKGO GNUTLS HDF5 NETCDF SLEPC PETSC MPFR PUMI HIOP\
GSLIB OCCA CEED RAJA UMPIRE MKL_CPARDISO MKL_PARDISO AMGX MAGMA CALIPER PARELAG\
TRIBOL BENCHMARK MOONOLITH ALGOIM
@@ -307,7 +320,7 @@ ifeq ($(MAKECMDGOALS),config)
endif
# List of MFEM dependencies, processed below
MFEM_DEPENDENCIES = $(MFEM_REQ_LIB_DEPS) LIBUNWIND OPENMP CUDA HIP
MFEM_DEPENDENCIES = ENZYME $(MFEM_REQ_LIB_DEPS) LIBUNWIND OPENMP CUDA HIP
# List of deprecated MFEM dependencies, processed below
MFEM_LEGACY_DEPENDENCIES = OPENMP
@@ -429,7 +442,7 @@ DIRS = general linalg linalg/batched linalg/simd mesh mesh/submesh fem \
fem/ceed/integrators/mass fem/ceed/integrators/convection \
fem/ceed/integrators/diffusion fem/ceed/integrators/nlconvection \
fem/ceed/interface fem/ceed/solvers fem/eltrans fem/fe fem/gslib \
fem/integ fem/lor fem/moonolith fem/qinterp fem/tmop
fem/integ fem/lor fem/moonolith fem/qinterp fem/tmop fem/dfem
ifeq ($(MFEM_USE_MOONOLITH),YES)
MFEM_CXXFLAGS += $(MOONOLITH_CXX_FLAGS)
+286 -195
View File
@@ -32,6 +32,7 @@
#include <cstring>
#include <ctime>
#include <functional>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
@@ -1553,6 +1554,7 @@ Geometry::Type Mesh::GetTypicalElementGeometry() const
return geom;
}
void Mesh::GetExteriorFaceMarker(Array<int> & face_marker) const
{
const int num_faces = GetNumFaces();
@@ -3247,6 +3249,19 @@ int Mesh::GetPatchBdrAttribute(int i) const
return NURBSext->GetPatchBdrAttribute(i);
}
void Mesh::GetNURBSPatches(Array<NURBSPatch*> &patches)
{
MFEM_VERIFY(NURBSext, "Must be a NURBS mesh");
// This sets the data in NURBSPatch(es) from the control points (Nodes)
NURBSext->ConvertToPatches(*Nodes);
// Deep copy patches
NURBSext->GetPatches(patches);
// Among other things, this deletes patches in NURBSext
UpdateNURBS();
}
void Mesh::FinalizeTetMesh(int generate_edges, int refine, bool fix_orientation)
{
FinalizeCheck();
@@ -5402,11 +5417,15 @@ void Mesh::MakeRefined_(Mesh &orig_mesh, const Array<int> &ref_factors,
Mesh Mesh::MakeSimplicial(const Mesh &orig_mesh)
{
Mesh mesh;
mesh.MakeSimplicial_(orig_mesh, NULL);
auto parent_elements = mesh.MakeSimplicial_(orig_mesh, NULL);
if (orig_mesh.GetNodes() != nullptr)
{
mesh.MakeHigherOrderSimplicial_(orig_mesh, parent_elements);
}
return mesh;
}
void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
Array<int> Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
{
MFEM_VERIFY(const_cast<Mesh&>(orig_mesh).CheckElementOrientation(false) == 0,
"Mesh::MakeSimplicial requires a properly oriented input mesh");
@@ -5420,7 +5439,9 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
{
Mesh copy(orig_mesh);
Swap(copy, true);
return;
Array<int> parent_elements(GetNE());
std::iota(parent_elements.begin(), parent_elements.end(), 0);
return parent_elements;
}
int nv = orig_mesh.GetNV();
@@ -5462,15 +5483,20 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
// global vertex number). Use the supplied global numbering, if it is
// non-NULL, otherwise use the local numbering.
Array<int> vglobal_id;
if (vglobal == NULL)
if (vglobal == nullptr)
{
vglobal_id.SetSize(nv);
for (int i=0; i<nv; ++i) { vglobal_id[i] = i; }
std::iota(vglobal_id.begin(), vglobal_id.end(), 0);
vglobal = vglobal_id.GetData();
}
// Number of vertices per element
constexpr int nv_tri = 3, nv_quad = 4, nv_tet = 4, nv_prism = 6, nv_hex = 8;
constexpr int quad_ntris = 2, prism_ntets = 3;
constexpr int quad_ntris = 2; // NTriangles per quad
constexpr int prism_ntets = 3; // NTets per prism
// Map verts of quad to verts of tri, in two possible configurations.
// quad_trimap[i][0,2,4] is the first triangle, and quad_trimap[i][1,3,5] is
// the second, for each configuration.
static const int quad_trimap[2][nv_tri*quad_ntris] =
{
{
@@ -5555,8 +5581,9 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
hex_tetmap0, hex_tetmap1, hex_tetmap2, hex_tetmap3
};
auto find_min = [](const int*a, int n) { return std::min_element(a,a+n)-a; };
auto find_min = [](const int *a, int n) { return std::min_element(a,a+n)-a; };
Array<int> parent_elems;
for (int i=0; i<ne; ++i)
{
const int *v = orig_mesh.elements[i]->GetVertices();
@@ -5565,13 +5592,14 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
if (num_subdivisions[orig_geom] == 1)
{
// (num_subdivisions[orig_geom] == 1) implies that the element does
// not need to be further split (it is either a segment, triangle,
// or tetrahedron), and so it is left unchanged.
// (num_subdivisions[orig_geom] == 1) implies that the element does not
// need to be further split (it is either a segment, triangle, or
// tetrahedron), and so it is left unchanged.
Element *e = NewElement(orig_geom);
e->SetAttribute(attrib);
e->SetVertices(v);
AddElement(e);
parent_elems.Append(i);
}
else if (orig_geom == Geometry::SQUARE)
{
@@ -5585,6 +5613,7 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
v2[iv] = v[quad_trimap[0][itri + iv*quad_ntris]];
}
AddElement(e);
parent_elems.Append(i);
}
}
else if (orig_geom == Geometry::PRISM)
@@ -5614,6 +5643,7 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
v2[iv] = vg[tetmap[itet + iv*prism_ntets]];
}
AddElement(e);
parent_elems.Append(i);
}
}
else if (orig_geom == Geometry::CUBE)
@@ -5677,6 +5707,7 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
v2[iv] = vg[tetmap[itet + iv*ntets]];
}
AddElement(e);
parent_elems.Append(i);
}
}
}
@@ -5726,8 +5757,134 @@ void Mesh::MakeSimplicial_(const Mesh &orig_mesh, int *vglobal)
MFEM_ASSERT(CheckElementOrientation(false) == 0, "");
MFEM_ASSERT(CheckBdrElementOrientation(false) == 0, "");
return parent_elems;
}
void Mesh::MakeHigherOrderSimplicial_(const Mesh &orig_mesh, const Array<int> &parent_elements)
{
// Higher order associated to vertices are unchanged, and those for
// previously existing edges. DOFs associated to new elements need to be set.
const int sdim = orig_mesh.SpaceDimension();
auto *orig_fespace = orig_mesh.GetNodes()->FESpace();
SetCurvature(orig_fespace->GetMaxElementOrder(), orig_fespace->IsDGSpace(),
orig_mesh.SpaceDimension(), orig_fespace->GetOrdering());
// The dofs associated with vertices are unchanged, but there can be new dofs
// associated to edges, faces and volumes. Additionally, because we know that
// the set of vertices is unchanged by the splitting operation, we can use
// the vertices to map local coordinates of the "child" elements (the new
// simplices introduced), from the "parent" element (the quad, prism, hex
// that was split).
// For segment, triangle and tetrahedron, the dof values are copied directly.
// For the others, we have to construct a map from the Node locations in the
// new simplex to the parent non-simplex element. This could be sped up by
// not repeatedly access the original FE as the accesses will be coherent
// (i.e. all child elems are consecutive).
Array<int> edofs; // element dofs in new element
Array<int> parent_vertices, child_vertices; // vertices of parent and child.
Array<int> node_map; // node indices of parent from child.
Vector edofvals; // values of elements dofs in original element
// Storage for evaluating node function on parent element, at node locations
// of child element
DenseMatrix shape; // ndof_coarse x nnode_refined.
DenseMatrix point_matrix; // sdim x nnode_refined
IntegrationRule child_nodes_in_parent; // The parent nodes that correspond to the child nodes
for (int i = 0; i < parent_elements.Size(); i++)
{
const int ip = parent_elements[i];
const Geometry::Type orig_geom = orig_mesh.GetElementBaseGeometry(ip);
orig_mesh.GetNodes()->GetElementDofValues(ip, edofvals);
switch (orig_geom)
{
case Geometry::Type::SEGMENT : // fall through
case Geometry::Type::TRIANGLE : // fall through
case Geometry::Type::TETRAHEDRON :
GetNodes()->FESpace()->GetElementVDofs(i, edofs);
GetNodes()->SetSubVector(edofs, edofvals);
break;
case Geometry::Type::CUBE : // fall through
case Geometry::Type::PRISM : // fall through
case Geometry::Type::PYRAMID : // fall through
case Geometry::Type::SQUARE :
{
// Extract the vertices of parent and child, can then form the
// map from child reference coordinates to parent reference
// coordinates. Exploit the fact that for Nodes, the vertex
// entries come first, and their indexing matches the vertex
// numbering. Thus we have already have an inverse index map.
orig_mesh.GetElementVertices(ip, parent_vertices);
GetElementVertices(i, child_vertices);
node_map.SetSize(0);
for (auto cv : child_vertices)
for (int ipv = 0; ipv < parent_vertices.Size(); ipv++)
if (cv == parent_vertices[ipv])
{
node_map.Append(ipv);
break;
}
MFEM_ASSERT(node_map.Size() == Geometry::NumVerts[GetElementBaseGeometry(i)], "!");
// node_map now says which of the parent vertex nodes map to each
// of the child vertex nodes. Using this can build a basis in the
// parent element from child Node values, exploit the linearity
// to then transform all nodes.
child_nodes_in_parent.SetSize(0);
const auto *orig_FE = orig_mesh.GetNodes()->FESpace()->GetFE(ip);
for (auto pn : node_map)
{
child_nodes_in_parent.Append(orig_FE->GetNodes()[pn]);
}
const auto *simplex_FE = GetNodes()->FESpace()->GetFE(i);
shape.SetSize(orig_FE->GetDof(), simplex_FE->GetDof()); // One set of evaluations per simplex dof.
Vector col;
for (int j = 0; j < simplex_FE->GetNodes().Size(); j++)
{
const auto &simplex_node = simplex_FE->GetNodes()[j];
IntegrationPoint simplex_node_in_orig;
// Handle the 2D vs 3D case by multiplying .z by zero.
simplex_node_in_orig.Set3(
child_nodes_in_parent[0].x +
simplex_node.x * (child_nodes_in_parent[1].x - child_nodes_in_parent[0].x)
+ simplex_node.y * (child_nodes_in_parent[2].x - child_nodes_in_parent[0].x)
+ simplex_node.z * (child_nodes_in_parent[(sdim > 2) ? 3 : 0].x - child_nodes_in_parent[0].x),
child_nodes_in_parent[0].y +
simplex_node.x * (child_nodes_in_parent[1].y - child_nodes_in_parent[0].y)
+ simplex_node.y * (child_nodes_in_parent[2].y - child_nodes_in_parent[0].y)
+ simplex_node.z * (child_nodes_in_parent[(sdim > 2) ? 3 : 0].y - child_nodes_in_parent[0].y),
child_nodes_in_parent[0].z +
simplex_node.x * (child_nodes_in_parent[1].z - child_nodes_in_parent[0].z)
+ simplex_node.y * (child_nodes_in_parent[2].z - child_nodes_in_parent[0].z)
+ simplex_node.z * (child_nodes_in_parent[(sdim > 2) ? 3 : 0].z - child_nodes_in_parent[0].z));
shape.GetColumnReference(j, col);
orig_FE->CalcShape(simplex_node_in_orig, col);
}
// All the non-simplex basis functions have now been evaluated at
// all the simplex basis function node locations. Now evaluate
// the summations and place back into the Nodes vector.
orig_mesh.GetNodes()->GetElementDofValues(ip, edofvals);
// Dof values are always returned as
// [[x_1,x_2,x_3,...],
// [y_1,y_2,y_3,...],
// [z_1,z_2,z_3,...]]
DenseMatrix edofvals_mat(edofvals.GetData(), orig_FE->GetDof(), sdim);
point_matrix.SetSize(simplex_FE->GetDof(), sdim);
MultAtB(shape, edofvals_mat, point_matrix);
GetNodes()->FESpace()->GetElementVDofs(i, edofs);
GetNodes()->SetSubVector(edofs, point_matrix.GetData());
}
break;
case Geometry::Type::POINT : // fall through
case Geometry::Type::INVALID :
case Geometry::Type::NUM_GEOMETRIES :
MFEM_ABORT("Internal Error!");
}
}
}
Mesh Mesh::MakePeriodic(const Mesh &orig_mesh, const std::vector<int> &v2v)
{
Mesh periodic_mesh(orig_mesh, true); // Make a copy of the original mesh
@@ -6129,7 +6286,7 @@ void Mesh::UpdateNURBS()
GenerateFaces();
}
void Mesh::LoadPatchTopo(std::istream &input, Array<int> &edge_to_knot)
void Mesh::LoadPatchTopo(std::istream &input, Array<int> &edge_to_ukv)
{
SetEmpty();
@@ -6169,20 +6326,20 @@ void Mesh::LoadPatchTopo(std::istream &input, Array<int> &edge_to_knot)
if (NumOfEdges > 0)
{
edge_vertex = new Table(NumOfEdges, 2);
edge_to_knot.SetSize(NumOfEdges);
edge_to_ukv.SetSize(NumOfEdges);
for (int j = 0; j < NumOfEdges; j++)
{
int *v = edge_vertex->GetRow(j);
input >> edge_to_knot[j] >> v[0] >> v[1];
input >> edge_to_ukv[j] >> v[0] >> v[1];
if (v[0] > v[1])
{
edge_to_knot[j] = -1 - edge_to_knot[j];
edge_to_ukv[j] = -1 - edge_to_ukv[j];
}
}
}
else
{
edge_to_knot.SetSize(0);
edge_to_ukv.SetSize(0);
}
skip_comment_lines(input, '#');
@@ -6194,196 +6351,129 @@ void Mesh::LoadPatchTopo(std::istream &input, Array<int> &edge_to_knot)
FinalizeTopology();
CheckBdrElementOrientation(); // check and fix boundary element orientation
/* Generate knot 2 edge mapping -- if edges are not specified in the mesh file
See data/two-squares-nurbs-autoedge.mesh for an example */
if (edge_to_knot.Size() == 0)
/* Generate edge to knotvector mapping if edges are not specified in the
mesh file. See miniapps/nurbs/meshes/two-squares-nurbs-autoedge.mesh
for an example */
if (edge_to_ukv.Size() == 0)
{
edge_vertex = new Table(NumOfEdges, 2);
edge_to_knot.SetSize(NumOfEdges);
constexpr int notset = -9999999;
edge_to_knot = notset;
Array<int> edges;
Array<int> oedge;
int knot = 0;
Array<int> ukv_to_rpkv;
GetEdgeToUniqueKnotvector(edge_to_ukv, ukv_to_rpkv);
}
}
Array<int> edge0, edge1;
int flip = 1;
if (Dimension() == 2)
void Mesh::GetEdgeToUniqueKnotvector(Array<int> &edge_to_ukv,
Array<int> &ukv_to_rpkv) const
{
const int dim = Dimension(); // topological (not physical) dimension
const int NP = NumOfElements; // number of patches
const int NPKV = NP * dim; // number of patch knotvectors
constexpr int notset = -9999999;
// Sign convention
auto sign = [](int i) { return -1 - i; };
auto unsign = [](int i) { return (i < 0) ? -1 - i : i; };
// Edge index -> dimension convention
auto edge_to_dim = [](int i) { return (i < 8) ? ((i & 1) ? 1 : 0) : 2; };
Array<int> v(2); // vertices of an edge
// 1D case is special: edge index = signed element index
// ukv_to_rpkv = Identity
if (dim == 1)
{
edge_to_ukv.SetSize(NP);
ukv_to_rpkv.SetSize(NP);
for (int i = 0; i < NP; i++)
{
edge0.SetSize(2);
edge1.SetSize(2);
edge0[0] = 0; edge1[0] = 2;
edge0[1] = 1; edge1[1] = 3;
flip = 1;
GetElementVertices(i, v);
// Sign is based on the edge's vertex indices
edge_to_ukv[i] = (v[1] > v[0]) ? i : sign(i);
ukv_to_rpkv[i] = i;
}
else if (Dimension() == 3)
return;
}
// Local (per-patch) variables
Array<int> edges, oedges;
// Edge index -> signed patch knotvector index (p*dim + d)
Array<int> edge_to_pkv(NumOfEdges);
edge_to_pkv.SetSize(NumOfEdges);
edge_to_pkv = notset;
// Initialize pkv_map as identity - this is the storage for the
// disjoint-set/union-find algorithm which will later be used
// to get the map pkv_to_rpkv
Array<int> pkv_map(NPKV);
for (int i = 0; i < NPKV; i++)
{
pkv_map[i] = i;
}
std::function<int(int)> get_root;
get_root = [&pkv_map, &get_root](int i) -> int
{
return (pkv_map[i] == i) ? i : get_root(pkv_map[i]);
};
auto unite = [&pkv_map, &get_root](int i, int j)
{
const int ri = get_root(i);
const int rj = get_root(j);
if (ri == rj) return;
// keep the lowest index
(ri < rj) ? pkv_map[rj] = ri : pkv_map[ri] = rj;
};
// Get edge_to_pkv (one edge can link to multiple pkv) and pkv_map
for (int p = 0; p < NP; p++)
{
GetElementEdges(p, edges, oedges);
// First loop checks for if edge has already been set
for (int i = 0; i < edges.Size(); i++)
{
edge0.SetSize(9);
edge1.SetSize(9);
const int edge = edges[i];
const int d = edge_to_dim(i);
const int pkv = p*dim+d;
edge0[0] = 0; edge1[0] = 2;
edge0[1] = 0; edge1[1] = 4;
edge0[2] = 0; edge1[2] = 6;
edge0[3] = 1; edge1[3] = 3;
edge0[4] = 1; edge1[4] = 5;
edge0[5] = 1; edge1[5] = 7;
edge0[6] = 8; edge1[6] = 9;
edge0[7] = 8; edge1[7] = 10;
edge0[8] = 8; edge1[8] = 11;
flip = -1;
}
/* Initial assignment of knots to edges. This is an algorithm that loops over the
patches and assigns knot vectors to edges. It starts with assigning knot vector 0
and 1 to the edges of the first patch. Then it uses: 1) patches can share edges
2) knot vectors on opposing edges in a patch are equal, to create edge_to_knot */
int e0, e1, v0, v1, df;
int p,j,k;
for (p = 0; p < GetNE(); p++)
{
GetElementEdges(p, edges, oedge);
const int *v = elements[p]->GetVertices();
for (j = 0; j < edges.Size(); j++)
// We've set this edge already - link this index to it
if (edge_to_pkv[edge] != notset)
{
int *vv = edge_vertex->GetRow(edges[j]);
const int *e = elements[p]->GetEdgeVertices(j);
if (oedge[j] == 1)
{
vv[0] = v[e[0]];
vv[1] = v[e[1]];
}
else
{
vv[0] = v[e[1]];
vv[1] = v[e[0]];
}
const int pkv_other = unsign(edge_to_pkv[edge]);
unite(pkv, pkv_other);
}
for (j = 0; j < edge1.Size(); j++)
else
{
e0 = edges[edge0[j]];
e1 = edges[edge1[j]];
v0 = edge_to_knot[e0];
v1 = edge_to_knot[e1];
df = flip*oedge[edge0[j]]*oedge[edge1[j]];
// Case 1: knot vector is not set
if ((v0 == notset) && (v1 == notset))
{
edge_to_knot[e0] = knot;
edge_to_knot[e1] = knot;
knot++;
}
// Case 2 & 3: knot vector on one of the two edges
// is set earlier (in another patch). We just have
// to copy it for the opposing edge.
else if ((v0 != notset) && (v1 == notset))
{
edge_to_knot[e1] = (df >= 0 ? -v0-1 : v0);
}
else if ((v0 == notset) && (v1 != notset))
{
edge_to_knot[e0] = (df >= 0 ? -v1-1 : v1);
}
GetEdgeVertices(edge, v);
// Sign is based on the edge's vertex indices
edge_to_pkv[edge] = (v[1] > v[0]) ? pkv : sign(pkv);
}
}
}
/* Verify correct assignment, make sure that corresponding edges
within patch point to same knot vector. If not assign the lowest number.
// Construct the pkv_to_rpkv map by finding the lowest/root index
Array<int> pkv_to_rpkv(NPKV);
ukv_to_rpkv.SetSize(NPKV);
for (int i = 0; i < NPKV; i++)
{
pkv_to_rpkv[i] = get_root(pkv_map[i]);
ukv_to_rpkv[i] = pkv_to_rpkv[i];
}
ukv_to_rpkv.Sort(); // ukv is just a renumbering of rpkv
ukv_to_rpkv.Unique();
We bound the while by GetNE() + 1 as this is probably the most unlucky
case. +1 to finish without corrections. Note that this is a check and
in general the initial assignment is correct. Then the while is performed
only once. Only on very tricky meshes it might need corrections.*/
int corrections;
int passes = 0;
do
{
corrections = 0;
for (p = 0; p < GetNE(); p++)
{
GetElementEdges(p, edges, oedge);
for (j = 0; j < edge1.Size(); j++)
{
e0 = edges[edge0[j]];
e1 = edges[edge1[j]];
v0 = edge_to_knot[e0];
v1 = edge_to_knot[e1];
v0 = ( v0 >= 0 ? v0 : -v0-1);
v1 = ( v1 >= 0 ? v1 : -v1-1);
if (v0 != v1)
{
corrections++;
if (v0 < v1)
{
edge_to_knot[e1] = (oedge[edge1[j]] >= 0 ? v0 : -v0-1);
}
else if (v1 < v0)
{
edge_to_knot[e0] = (oedge[edge0[j]] >= 0 ? v1 : -v1-1);
}
}
}
}
// Create inverse map
std::map<int, int> rpkv_to_ukv;
for (int i = 0; i < ukv_to_rpkv.Size(); i++)
{
rpkv_to_ukv[ukv_to_rpkv[i]] = i;
}
passes++;
}
while (corrections > 0 && passes < GetNE() + 1);
// Check the validity of corrections applied
if (corrections > 0)
{
mfem::err<<"Edge_to_knot mapping potentially incorrect"<<endl;
mfem::err<<" passes = "<<passes<<endl;
mfem::err<<" corrections = "<<corrections<<endl;
}
/* Renumber knotvectors, such that:
-- numbering is consecutive
-- starts at zero */
Array<int> cnt(NumOfEdges);
cnt = 0;
for (j = 0; j < NumOfEdges; j++)
{
k = edge_to_knot[j];
cnt[(k >= 0 ? k : -k-1)]++;
}
k = 0;
for (j = 0; j < cnt.Size(); j++)
{
cnt[j] = (cnt[j] > 0 ? k++ : -1);
}
for (j = 0; j < NumOfEdges; j++)
{
k = edge_to_knot[j];
edge_to_knot[j] = (k >= 0 ? cnt[k]:-cnt[-k-1]-1);
}
// Print knot to edge mapping
mfem::out<<"Generated edge to knot mapping:"<<endl;
for (j = 0; j < NumOfEdges; j++)
{
int *v = edge_vertex->GetRow(j);
k = edge_to_knot[j];
v0 = v[0];
v1 = v[1];
if (k < 0)
{
v[0] = v1;
v[1] = v0;
}
mfem::out<<(k >= 0 ? k:-k-1)<<" "<< v[0] <<" "<<v[1]<<endl;
}
// Terminate here upon failure after printing to have an idea of edge_to_knot.
if (corrections > 0 ) {mfem_error("Mesh::LoadPatchTopo");}
// Get edge_to_ukv = edge_to_pkv -> pkv_to_rpkv -> rpkv_to_ukv
edge_to_ukv.SetSize(NumOfEdges);
for (int i = 0; i < NumOfEdges; i++)
{
const int pkv = unsign(edge_to_pkv[i]);
const int rpkv = pkv_to_rpkv[pkv];
const int ukv = rpkv_to_ukv[rpkv];
edge_to_ukv[i] = (edge_to_pkv[i] < 0) ? sign(ukv) : ukv;
}
}
@@ -14518,11 +14608,12 @@ MeshPartitioner::ExtractGridFunction(const MeshPart &mesh_part,
for (int loc_elem_id = 0; loc_elem_id < num_elems; loc_elem_id++)
{
const int glob_elem_id = elem_list[loc_elem_id];
auto glob_dt = global_gf.FESpace()->GetElementVDofs(glob_elem_id, gvdofs);
DofTransformation glob_dt, local_dt;
global_gf.FESpace()->GetElementVDofs(glob_elem_id, gvdofs, glob_dt);
global_gf.GetSubVector(gvdofs, loc_vals);
if (glob_dt) { glob_dt->InvTransformPrimal(loc_vals); }
auto local_dt = local_fespace.GetElementVDofs(loc_elem_id, lvdofs);
if (local_dt) { local_dt->TransformPrimal(loc_vals); }
glob_dt.InvTransformPrimal(loc_vals);
local_fespace.GetElementVDofs(loc_elem_id, lvdofs, local_dt);
local_dt.TransformPrimal(loc_vals);
local_gf->SetSubVector(lvdofs, loc_vals);
}
return local_gf;
+58 -2
View File
@@ -39,6 +39,7 @@ namespace mfem
class GeometricFactors;
class FaceGeometricFactors;
class KnotVector;
class NURBSPatch;
class NURBSExtension;
class FiniteElementSpace;
class GridFunction;
@@ -472,7 +473,7 @@ protected:
const int *fine, int nfine, int op);
/// Read NURBS patch/macro-element mesh
void LoadPatchTopo(std::istream &input, Array<int> &edge_to_knot);
void LoadPatchTopo(std::istream &input, Array<int> &edge_to_ukv);
void UpdateNURBS();
@@ -662,8 +663,34 @@ protected:
Array<int> &elem_vtx, Array<int> &attr) const;
// Internal helper used in MakeSimplicial (and ParMesh::MakeSimplicial).
void MakeSimplicial_(const Mesh &orig_mesh, int *vglobal);
/**
* @brief Internal helper user in MakeSimplicial (and
* ParMesh::MakeSimplicial). Optional return is used in assembling a higher
* order mesh.
* @details The construction of the higher order nodes must be separated out
* because the
*
* @param orig_mesh The mesh from to create the simplices
* @param vglobal An optional global ordering of vertices. Necessary for
* parallel splitting.
* @return Array<int> parent elements from the orig_mesh for each split
* element
*/
Array<int> MakeSimplicial_(const Mesh &orig_mesh, int *vglobal);
/**
* @brief Helper function for constructing higher order nodes from a mesh
* transformed into simplices. Only to be called as part of MakeSimplicial
* or ParMesh::MakeSimplicial.
*
* @param orig_mesh The mesh that was used to transform this mesh into
* simplices.
* @param parent_elements parent_elements[i] gives the element in orig_mesh
* split to give element i.
*/
void MakeHigherOrderSimplicial_(const Mesh &orig_mesh,
const Array<int> &parent_elements);
public:
/// @anchor mfem_Mesh_ctors
@@ -763,6 +790,29 @@ public:
/// Destroys Mesh.
virtual ~Mesh() { DestroyPointers(); }
/** Get the edge to unique knotvector map used by NURBS patch topology meshes
Various index maps are defined using the following indices:
edge: Edge index in the patch topology mesh
pkv: Patch knotvector index, equivalent to (p * dim + d) where
p is the patch index, dim is the topological dimension of
the patch, and d is the local dimension
rpkv: Root patch knotvector index; the lowest index pkv for all
equivalent pkv.
ukv: (signed) Unique knotvector index. Equivalent to rpkv reordered
from 0 to N-1, where N is the number of unique knotvectors +
sign, which indicates the orientation of the edge.
@param[in,out] edge_to_ukv Array<int> Map from edge index to (signed)
unique knotvector index. Will be resized
to the number of edges.
@param[in,out] ukv_to_rpkv Array<int> Map from (unsigned) unique
knotvector index to the (unsigned) root
patch knotvector index. Will be resized
to the number of unique knotvectors.
*/
void GetEdgeToUniqueKnotvector(Array<int> &edge_to_ukv,
Array<int> &ukv_to_rpkv) const;
/// @}
/** @anchor mfem_Mesh_named_ctors @name Named mesh constructors.
@@ -1409,6 +1459,12 @@ public:
/// Set the attribute of patch boundary element i, for a NURBS mesh.
void SetPatchBdrAttribute(int i, int attr);
/** Returns a deep copy of all patches. This method is not const
as it first sets the patches in NURBSext using control points
defined by Nodes. Caller gets ownership of the returned object,
and is responsible for deletion.*/
void GetNURBSPatches(Array<NURBSPatch*> &patches);
/// Returns the type of element i.
Element::Type GetElementType(int i) const;
+61 -60
View File
@@ -1984,7 +1984,7 @@ NURBSExtension::NURBSExtension(const NURBSExtension &orig)
activeDof(orig.activeDof),
patchTopo(new Mesh(*orig.patchTopo)),
own_topo(true),
edge_to_knot(orig.edge_to_knot),
edge_to_ukv(orig.edge_to_ukv),
knotVectors(orig.knotVectors.Size()), // knotVectors are copied in the body
knotVectorsCompr(orig.knotVectorsCompr.Size()),
weights(orig.weights),
@@ -2025,7 +2025,7 @@ NURBSExtension::NURBSExtension(std::istream &input, bool spacing)
{
// Read topology
patchTopo = new Mesh;
patchTopo->LoadPatchTopo(input, edge_to_knot);
patchTopo->LoadPatchTopo(input, edge_to_ukv);
own_topo = true;
CheckPatches();
@@ -2227,7 +2227,7 @@ NURBSExtension::NURBSExtension(NURBSExtension *parent, int newOrder)
patchTopo = parent->patchTopo;
own_topo = false;
parent->edge_to_knot.Copy(edge_to_knot);
parent->edge_to_ukv.Copy(edge_to_ukv);
NumOfKnotVectors = parent->GetNKV();
knotVectors.SetSize(NumOfKnotVectors);
@@ -2285,7 +2285,7 @@ NURBSExtension::NURBSExtension(NURBSExtension *parent,
patchTopo = parent->patchTopo;
own_topo = false;
parent->edge_to_knot.Copy(edge_to_knot);
parent->edge_to_ukv.Copy(edge_to_ukv);
NumOfKnotVectors = parent->GetNKV();
MFEM_VERIFY(mOrders.Size() == NumOfKnotVectors, "invalid newOrders array");
@@ -2344,7 +2344,7 @@ NURBSExtension::NURBSExtension(Mesh *mesh_array[], int num_pieces)
own_topo = true;
parent->own_topo = false;
parent->edge_to_knot.Copy(edge_to_knot);
parent->edge_to_ukv.Copy(edge_to_ukv);
parent->GetOrders().Copy(mOrders);
mOrder = parent->GetOrder();
@@ -2377,70 +2377,61 @@ NURBSExtension::NURBSExtension(Mesh *mesh_array[], int num_pieces)
}
NURBSExtension::NURBSExtension(const Mesh *patch_topology,
const Array<const NURBSPatch*> p)
const Array<const NURBSPatch*> patches_)
{
// Basic topology checks
MFEM_VERIFY(patches_.Size() > 0, "Must have at least one patch");
MFEM_VERIFY(patches_.Size() == patch_topology->GetNE(),
"Number of patches must equal number of elements in patch_topology");
// Copy patch_topology mesh and NURBSPatch(es)
patchTopo = new Mesh( *patch_topology );
patchTopo->GetEdgeVertexTable();
own_topo = 1;
patches.Reserve(p.Size());
Array<int> edges;
Array<int> oedges;
Array<int> kvs(3);
edge_to_knot.SetSize(patch_topology->GetNEdges());
NumOfKnotVectors = 0;
NumOfElements = 0;
for (int ielem = 0; ielem < patch_topology->GetNE(); ++ielem)
patches.SetSize(patches_.Size());
for (int p = 0; p < patches.Size(); p++)
{
patches.Append(new NURBSPatch(*p[ielem]));
NURBSPatch& patch = *patches[ielem];
int num_patch_elems = 1;
for (int ikv = 0; ikv < patch.GetNKV(); ++ikv)
{
kvs[ikv] = knotVectors.Size();
knotVectors.Append(new KnotVector(*patch.GetKV(ikv)));
num_patch_elems *= patch.GetKV(ikv)->GetNE();
++NumOfKnotVectors;
}
NumOfElements += num_patch_elems;
patch_topology->GetElementEdges(ielem, edges, oedges);
for (int iedge = 0; iedge < edges.Size(); ++iedge)
{
if (iedge < 8)
{
if (iedge & 1)
{
edge_to_knot[edges[iedge]] = kvs[1];
}
else
{
edge_to_knot[edges[iedge]] = kvs[0];
}
}
else
{
edge_to_knot[edges[iedge]] = kvs[2];
}
}
patches[p] = new NURBSPatch(*patches_[p]);
}
GenerateOffsets();
CountBdrElements();
NumOfActiveElems = NumOfElements;
activeElem.SetSize(NumOfElements);
activeElem = true;
Array<int> ukv_to_rpkv;
patchTopo->GetEdgeToUniqueKnotvector(edge_to_ukv, ukv_to_rpkv);
own_topo = true;
CheckPatches(); // This is checking the edge_to_ukv mapping
// Set number of unique (not comprehensive) knot vectors
NumOfKnotVectors = ukv_to_rpkv.Size();
knotVectors.SetSize(NumOfKnotVectors);
knotVectors = NULL;
// Assign the unique knot vectors from patches
for (int i = 0; i < NumOfKnotVectors; i++)
{
// pkv = p*dim + d for an arbitrarily chosen patch p,
// in its reference direction d
const int pkv = ukv_to_rpkv[i];
const int p = pkv / Dimension();
const int d = pkv % Dimension();
knotVectors[i] = new KnotVector(*patches[p]->GetKV(d));
}
CreateComprehensiveKV();
SetOrdersFromKnotVectors();
GenerateOffsets();
CountElements();
CountBdrElements();
NumOfActiveElems = NumOfElements;
activeElem.SetSize(NumOfElements);
activeElem = true;
GenerateActiveVertices();
InitDofMap();
GenerateElementDofTable();
GenerateActiveBdrElems();
GenerateBdrElementDofTable();
weights.SetSize(GetNDof());
CheckPatches();
ConnectBoundaries();
}
NURBSExtension::~NURBSExtension()
@@ -2481,7 +2472,7 @@ void NURBSExtension::Print(std::ostream &os, const std::string &comments) const
}
const int version = kvSpacing.Size() > 0 ? 11 : 10; // v1.0 or v1.1
patchTopo->PrintTopo(os, edge_to_knot, version, comments);
patchTopo->PrintTopo(os, edge_to_ukv, version, comments);
if (patches.Size() == 0)
{
os << "\nknotvectors\n" << NumOfKnotVectors << '\n';
@@ -2936,7 +2927,7 @@ void NURBSExtension::CheckPatches()
for (int i = 0; i < edges.Size(); i++)
{
edges[i] = edge_to_knot[edges[i]];
edges[i] = edge_to_ukv[edges[i]];
if (oedge[i] < 0)
{
edges[i] = -1 - edges[i];
@@ -2954,7 +2945,7 @@ void NURBSExtension::CheckPatches()
edges[8] != edges[11])))
{
mfem::err << "NURBSExtension::CheckPatch (patch = " << p
<< ")\n Inconsistent edge-to-knot mapping!\n";
<< ")\n Inconsistent edge-to-knotvector mapping!";
mfem_error();
}
}
@@ -2971,7 +2962,7 @@ void NURBSExtension::CheckBdrPatches()
for (int i = 0; i < edges.Size(); i++)
{
edges[i] = edge_to_knot[edges[i]];
edges[i] = edge_to_ukv[edges[i]];
if (oedge[i] < 0)
{
edges[i] = -1 - edges[i];
@@ -4878,6 +4869,16 @@ void NURBSExtension::GetElementIJK(int elem, Array<int> & ijk)
el_to_IJK.GetRow(elem, ijk);
}
void NURBSExtension::GetPatches(Array<NURBSPatch*> &patches_copy)
{
const int NP = patches.Size();
patches_copy.SetSize(NP);
for (int p = 0; p < NP; p++)
{
patches_copy[p] = new NURBSPatch(*GetPatch(p));
}
}
void NURBSExtension::SetPatchToElements()
{
const int np = GetNP();
@@ -4982,7 +4983,7 @@ ParNURBSExtension::ParNURBSExtension(MPI_Comm comm, NURBSExtension *parent,
own_topo = true;
parent->own_topo = false;
parent->edge_to_knot.Copy(edge_to_knot);
parent->edge_to_ukv.Copy(edge_to_ukv);
parent->GetOrders().Copy(mOrders);
mOrder = parent->GetOrder();
@@ -5045,7 +5046,7 @@ ParNURBSExtension::ParNURBSExtension(NURBSExtension *parent,
own_topo = parent->own_topo;
parent->own_topo = false;
Swap(edge_to_knot, parent->edge_to_knot);
Swap(edge_to_ukv, parent->edge_to_ukv);
NumOfKnotVectors = parent->NumOfKnotVectors;
Swap(knotVectors, parent->knotVectors);
+17 -6
View File
@@ -469,7 +469,7 @@ protected:
/// Orders of all KnotVectors
Array<int> mOrders;
/// Number of KnotVectors
/// Number of unique (not comprehensive) KnotVectors
int NumOfKnotVectors;
/// Global entity counts
@@ -490,8 +490,8 @@ protected:
/// Whether this object owns patchTopo
bool own_topo;
/// Map from edge indices to KnotVector indices
Array<int> edge_to_knot;
/// Map from patchTopo edge indices to unique KnotVector indices
Array<int> edge_to_ukv;
/// Set of unique KnotVectors
Array<KnotVector *> knotVectors;
@@ -555,7 +555,7 @@ protected:
if the KnotVector index associated with edge @a edge is negative. */
inline const KnotVector *KnotVec(int edge, int oedge, int *okv) const;
/// Throw an error if any patch has an inconsistent edge-to-knot mapping.
/// Throw an error if any patch has an inconsistent edge_to_ukv mapping.
void CheckPatches();
/// Throw an error if any boundary patch has invalid KnotVector orientation.
@@ -673,6 +673,9 @@ protected:
/// Set @a patch_to_bel.
void SetPatchToBdrElements();
/// Return NURBSPatch object; returned object should NOT be deleted.
const NURBSPatch* GetPatch(int patch) const { return patches[patch]; }
/// To be used by ParNURBSExtension constructor(s)
NURBSExtension() : el_dof(nullptr), bel_dof(nullptr) { }
@@ -911,6 +914,14 @@ public:
Cartesian order. */
void GetPatchDofs(const int patch, Array<int> &dofs);
/// Returns a deep copy of the patch topology mesh
Mesh GetPatchTopology() const { return Mesh(*patchTopo); }
/** Returns a deep copy of all instantiated patches. To ensure that patches
are instantiated, use Mesh::GetNURBSPatches() instead. Caller gets
ownership of the returned object, and is responsible for deletion.*/
void GetPatches(Array<NURBSPatch*> &patches);
/// Return the array of indices of all elements in patch @a patch.
const Array<int>& GetPatchElements(int patch);
/// Return the array of indices of all boundary elements in patch @a patch.
@@ -1138,7 +1149,7 @@ inline const real_t &NURBSPatch::operator()(int i, int j, int k, int l) const
inline int NURBSExtension::KnotInd(int edge) const
{
int kv = edge_to_knot[edge];
int kv = edge_to_ukv[edge];
return (kv >= 0) ? kv : (-1-kv);
}
@@ -1155,7 +1166,7 @@ inline const KnotVector *NURBSExtension::KnotVec(int edge) const
inline const KnotVector *NURBSExtension::KnotVec(int edge, int oedge, int *okv)
const
{
int kv = edge_to_knot[edge];
int kv = edge_to_ukv[edge];
if (kv >= 0)
{
*okv = oedge;
+6 -1
View File
@@ -1400,7 +1400,7 @@ ParMesh ParMesh::MakeSimplicial(ParMesh &orig_mesh)
{
vglobal[iv] = fes.GetGlobalTDofNumber(iv);
}
mesh.MakeSimplicial_(orig_mesh, vglobal);
auto parent_elements = mesh.MakeSimplicial_(orig_mesh, vglobal);
// count the number of entries in each row of group_s{vert,edge,face}
mesh.group_svert.MakeI(mesh.GetNGroups()-1); // exclude the local group 0
@@ -1517,6 +1517,11 @@ ParMesh ParMesh::MakeSimplicial(ParMesh &orig_mesh)
mesh.FinalizeParTopo();
if (orig_mesh.GetNodes() != nullptr)
{
mesh.MakeHigherOrderSimplicial_(orig_mesh, parent_elements);
}
return mesh;
}

Some files were not shown because too many files have changed in this diff Show More