feat(mean_field): added initial implementation

note this implementation lacks many tests
This commit is contained in:
2026-07-15 09:44:43 -04:00
commit 9bc4f2758a
49 changed files with 171811 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
.idea/
cmake-build/
build/
._DS_store
._DS_Store
.DSStore
.DS_Store

125
CMakeLists.txt Normal file
View File

@@ -0,0 +1,125 @@
cmake_minimum_required(VERSION 3.28)
project(MeanField CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_compile_options(
-gdwarf-4
-Wno-unused-parameter
-Wno-unused-function
-Wno-unused-variable
-Wno-unused-const-variable
-Wno-unused-private-field
-Wno-unused-but-set-variable
-Wno-unused-local-typedefs
-Wno-unused-value
-Wno-unused-label
-Wno-unused-lambda-capture
)
find_package(MPI REQUIRED COMPONENTS CXX)
find_package(XAD REQUIRED)
find_package(mfem REQUIRED)
find_package(UMFPACK REQUIRED)
find_package(hypre REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(stroid REQUIRED IMPORTED_TARGET stroid)
add_library(mean_field)
target_include_directories(mean_field
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/libmeanfield/include>
)
target_sources(mean_field
PRIVATE
libmeanfield/impl/analysis/integral.cpp
libmeanfield/impl/fem.cpp
libmeanfield/impl/mapping/coefficients.cpp
libmeanfield/impl/mapping/domain_mapper.cpp
libmeanfield/impl/physics/gravity.cpp
libmeanfield/impl/physics/solid.cpp
libmeanfield/impl/utils/domain.cpp
libmeanfield/impl/utils/misc.cpp
libmeanfield/impl/integrators/advection.cpp
libmeanfield/impl/integrators/centrifugal.cpp
libmeanfield/impl/integrators/coriolis.cpp
libmeanfield/impl/integrators/gravity.cpp
libmeanfield/impl/integrators/mass_continuity.cpp
libmeanfield/impl/integrators/viscosity.cpp
)
target_sources(mean_field
PUBLIC
FILE_SET CXX_MODULES FILES
libmeanfield/interface/mean_field.cppm
libmeanfield/interface/fem.cppm
libmeanfield/interface/analysis/integral.cppm
libmeanfield/interface/boundary/context.cppm
libmeanfield/interface/mapping/coefficients.cppm
libmeanfield/interface/mapping/domain_mapper.cppm
libmeanfield/interface/mapping/types.cppm
libmeanfield/interface/physics/context.cppm
libmeanfield/interface/physics/gravity.cppm
libmeanfield/interface/physics/solid.cppm
libmeanfield/interface/utils/domain.cppm
libmeanfield/interface/utils/misc.cppm
libmeanfield/interface/utils/user.cppm
libmeanfield/interface/integrators/advection.cppm
libmeanfield/interface/integrators/centrifugal.cppm
libmeanfield/interface/integrators/coriolis.cppm
libmeanfield/interface/integrators/gravity.cppm
libmeanfield/interface/integrators/mass_continuity.cppm
libmeanfield/interface/integrators/pressure_gradient.cppm
libmeanfield/interface/integrators/viscosity.cppm
libmeanfield/interface/quadrature/policy.cppm
libmeanfield/interface/quadrature/mfem.cppm
)
target_link_libraries(mean_field
PUBLIC
MPI::MPI_CXX
XAD::xad
mfem
PkgConfig::stroid
)
add_library(test_mod)
target_sources(test_mod
PUBLIC
FILE_SET CXX_MODULES FILES
tests/test_helpers.cppm
)
target_link_libraries(test_mod
PUBLIC
mean_field
)
find_package(Catch2 3 REQUIRED)
cmake_policy(SET CMP0167 NEW)
find_package(Boost REQUIRED)
pkg_check_modules(fourdst_config REQUIRED IMPORTED_TARGET fourdst_config)
add_executable(tests
tests/test_main.cpp
tests/physics/gravity.cpp
tests/geometry/volume.cpp
tests/quadrature/policy.cpp
)
target_link_libraries(tests PRIVATE mean_field test_mod Catch2::Catch2 Boost::boost)
include (CTest)
include (Catch)
catch_discover_tests(tests)

674
LICENSE.txt Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

13
generate_mesh.py Normal file
View File

@@ -0,0 +1,13 @@
from stroid.config import MeshConfig
from stroid.IO import SaveStroidMesh
from stroid import GenerateMesh
cfg = MeshConfig()
cfg.order = 4
cfg.refinement_levels = 2
print(cfg)
mesh = GenerateMesh(cfg)
SaveStroidMesh(mesh, "sandbox.smesh")
print(mesh)

View File

@@ -0,0 +1,182 @@
module;
#include <mfem.hpp>
module mean_field;
import :mapping.coefficients;
namespace mean_field::analysis {
double domain_integrate_grid_function(const fem::FEM &fem, const mfem::GridFunction &gf, utils::DOMAINS domain, mapping::COORDINATE_SPACE coord_space) {
mfem::LinearForm lf(fem.H1_fes.get());
mfem::GridFunctionCoefficient gf_c(&gf);
double local_integral;
mfem::Array<int> elem_markers;
populate_element_mask(fem.mesh.get(), domain, elem_markers);
if (fem.has_mapping() && coord_space == mapping::COORDINATE_SPACE::PHYSICAL) {
mapping::MappedScalarCoefficient mapped_gf_c(*fem.mapping, gf_c);
// ReSharper disable once CppDFAMemoryLeak // Disabled because MFEM takes ownership so memory is not leaked
auto *lf_integrator = new mfem::DomainLFIntegrator(mapped_gf_c);
lf_integrator->SetIntRule(fem.int_rule.get());
lf.AddDomainIntegrator(lf_integrator, elem_markers);
lf.Assemble();
local_integral = lf.Sum();
} else {
if (coord_space == mapping::COORDINATE_SPACE::PHYSICAL) {
MFEM_ABORT(
"Physical evaluation mode requested but no mapping provided. Check domain bounds and mapping setup.");
}
lf.AddDomainIntegrator(new mfem::DomainLFIntegrator(gf_c), elem_markers);
lf.Assemble();
local_integral = lf.Sum();
}
double global_integral = 0.0;
MPI_Allreduce(&local_integral, &global_integral, 1, MPI_DOUBLE, MPI_SUM, fem.H1_fes->GetComm());
return global_integral;
}
mfem::Vector get_com(const fem::FEM &fem, const mfem::GridFunction &rho) {
const int dim = fem.mesh->Dimension();
mfem::Vector local_com(dim);
local_com = 0.0;
double local_mass = 0.0;
for (int i = 0; i < fem.H1_fes->GetNE(); ++i) {
if (fem.mesh->GetAttribute(i) == 3) continue;
mfem::ElementTransformation *trans = fem.H1_fes->GetElementTransformation(i);
const mfem::IntegrationRule &ir = *fem.int_rule;
for (int j = 0; j < ir.GetNPoints(); ++j) {
const mfem::IntegrationPoint &ip = ir.IntPoint(j);
trans->SetIntPoint(&ip);
double weight = trans->Weight() * ip.weight;
if (fem.has_mapping()) {
weight *= fem.mapping->ComputeDetJ(*trans, ip);
}
double rho_val = rho.GetValue(i, ip);
mfem::Vector phys_point(dim);
if (fem.has_mapping()) {
fem.mapping->GetPhysicalPoint(*trans, ip, phys_point);
} else {
trans->Transform(ip, phys_point);
}
const double mass_term = rho_val * weight;
local_mass += mass_term;
for (int d = 0; d < dim; ++d) {
local_com(d) += phys_point(d) * mass_term;
}
}
}
double global_mass = 0.0;
mfem::Vector global_com(dim);
MPI_Comm comm = fem.H1_fes->GetComm();
MPI_Allreduce(&local_mass, &global_mass, 1, MPI_DOUBLE, MPI_SUM, comm);
MPI_Allreduce(local_com.GetData(), global_com.GetData(), dim, MPI_DOUBLE, MPI_SUM, comm);
if (global_mass > 1e-18) {
global_com /= global_mass;
} else {
global_com = 0.0;
}
return global_com;
}
void conserve_mass(const fem::FEM &fem, mfem::GridFunction &rho, const double target_mass) {
if (const double current_mass = domain_integrate_grid_function(fem, rho, utils::DOMAINS::STELLAR); current_mass > 1e-15)
rho *= (target_mass / current_mass);
}
double get_moment_of_inertia(const fem::FEM &fem, const mfem::GridFunction &rho) {
auto s2_func = [](const mfem::Vector &x) {
return std::pow(x(0), 2) + std::pow(x(1), 2);
};
std::unique_ptr<mfem::Coefficient> s2_coeff;
if (fem.has_mapping()) {
s2_coeff = std::make_unique<mapping::PhysicalPositionFunctionCoefficient>(*fem.mapping, s2_func);
} else {
s2_coeff = std::make_unique<mfem::FunctionCoefficient>(s2_func);
}
mfem::GridFunctionCoefficient rho_coeff(&rho);
mfem::ProductCoefficient I_integrand(rho_coeff, *s2_coeff);
mfem::LinearForm I_lf(fem.H1_fes.get());
double I = 0.0;
// TODO: Need to filter here to just the stellar domain and also update the IntRule
if (fem.has_mapping()) {
mapping::MappedScalarCoefficient mapped_integrand(*fem.mapping, I_integrand);
I_lf.AddDomainIntegrator(new mfem::DomainLFIntegrator(mapped_integrand));
I_lf.Assemble();
I = I_lf.Sum();
} else {
I_lf.AddDomainIntegrator(new mfem::DomainLFIntegrator(I_integrand));
I_lf.Assemble();
I = I_lf.Sum();
}
return I;
}
double get_mesh_volume(
const fem::FEM& fem,
const mapping::COORDINATE_SPACE coordinate_space,
const utils::DOMAINS domain
) {
mfem::ParMesh &mesh = *fem.mesh;
const mapping::DomainMapper &map = *fem.mapping;
const mfem::IntegrationRule &ir = *fem.int_rule;
const bool physical =
(coordinate_space == mapping::COORDINATE_SPACE::PHYSICAL);
double local_volume = 0.0;
for (int e = 0; e < mesh.GetNE(); ++e) {
const int attr = mesh.GetAttribute(e);
switch (domain) {
case utils::DOMAINS::ALL:
break;
case utils::DOMAINS::STELLAR:
if (attr == 3) continue;
break;
case utils::DOMAINS::VACUUM:
if (attr != 3) continue;
break;
default:
MFEM_ABORT("Unsupported domain type for volume computation.");
}
mfem::ElementTransformation *T = mesh.GetElementTransformation(e);
for (int q = 0; q < ir.GetNPoints(); ++q) {
const mfem::IntegrationPoint &ip = ir.IntPoint(q);
T->SetIntPoint(&ip);
double dV = ip.weight * T->Weight();
if (physical) {
dV *= std::fabs(map.ComputeDetJ(*T, ip));
}
local_volume += dV;
}
}
double global_volume = 0.0;
MPI_Allreduce(&local_volume, &global_volume, 1, MPI_DOUBLE, MPI_SUM,
mesh.GetComm());
return global_volume;
}
}

190
libmeanfield/impl/fem.cpp Normal file
View File

@@ -0,0 +1,190 @@
module;
#include <string>
#include <memory>
#include <mfem.hpp>
#include <stroid/stroid.h>
module mean_field;
import :boundary.contexts;
import :mapping.coefficients;
import :utils.misc;
import :utils.user;
namespace mean_field::fem {
FEM setup_fem(const std::string &filename, const utils::Args &args, const int extra_refine) {
FEM fem;
//==================================================================
// Section 1: Mesh and FE Space Setup
//==================================================================
fem.smesh = stroid::IO::LoadStroidMesh(filename).value();
if (extra_refine > 0) {
stroid::refinement::UniformRefinement(fem.smesh, extra_refine);
}
fem.mesh = std::make_unique<mfem::ParMesh>(MPI_COMM_WORLD, *fem.smesh.mesh);
fem.mesh->EnsureNodes();
const int geom_order = utils::get_mesh_order(*fem.mesh);
const int dim = fem.mesh->Dimension();
const int v_order = 2;
const int rho_order = 2;
const int p = rho_order ;
const int cb_type = mfem::BasisType::GaussLobatto;
const int ob_type = mfem::BasisType::IntegratedGLL;
fem.RT_fec = std::make_unique<mfem::RT_FECollection>(p, dim, cb_type, ob_type);
fem.RT_fes = std::make_unique<mfem::ParFiniteElementSpace>(fem.mesh.get(), fem.RT_fec.get());
fem.H1_fec = std::make_unique<mfem::H1_FECollection>(v_order, dim);
fem.L2_fec = std::make_unique<mfem::L2_FECollection>(rho_order, dim);
// Gravity (Scalar H1) and Velocity (Vector H1)
fem.H1_fes = std::make_unique<mfem::ParFiniteElementSpace>(fem.mesh.get(), fem.H1_fec.get());
fem.Vec_H1_fes = std::make_unique<mfem::ParFiniteElementSpace>(fem.mesh.get(), fem.H1_fec.get(), dim,
mfem::Ordering::byNODES);
// Density & Pressure (Scalar Discontinuous L2)
fem.L2_fes = std::make_unique<mfem::ParFiniteElementSpace>(fem.mesh.get(), fem.L2_fec.get());
//==================================================================
// Section 2: Domain Mapping
//==================================================================
auto [r_star_ref, r_inf_ref] = utils::discover_bounds(fem.mesh.get(), 3)
.or_else([](const boundary::BoundsError &err)-> std::expected<boundary::Bounds, boundary::BoundsError> {
throw std::runtime_error("Unable to determine vacuum domain reference boundary...");
}).value();
fem.mapping = std::make_unique<mapping::DomainMapper>(r_star_ref, r_inf_ref);
//==================================================================
// Section 3: Multi-physics Block-offsets
//==================================================================
fem.block_true_offsets.SetSize(3);
fem.block_true_offsets[0] = 0;
fem.block_true_offsets[1] = fem.Vec_H1_fes->GetTrueVSize();
fem.block_true_offsets[2] = fem.block_true_offsets[1] + fem.L2_fes->GetTrueVSize();
fem.gravity_block_true_offsets.SetSize(3);
fem.gravity_block_true_offsets[0] = 0;
fem.gravity_block_true_offsets[1] = fem.RT_fes->GetTrueVSize();
fem.gravity_block_true_offsets[2] = fem.gravity_block_true_offsets[1] + fem.L2_fes->GetTrueVSize();
//==================================================================
// Section 4: Multipole BC setup.
//==================================================================
fem.com.SetSize(dim);
fem.com = 0.0;
fem.Q.SetSize(dim, dim);
fem.Q = 0.0;
//==================================================================
// Section 5: Integration Rules
//==================================================================
MFEM_ASSERT(fem.mesh->GetElementGeometry(0) == mfem::Geometry::CUBE,
"Currently only hexahedral meshes are supported");
const int element_order = fem.H1_fes->GetMaxElementOrder();
fem.int_order = 2 * element_order + geom_order - 2 + args.quad_boost;
fem.int_rule = std::make_unique<mfem::IntegrationRule>(mfem::IntRules.Get(mfem::Geometry::CUBE, fem.int_order));
//==================================================================
// Section 6: Essential Boundaries & Domain Masks
//==================================================================
fem.ess_v_tdofs.SetSize(0);
populate_element_mask(fem.mesh.get(), utils::DOMAINS::STELLAR, fem.gravity_context.stellar_mask);
const int n_bdr_attrs = fem.mesh->bdr_attributes.Max();
fem.boundary_context.inf_bounds.SetSize(n_bdr_attrs);
fem.boundary_context.stellar_bounds.SetSize(n_bdr_attrs);
fem.boundary_context.inf_bounds = 0;
fem.boundary_context.stellar_bounds = 0;
fem.boundary_context.inf_bounds[static_cast<int>(boundary::Boundaries::INF_SURFACE) - 1] = 1;
fem.boundary_context.stellar_bounds[static_cast<int>(boundary::Boundaries::STELLAR_SURFACE) - 1] = 1;
//==================================================================
// Section 7: Gravity Context Setup
//==================================================================
fem.gravity_context.minres = std::make_unique<mfem::MINRESSolver>(fem.mesh->GetComm());
fem.gravity_context.minres->SetRelTol(1e-12);
fem.gravity_context.minres->SetAbsTol(1e-12);
fem.gravity_context.minres->SetMaxIter(1000);
fem.gravity_context.minres->SetPrintLevel(0);
fem.gravity_context.prec_Phi = std::make_unique<mfem::HypreBoomerAMG>();
fem.gravity_context.prec_Phi->SetPrintLevel(0);
fem.gravity_context.block_prec = std::make_unique<mfem::BlockDiagonalPreconditioner>(fem.gravity_block_true_offsets);
fem.gravity_context.minres->SetPreconditioner(*fem.gravity_context.block_prec);
//=========================================================
// Section 10: Set All vacuum elements true degrees of freedom
//=========================================================
{
mfem::Array<int> vacuum_mask;
utils::populate_element_mask(fem.mesh.get(), utils::DOMAINS::VACUUM, vacuum_mask);
utils::populate_domain_tdofs(fem.Vec_H1_fes.get(), vacuum_mask, fem.vacuum_tdof_v);
utils::populate_domain_tdofs(fem.L2_fes.get(), vacuum_mask, fem.vacuum_tdof_rho);
}
const quadrature::QuadratureOptions& quadrature_options = args.quadrature;
if (quadrature_options.validation.reject_negative_boosts && quadrature_options.global_boost < 0) {
throw std::invalid_argument("Global quadrature boost cannot be negative.");
}
quadrature::RuleSet quadrature_rule_set = quadrature::make_rule_set(quadrature_options.mode, quadrature_options.global_boost);
if (quadrature_options.fallback_fixed_order.has_value()) {
if (*quadrature_options.fallback_fixed_order < 0) {
throw std::invalid_argument("Fallback quadrature order cannot be negative.");
}
quadrature_rule_set.fallback.fixed_order = quadrature_options.fallback_fixed_order;
}
auto apply_quadrature_options = [&quadrature_options](quadrature::RuleControl& rule_control, const quadrature::QuadratureTermOptions& term_options) {
if (term_options.fixed_order.has_value() && *term_options.fixed_order < 0) {
throw std::invalid_argument("Fixed quadrature order cannot be negative.");
}
if (quadrature_options.validation.reject_negative_boosts && term_options.additional_boost < 0) {
throw std::invalid_argument("Term quadrature boost cannot be negative.");
}
rule_control.boost += term_options.additional_boost;
if (term_options.fixed_order.has_value()) {
rule_control.fixed_order = term_options.fixed_order;
}
};
apply_quadrature_options(quadrature_rule_set.gravity_hdiv_mass, quadrature_options.gravity_hdiv_mass);
apply_quadrature_options(quadrature_rule_set.gravity_divergence, quadrature_options.gravity_divergence);
apply_quadrature_options(quadrature_rule_set.gravity_source, quadrature_options.gravity_source);
apply_quadrature_options(quadrature_rule_set.gravity_boundary, quadrature_options.gravity_boundary);
apply_quadrature_options(quadrature_rule_set.density_projection, quadrature_options.density_projection);
apply_quadrature_options(quadrature_rule_set.mass_conservation, quadrature_options.mass_conservation);
apply_quadrature_options(quadrature_rule_set.center_of_mass, quadrature_options.center_of_mass);
apply_quadrature_options(quadrature_rule_set.quadrupole, quadrature_options.quadrupole);
apply_quadrature_options(quadrature_rule_set.gravitational_energy, quadrature_options.gravitational_energy);
apply_quadrature_options(quadrature_rule_set.virial, quadrature_options.virial);
apply_quadrature_options(quadrature_rule_set.error_norm, quadrature_options.error_norm);
apply_quadrature_options(quadrature_rule_set.roles.discretization, quadrature_options.roles.discretization);
apply_quadrature_options(quadrature_rule_set.roles.preconditioner, quadrature_options.roles.preconditioner);
apply_quadrature_options(quadrature_rule_set.roles.diagnostic, quadrature_options.roles.diagnostic);
apply_quadrature_options(quadrature_rule_set.roles.projection, quadrature_options.roles.projection);
fem.quadrature_factory = std::make_unique<quadrature::RuleFactory>(quadrature::Policy(std::move(quadrature_rule_set)));
return fem;
}
}

View File

@@ -0,0 +1,206 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
AdvectionIntegrator::AdvectionIntegrator(const mapping::DomainMapper &map) : m_map(map) {}
void AdvectionIntegrator::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement *fe_v = el[0];
const mfem::FiniteElement *fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector &v_dofs = *elfun[0];
const mfem::Vector &rho_dofs = *elfun[1];
mfem::Vector &r_v = *elvec[0];
r_v.SetSize(dof_v * dim);
r_v = 0.0;
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
const mfem::IntegrationRule *ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder() + 1);
for (int q = 0; q < ir->GetNPoints(); q++) {
const mfem::IntegrationPoint &ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
mfem::Vector v_val(dim);
v_val = 0.0;
mfem::DenseMatrix grad_v(dim, dim);
grad_v = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
const double v_ic = v_dofs(i + c * dof_v);
v_val(c) += v_ic * shape_v(i);
for (int d = 0; d < dim; ++d) {
grad_v(c, d) += v_ic * dshape_v_phys(i, d);
}
}
}
mfem::Vector adv_val(dim);
adv_val = 0.0;
for (int c = 0; c < dim; ++c) {
for (int d = 0; d < dim; ++d) {
adv_val(c) += v_val(d) * grad_v(c, d);
}
}
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
r_v(i + c * dof_v) += shape_v(i) * rho_val * adv_val(c) * weight;
}
}
}
}
void AdvectionIntegrator::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement *fe_v = el[0];
const mfem::FiniteElement *fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector &v_dofs = *elfun[0];
const mfem::Vector &rho_dofs = *elfun[1];
mfem::DenseMatrix *dv_dv = elmats(0, 0);
mfem::DenseMatrix *dv_drho = elmats(0, 1);
if (dv_dv) *dv_dv = 0.0;
if (dv_drho) *dv_drho = 0.0;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
const mfem::IntegrationRule *ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder() + 1);
for (int q = 0; q < ir->GetNPoints(); q++) {
const mfem::IntegrationPoint &ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
mfem::Vector v_val(dim);
v_val = 0.0;
mfem::DenseMatrix grad_v(dim, dim);
grad_v = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
double v_ic = v_dofs(i + c * dof_v);
v_val(c) += v_ic * shape_v(i);
for (int d = 0; d < dim; ++d) {
grad_v(c, d) += v_ic * dshape_v_phys(i, d);
}
}
}
mfem::Vector adv_val(dim);
adv_val = 0.0;
for (int c = 0; c < dim; ++c) {
for (int d = 0; d < dim; ++d) {
adv_val(c) += v_val(d) * grad_v(c, d);
}
}
// Jacobian wrt. Velocity: dR_v/dv
if (dv_dv) {
for (int i = 0; i < dof_v; ++i) {
// Test function index
for (int c = 0; c < dim; ++c) {
// Test function component
int row = i + c * dof_v;
for (int j = 0; j < dof_v; ++j) {
// Trial function index
double v_dot_grad_phi_j = 0.0;
for (int k = 0; k < dim; ++k) {
v_dot_grad_phi_j += v_val(k) * dshape_v_phys(j, k);
}
for (int d = 0; d < dim; ++d) {
// Trial function component
int col = j + d * dof_v;
// \rho (\delta \vec{v} \cdot \nabla \vec{v})
// \delta v is along direction 'd' for the cth component of advection
double termA = shape_v(j) * grad_v(c, d);
// \rho(\vec{v} \cdot \nabla \delta \vec{v})
// Only non-zero when the advected component matches the test component
double termB = (c == d) ? v_dot_grad_phi_j : 0.0;
(*dv_dv)(row, col) += shape_v(i) * rho_val * (termA + termB) * weight;
}
}
}
}
}
// Jacobian wrt. Density: dR_v / drho
if (dv_drho) {
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
int row = i + c * dof_v;
for (int j = 0; j < dof_rho; ++j) {
int col = j;
// \delta \rho * (\vec{v} \cdot \nabla \vec{v})
double term = shape_rho(j) * adv_val(c);
(*dv_drho)(row, col) += shape_v(i) * term * weight;
}
}
}
}
}
}
}

View File

@@ -0,0 +1,146 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
CentrifugalForceIntegrator::CentrifugalForceIntegrator(
const mapping::DomainMapper& map,
const mfem::Vector& omega
) : m_map(map), m_omega(3) {
MFEM_ASSERT(omega.Size() == 3, "Omega vector must be 3D");
m_omega = omega;
}
void CentrifugalForceIntegrator::SetOmega(const mfem::Vector& omega) {
MFEM_ASSERT(omega.Size() == 3, "Omega vector must be 3D");
m_omega = omega;
}
void CentrifugalForceIntegrator::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& rho_dofs = *elfun[1];
mfem::Vector& r_v = *elvec[0];
r_v = 0.0;
r_v.SetSize(dof_v * dim);
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::Vector x_phys(dim);
mfem::Vector a(dim), b(dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
m_map.GetPhysicalPoint(Tr, ip, x_phys);
// ω x r
a(0) = m_omega(1) * x_phys(2) - m_omega(2) * x_phys(1);
a(1) = m_omega(2) * x_phys(0) - m_omega(0) * x_phys(2);
a(2) = m_omega(0) * x_phys(1) - m_omega(1) * x_phys(0);
// ω x (ω x r) [centrifugal acceleration]
b(0) = m_omega(1) * a(2) - m_omega(2) * a(1);
b(1) = m_omega(2) * a(0) - m_omega(0) * a(2);
b(2) = m_omega(0) * a(1) - m_omega(1) * a(0);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
r_v(i + c * dof_v) += shape_v(i) * rho_val * b(c) * weight;
}
}
}
}
void CentrifugalForceIntegrator::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
mfem::DenseMatrix* dv_dv = elmats(0,0);
mfem::DenseMatrix* dv_drho = elmats(0,1);
if (dv_dv) *dv_dv = 0.0;
if (elmats(1, 0)) *elmats(1, 0) = 0.0;
if (elmats(1, 1)) *elmats(1, 1) = 0.0;
if (dv_drho) *dv_drho = 0.0;
if (!dv_drho) return;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::Vector x_phys(dim);
mfem::Vector a(dim), b(dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
m_map.GetPhysicalPoint(Tr, ip, x_phys);
// ω x r
a(0) = m_omega(1) * x_phys(2) - m_omega(2) * x_phys(1);
a(1) = m_omega(2) * x_phys(0) - m_omega(0) * x_phys(2);
a(2) = m_omega(0) * x_phys(1) - m_omega(1) * x_phys(0);
// ω x (ω x r) [centrifugal acceleration]
b(0) = m_omega(1) * a(2) - m_omega(2) * a(1);
b(1) = m_omega(2) * a(0) - m_omega(0) * a(2);
b(2) = m_omega(0) * a(1) - m_omega(1) * a(0);
// dR_dv_i_c / drho_j = φ_i * φ_j * b_c
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
const int row = i + c * dof_v;
for (int j = 0; j < dof_rho; ++j) {
(*dv_drho)(row, j) += shape_v(i) * shape_rho(j) * b(c) * weight;
}
}
}
}
}
}

View File

@@ -0,0 +1,152 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
CoriolisIntegrator::CoriolisIntegrator(const mapping::DomainMapper& map, const mfem::Vector& omega)
: m_map(map), m_omega(omega) {
m_omega_mat.SetSize(3, 3);
m_omega_mat = 0.0;
m_omega_mat(0, 1) = -m_omega(2);
m_omega_mat(0, 2) = m_omega(1);
m_omega_mat(1, 0) = m_omega(2);
m_omega_mat(1, 2) = -m_omega(0);
m_omega_mat(2, 0) = -m_omega(1);
m_omega_mat(2, 1) = m_omega(0);
}
void CoriolisIntegrator::AssembleElementVector(const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& v_dofs = *elfun[0];
const mfem::Vector& rho_dofs = *elfun[1];
mfem::Vector& r_v = *elvec[0];
r_v.SetSize(dof_v * dim);
r_v = 0.0;
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) rho_val += rho_dofs(i) * shape_rho(i);
mfem::Vector v_val(dim); v_val = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) v_val(c) += v_dofs(i + c * dof_v) * shape_v(i);
}
mfem::Vector F_coriolis(dim);
m_omega_mat.Mult(v_val, F_coriolis);
F_coriolis *= 2.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
r_v(i + c * dof_v) += shape_v(i) * rho_val * F_coriolis(c) * weight;
}
}
}
}
void CoriolisIntegrator::AssembleElementGrad(const mfem::Array<const mfem::FiniteElement*> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& v_dofs = *elfun[0];
const mfem::Vector& rho_dofs = *elfun[1];
mfem::DenseMatrix* dv_dv = elmats(0, 0);
mfem::DenseMatrix* dv_drho = elmats(0, 1);
if (dv_dv) *dv_dv = 0.0;
if (dv_drho) *dv_drho = 0.0;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) rho_val += rho_dofs(i) * shape_rho(i);
mfem::Vector v_val(dim); v_val = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) v_val(c) += v_dofs(i + c * dof_v) * shape_v(i);
}
mfem::Vector F_coriolis(dim);
m_omega_mat.Mult(v_val, F_coriolis);
F_coriolis *= 2.0;
if (dv_dv) {
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
int row = i + c * dof_v;
for (int j = 0; j < dof_v; ++j) {
for (int d = 0; d < dim; ++d) {
int col = j + d * dof_v;
double coupling = m_omega_mat(c, d);
(*dv_dv)(row, col) += shape_v(i) * shape_v(j) * 2.0 * rho_val * coupling * weight;
}
}
}
}
}
if (dv_drho) {
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
int row = i + c * dof_v;
for (int j = 0; j < dof_rho; ++j) {
int col = j;
(*dv_drho)(row, col) += shape_v(i) * shape_rho(j) * F_coriolis(c) * weight;
}
}
}
}
}
}
}

View File

@@ -0,0 +1,124 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
GravityForceIntegrator::GravityForceIntegrator(
const mapping::DomainMapper& map,
const mfem::GridFunction& phi
): m_map(map), m_phi(&phi) {}
void GravityForceIntegrator::SetPotential(const mfem::GridFunction& phi) { m_phi = &phi; };
void GravityForceIntegrator::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& rho_dofs = *elfun[1];
mfem::Vector& r_v = *elvec[0];
r_v.SetSize(dof_v * dim);
r_v = 0.0;
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::Vector grad_phi_ref(dim), grad_phi_phys(dim), grad_phi_elem(dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
m_phi->GetGradient(Tr, grad_phi_elem);
mfem::DenseMatrix J_map(dim, dim), J_map_inv(dim, dim);
m_map.ComputeJacobian(Tr, J_map);
mfem::CalcInverse(J_map, J_map_inv);
J_map_inv.MultTranspose(grad_phi_elem, grad_phi_phys);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
r_v(i + c * dof_v) += shape_v(i) * rho_val * grad_phi_phys(c) * weight;
}
}
}
}
void GravityForceIntegrator::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
mfem::DenseMatrix* dv_dv = elmats(0, 0);
mfem::DenseMatrix* dv_drho = elmats(0, 1);
if (dv_dv) *dv_dv = 0.0;
if (dv_drho) *dv_drho = 0.0;
if (!dv_drho) return;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::Vector grad_phi_ref(dim), grad_phi_phys(dim), grad_phi_elem(dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
m_phi->GetGradient(Tr, grad_phi_elem);
mfem::DenseMatrix J_map(dim, dim), J_map_inv(dim, dim);
m_map.ComputeJacobian(Tr, J_map);
mfem::CalcInverse(J_map, J_map_inv);
J_map_inv.MultTranspose(grad_phi_elem, grad_phi_phys);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
const int row = i + c * dof_v;
for (int j = 0; j < dof_rho; ++j) {
(*dv_drho)(row, j) += shape_v(i) * shape_rho(j) * grad_phi_phys(c) * weight;
}
}
}
}
}
}

View File

@@ -0,0 +1,417 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
ContinuityVolumeIntegrator::ContinuityVolumeIntegrator(const mapping::DomainMapper& map) : m_map(map) {};
void ContinuityVolumeIntegrator::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement *fe_v = el[0];
const mfem::FiniteElement *fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector v_dofs = *elfun[0];
const mfem::Vector rho_dofs = *elfun[1];
void* data_rho_before = elvec[1] ? (void*)elvec[1]->GetData() : nullptr;
int size_rho_before = elvec[1] ? elvec[1]->Size() : -1;
if (elvec[0]) {
elvec[0]->SetSize(dof_v * dim);
*elvec[0] = 0.0;
}
mfem::Vector& r_rho = *elvec[1];
r_rho.SetSize(dof_rho);
r_rho = 0.0;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::DenseMatrix dshape_rho_ref(dof_rho, dim), dshape_rho_phys(dof_rho, dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
fe_rho->CalcDShape(ip, dshape_rho_ref);
mfem::Mult(dshape_rho_ref, J_inv, dshape_rho_phys);
mfem::Vector v_val(dim); v_val = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
const int row = i + c * dof_v;
v_val(c) += v_dofs(row) * shape_v(i);
}
}
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
for (int i = 0; i < dof_rho; ++i) {
double grad_dot_rhov = 0.0;
for (int c = 0; c < dim; ++c) {
grad_dot_rhov += dshape_rho_phys(i, c) * rho_val * v_val(c);
}
r_rho(i) -= grad_dot_rhov * weight;
}
}
}
void ContinuityVolumeIntegrator::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement *fe_v = el[0];
const mfem::FiniteElement *fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& v_dofs = *elfun[0];
const mfem::Vector& rho_dofs = *elfun[1];
mfem::DenseMatrix* drho_dv = elmats(1, 0);
mfem::DenseMatrix* drho_drho = elmats(1, 1);
if (elmats(0, 0)) *elmats(0, 0) = 0.0;
if (elmats(0, 1)) *elmats(0, 1) = 0.0;
if (drho_dv) *drho_dv = 0.0;
if (drho_drho) *drho_drho = 0.0;
mfem::Vector shape_v(dof_v), shape_rho(dof_rho);
mfem::DenseMatrix dshape_rho_ref(dof_rho, dim), dshape_rho_phys(dof_rho, dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcShape(ip, shape_v);
fe_rho->CalcShape(ip, shape_rho);
fe_rho->CalcDShape(ip, dshape_rho_ref);
mfem::Mult(dshape_rho_ref, J_inv, dshape_rho_phys);
mfem::Vector v_val(dim); v_val = 0.0;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
const int row = i + c * dof_v;
v_val(c) += v_dofs(row) * shape_v(i);
}
}
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) {
rho_val += rho_dofs(i) * shape_rho(i);
}
if (drho_dv) {
for (int i = 0; i < dof_rho; ++i) {
for (int j = 0; j < dof_v; ++j) {
for (int d = 0; d < dim; ++d) {
const int col = j + d * dof_v;
(*drho_dv)(i, col) -= dshape_rho_phys(i, d) * rho_val * shape_v(j) * weight;
}
}
}
}
if (drho_drho) {
for (int i = 0; i < dof_rho; ++i) {
double grad_psi_dot_v = 0.0;
for (int c = 0; c < dim; ++c) {
grad_psi_dot_v += dshape_rho_phys(i, c) * v_val(c);
}
for (int j = 0; j < dof_rho; ++j) {
(*drho_drho)(i, j) -= grad_psi_dot_v * shape_rho(j) * weight;
}
}
}
}
}
ContinuityFaceIntegrator::ContinuityFaceIntegrator(const mapping::DomainMapper& map): m_map(map) {}
void ContinuityFaceIntegrator::AssembleFaceVector(
const mfem::Array<const mfem::FiniteElement *> &el1,
const mfem::Array<const mfem::FiniteElement *> &el2,
mfem::FaceElementTransformations &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvect
) {
const mfem::FiniteElement *fe_v_minus = el1[0];
const mfem::FiniteElement *fe_v_plus = el2[0];
const mfem::FiniteElement *fe_rho_minus = el1[1];
const mfem::FiniteElement *fe_rho_plus = el2[1];
const int dof_v_minus = fe_v_minus->GetDof();
const int dof_v_plus = fe_v_plus->GetDof();
const int dof_rho_minus = fe_rho_minus->GetDof();
const int dof_rho_plus = fe_rho_plus->GetDof();
const int dim = Tr.GetSpaceDim();
if (elvect[0]) {
elvect[0]->SetSize(dim * dof_v_minus + dim * dof_v_plus);
*elvect[0] = 0.0;
}
mfem::Vector &r_rho = *elvect[1];
r_rho.SetSize(dof_rho_minus + dof_rho_plus);
r_rho = 0.0;
const int attr_minus = Tr.Elem1->Attribute;
const int attr_plus = (Tr.Elem2 != nullptr) ? Tr.Elem2->Attribute : -1;
constexpr int VACUUM_ATTR = 3;
if (attr_minus == VACUUM_ATTR || attr_plus == VACUUM_ATTR) {
return; // No flux contribution for vacuum faces
}
if (Tr.Elem2 == nullptr) {
return; // Boundary face,
}
const mfem::Vector &v_dofs = *elfun[0]; // Size: dim * dof_v_minus + dim*dof_v_plus
const mfem::Vector &rho_dofs = *elfun[1]; // Size: dof_rho_minus + dof_rho_plus
// Helpers to auto offset to the correct point in the dof array
auto rho_minus_dof = [&](const int i) {return rho_dofs(i);};
auto rho_plus_dof = [&](const int i) {return rho_dofs(i + dof_rho_minus);};
auto v_minus_dof = [&](const int k, const int c) {return v_dofs(k + c * dof_v_minus);};
const int p_v = fe_v_minus->GetOrder();
const int p_rho = fe_rho_minus->GetOrder();
const int int_order = 2 * std::max(p_v, p_rho) + 1;
const mfem::IntegrationRule *ir = &mfem::IntRules.Get(Tr.GetGeometryType(), int_order);
mfem::Vector shape_v_minus(dof_v_minus), shape_rho_minus(dof_rho_minus), shape_rho_plus(dof_rho_plus);
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& face_ip = ir->IntPoint(q);
Tr.SetAllIntPoints(&face_ip);
const mfem::IntegrationPoint &ip_minus = Tr.GetElement1IntPoint();
const mfem::IntegrationPoint &ip_plus = Tr.GetElement2IntPoint();
auto [n_unit, ds, v_dot_n_scale] = m_map.GetFaceQuadratureContext(Tr, face_ip);
fe_v_minus->CalcShape(ip_minus, shape_v_minus);
fe_rho_minus->CalcShape(ip_minus, shape_rho_minus);
fe_rho_plus->CalcShape(ip_plus, shape_rho_plus);
// v dot n
// u_n = ∑ n_c * ∑ v_kc * φ_k
double u_n = 0.0;
for (int c = 0; c < dim; ++c) {
double v_c = 0.0;
for (int k = 0; k < dof_v_minus; ++k) {
v_c += v_minus_dof(k, c) * shape_v_minus(k);
}
u_n += v_c * n_unit(c);
}
double rho_minus_val = 0.0;
for (int i = 0; i < dof_rho_minus; ++i) {
rho_minus_val += shape_rho_minus(i) * rho_minus_dof(i);
}
double rho_plus_val = 0.0;
for (int i = 0; i < dof_rho_plus; ++i) {
rho_plus_val += shape_rho_plus(i) * rho_plus_dof(i);
}
// Upwind density
// I use the convention that the flow is positive when moving from minus to plus
const double rho_up = (u_n >= 0) ? rho_minus_val : rho_plus_val;
const double flux_weighted = u_n * rho_up * ds;
// Note the normals need to be in opposite directions for these two fluxes
for (int i = 0; i < dof_rho_minus; ++i) {
r_rho(i) += shape_rho_minus(i) * flux_weighted;
}
for (int i = 0; i < dof_rho_plus; ++i) {
r_rho(dof_rho_minus + i) -= shape_rho_plus(i) * flux_weighted;
}
}
}
void ContinuityFaceIntegrator::AssembleFaceGrad(
const mfem::Array<const mfem::FiniteElement *> &el1,
const mfem::Array<const mfem::FiniteElement *> &el2,
mfem::FaceElementTransformations &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement *fe_v_minus = el1[0];
const mfem::FiniteElement *fe_v_plus = el2[0];
const mfem::FiniteElement *fe_rho_minus = el1[1];
const mfem::FiniteElement *fe_rho_plus = el2[1];
const int dof_v_minus = fe_v_minus->GetDof();
const int dof_v_plus = fe_v_plus->GetDof();
const int dof_rho_minus = fe_rho_minus->GetDof();
const int dof_rho_plus = fe_rho_plus->GetDof();
const int dim = Tr.GetSpaceDim();
const int N_v_total = dim * (dof_v_minus + dof_v_plus);
const int N_rho_total = dof_rho_minus + dof_rho_plus;
auto size_and_zero_mat = [&](mfem::DenseMatrix* mat, const int r_size, const int c_size) {
if (mat) {
mat->SetSize(r_size, c_size);
*mat = 0.0;
}
};
size_and_zero_mat(elmats(0, 0), N_v_total, N_v_total);
size_and_zero_mat(elmats(0, 1), N_v_total, N_rho_total);
size_and_zero_mat(elmats(1, 0), N_rho_total, N_v_total);
size_and_zero_mat(elmats(1, 1), N_rho_total, N_rho_total);
if (skip_face(Tr)) return;
mfem::DenseMatrix *drho_dv = elmats(1, 0);
mfem::DenseMatrix *drho_drho = elmats(1, 1);
if (!drho_dv && !drho_drho) return;
const mfem::Vector &v_dofs = *elfun[0];
const mfem::Vector &rho_dofs = *elfun[1];
const int int_order = 2 * std::max(fe_v_minus->GetOrder(), fe_rho_minus->GetOrder()) + 1;
const mfem::IntegrationRule *ir = &mfem::IntRules.Get(Tr.GetGeometryType(), int_order);
mfem::Vector shape_v_minus(dof_v_minus), shape_rho_minus(dof_rho_minus), shape_rho_plus(dof_rho_plus);
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& face_ip = ir->IntPoint(q);
Tr.SetAllIntPoints(&face_ip);
const mfem::IntegrationPoint &ip_minus = Tr.GetElement1IntPoint();
const mfem::IntegrationPoint &ip_plus = Tr.GetElement2IntPoint();
auto [n_unit, ds, v_dot_n_scale] = m_map.GetFaceQuadratureContext(Tr, face_ip);
fe_v_minus->CalcShape(ip_minus, shape_v_minus);
fe_rho_minus->CalcShape(ip_minus, shape_rho_minus);
fe_rho_plus->CalcShape(ip_plus, shape_rho_plus);
const double u_n = compute_u_n(v_dofs, shape_v_minus, n_unit, dof_v_minus, dim);
double rho_minus_val = 0.0;
for (int i = 0; i < dof_rho_minus; ++i) {
rho_minus_val += shape_rho_minus(i) * rho_dofs(i);
}
double rho_plus_val = 0.0;
for (int i = 0; i < dof_rho_plus; ++i) {
rho_plus_val += shape_rho_plus(i) * rho_dofs(dof_rho_minus + i);
}
const bool upwind_minus = (u_n >= 0.0);
const double rho_up = upwind_minus ? rho_minus_val : rho_plus_val;
// (1, 1)
if (drho_drho) {
const double u_w = u_n * ds;
if (upwind_minus) {
for (int ip = 0; ip < dof_rho_minus; ++ip) {
const double col_w = u_w * shape_rho_minus(ip);
for (int i = 0; i < dof_rho_minus; ++i) {
(*drho_drho)(i, ip) += shape_rho_minus(i) * col_w;
}
for (int j = 0; j < dof_rho_plus; ++j) {
(*drho_drho)(dof_rho_minus + j, ip) -= shape_rho_plus(j) * col_w;
}
}
} else {
for (int jp = 0; jp < dof_rho_plus; ++jp) {
const double col_w = u_w * shape_rho_plus(jp);
const int col_idx = dof_rho_minus + jp;
for (int i = 0; i < dof_rho_minus; ++i) {
(*drho_drho)(i, col_idx) += shape_rho_minus(i) * col_w;
}
for (int j = 0; j < dof_rho_plus; ++j) {
(*drho_drho)(dof_rho_minus + j, col_idx) -= shape_rho_plus(j) * col_w;
}
}
}
}
// (1, 0)
if (drho_dv) {
const double rho_w = rho_up * ds;
for (int c = 0; c < dim; ++c) {
const double n_c_rho_w = n_unit(c) * rho_w;
for (int k = 0; k < dof_v_minus; ++k) {
const int col_idx = k + c * dof_v_minus;
const double col_w = n_c_rho_w * shape_v_minus(k);
for (int i = 0; i < dof_rho_minus; ++i) {
(*drho_dv)(i, col_idx) += shape_rho_minus(i) * col_w;
}
for (int j = 0; j < dof_rho_plus; ++j) {
(*drho_dv)(dof_rho_minus + j, col_idx) -= shape_rho_plus(j) * col_w;
}
}
}
}
}
}
bool ContinuityFaceIntegrator::skip_face(const mfem::FaceElementTransformations& Tr) {
constexpr int VACUUM_ATTR = 3;
const int attr_minus = Tr.Elem1->Attribute;
const int attr_plus = (Tr.Elem2 != nullptr) ? Tr.Elem2->Attribute : -1;
if (attr_minus == VACUUM_ATTR || attr_plus == VACUUM_ATTR) {
return true; // No flux contribution for vacuum faces
}
if (Tr.Elem2 == nullptr) {
return true; // Boundary face,
}
return false;
}
double ContinuityFaceIntegrator::compute_u_n(const mfem::Vector& v_dofs, const mfem::Vector& shape_v_minus, const mfem::Vector& n_unit, int dof_v_minus, int dim) {
double u_n = 0.0;
for (int c = 0; c < dim; ++c) {
double v_c = 0.0;
for (int k = 0; k < dof_v_minus; ++k) {
v_c += v_dofs(k + c * dof_v_minus) * shape_v_minus(k);
}
u_n += v_c * n_unit(c);
}
return u_n;
}
}

View File

@@ -0,0 +1,156 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::integrators {
ViscosityIntegrator::ViscosityIntegrator(
const mapping::DomainMapper& map,
const double mu,
const int quad_boost
) : m_map(map), m_mu(mu), m_quad_boost(quad_boost) {}
void ViscosityIntegrator::SetMu(const double mu) { m_mu = mu; }
void ViscosityIntegrator::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
void* data_before = (void*)elvec[0]->GetData();
int size_before = elvec[0]->Size();
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& v_dofs = *elfun[0];
mfem::Vector& r_v = *elvec[0];
r_v.SetSize(dof_v * dim);
r_v = 0.0;
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder() + m_quad_boost);
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
// ∇v(c,j) = δj v_c
mfem::DenseMatrix grad_v(dim, dim); grad_v = 0.0;
for (int n = 0; n < dof_v; ++n) {
for (int c = 0; c < dim; ++c) {
const double vn_c = v_dofs(n + c * dof_v);
for (int j = 0; j < dim; ++j) {
grad_v( c, j) += vn_c * dshape_v_phys(n, j);
}
}
}
double div_v = 0.0;
for (int c = 0; c < dim; ++c) {
div_v += grad_v(c, c);
}
// D_cj = dj v_c + dc v_j - (2/3) δcj ∇v
// R_v_i^c += μ * weight * ∑_j (δj φi) D_cj
const double mu_w = m_mu * weight;
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
double acc = 0.0;
for (int j = 0; j < dim; ++j) {
double D_cj = grad_v(c, j) + grad_v(j, c);
if (c == j) D_cj -= (2.0 / 3.0) * div_v;
acc += dshape_v_phys(i, j) * D_cj;
}
r_v(i + c * dof_v) += mu_w * acc;
}
}
}
}
void ViscosityIntegrator::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
mfem::DenseMatrix* dv_dv = elmats(0, 0);
mfem::DenseMatrix* dv_drho = elmats(0, 1);
if (dv_drho) *dv_drho =0.0;
if (dv_dv) *dv_dv = 0.0;
if (elmats(1, 0)) *elmats(1, 0) = 0.0;
if (elmats(1, 1)) *elmats(1, 1) = 0.0;
if (!dv_dv) return;
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
const double mu_w = m_mu * weight;
for (int i = 0; i < dof_v; ++i) {
for (int n = 0; n < dof_v; ++n) {
double dot_grad = 0.0;
for (int j = 0; j < dim; ++j) {
dot_grad += dshape_v_phys(i, j) * dshape_v_phys(n, j);
}
for (int c = 0; c < dim; ++c) {
const int row = i + c * dof_v;
for (int d = 0; d < dim; ++d) {
const int col = n + d * dof_v;
double val = 0.0;
if (c == d) val += dot_grad;
val += dshape_v_phys(i, d) * dshape_v_phys(n, c);
val -= (2.0 / 3.0) * dshape_v_phys(i, c) * dshape_v_phys(n, d);
(*dv_dv)(row, col) += mu_w * val;
}
}
}
}
}
}
}

View File

@@ -0,0 +1,152 @@
module;
#include <mfem.hpp>
module mean_field;
import :mapping.types;
namespace mean_field::mapping {
///////////////////////////////
/// MappedScalarCoefficient ///
//////////////////////////////
MappedScalarCoefficient::MappedScalarCoefficient(
const DomainMapper &map,
mfem::Coefficient &coeff,
const COORDINATE_SPACE coord_space
) : m_map(map),
m_coeff(coeff),
m_coord_space(coord_space) {};
double MappedScalarCoefficient::Eval(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) {
T.SetIntPoint(&ip);
double f_val = 0.0;
switch (m_coord_space) {
case COORDINATE_SPACE::PHYSICAL: {
f_val = eval_at_point(m_coeff, T, ip);
const double detJ = m_map.ComputeDetJ(T, ip);
return f_val * fabs(detJ);
}
case COORDINATE_SPACE::REFERENCE: {
f_val = m_coeff.Eval(T, ip);
return f_val;
}
}
}
double MappedScalarCoefficient::eval_at_point(mfem::Coefficient &c, mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) {
return c.Eval(T, ip);
}
//////////////////////////////////
/// MappedDiffusionCoefficient ///
//////////////////////////////////
MappedDiffusionCoefficient::MappedDiffusionCoefficient(
const DomainMapper &map,
mfem::Coefficient &sigma,
const int dim
) : mfem::MatrixCoefficient(dim),
m_map(map),
m_scalar(&sigma),
m_tensor(nullptr) {
};
MappedDiffusionCoefficient::MappedDiffusionCoefficient(
const DomainMapper &map,
mfem::MatrixCoefficient &sigma
) : mfem::MatrixCoefficient(sigma.GetHeight()),
m_map(map),
m_scalar(nullptr),
m_tensor(&sigma) {
};
void MappedDiffusionCoefficient::Eval(mfem::DenseMatrix &K, mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) {
const int dim = height;
T.SetIntPoint(&ip);
mfem::DenseMatrix J(dim, dim), JInv(dim, dim);
m_map.ComputeJacobian(T, J);
const double detJ = J.Det();
mfem::CalcInverse(J, JInv);
if (m_scalar) {
const double sig_val = m_scalar->Eval(T, ip);
mfem::MultABt(JInv, JInv, K);
K *= sig_val * fabs(detJ);
} else {
mfem::DenseMatrix sig_mat(dim, dim);
m_tensor->Eval(sig_mat, T, ip);
mfem::DenseMatrix temp(dim, dim);
Mult(JInv, sig_mat, temp);
MultABt(temp, JInv, K);
K *= fabs(detJ);
}
}
///////////////////////////////
/// MappedVectorCoefficient ///
///////////////////////////////
MappedVectorCoefficient::MappedVectorCoefficient(
const DomainMapper &map,
mfem::VectorCoefficient &coeff
) : mfem::VectorCoefficient(coeff.GetVDim()),
m_map(map),
m_coeff(coeff) {
};
void MappedVectorCoefficient::Eval(mfem::Vector &V, mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) {
const int dim = vdim;
T.SetIntPoint(&ip);
mfem::DenseMatrix JInv(dim, dim);
m_map.ComputeInverseJacobian(T, JInv);
double detJ = m_map.ComputeDetJ(T, ip);
mfem::Vector C_phys(dim);
m_coeff.Eval(C_phys, T, ip);
V.SetSize(dim);
JInv.MultTranspose(C_phys, V);
V *= fabs(detJ);
}
///////////////////////////////////////////
/// PhysicalPositionFunctionCoefficient ///
///////////////////////////////////////////
PhysicalPositionFunctionCoefficient::PhysicalPositionFunctionCoefficient(
const DomainMapper &map,
Func f // std::function<double(const mfem::Vector&)>
) : m_f(std::move(f)),
m_map(map) {};
double PhysicalPositionFunctionCoefficient::Eval(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) {
T.SetIntPoint(&ip);
mfem::Vector x;
m_map.GetPhysicalPoint(T, ip, x);
return m_f(x);
}
MappedHDivMassCoefficient::MappedHDivMassCoefficient(const DomainMapper& map, const int dim)
: mfem::MatrixCoefficient(dim),
m_map(map) {}
void MappedHDivMassCoefficient::Eval(
mfem::DenseMatrix& matrix,
mfem::ElementTransformation& transformation,
const mfem::IntegrationPoint& integration_point
) {
transformation.SetIntPoint(&integration_point);
mfem::DenseMatrix map_jacobian(height, height);
m_map.ComputeJacobian(transformation, map_jacobian);
const double map_determinant = map_jacobian.Det();
MFEM_VERIFY(map_determinant > 0.0, "Domain mapping has a non-positive Jacobian determinant.");
mfem::MultAtB(map_jacobian, map_jacobian, matrix);
matrix *= 1.0 / std::abs(map_determinant);
}
}

View File

@@ -0,0 +1,294 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::mapping {
DomainMapper::DomainMapper(
const double r_star_ref,
const double r_inf_ref
) : m_d(nullptr),
m_r_star_ref(r_star_ref),
m_r_inf_ref(r_inf_ref) {
InitAllScratchSpaces();
}
DomainMapper::DomainMapper(
const mfem::GridFunction &d,
const double r_star_ref,
const double r_inf_ref
) : m_d(&d),
m_dim(d.FESpace()->GetMesh()->Dimension()),
m_r_star_ref(r_star_ref),
m_r_inf_ref(r_inf_ref) {
InitAllScratchSpaces();
}
bool DomainMapper::is_vacuum(const mfem::ElementTransformation &T) const {
if (T.ElementType == mfem::ElementTransformation::ELEMENT) {
return T.Attribute == m_vacuum_attr;
} else if (T.ElementType == mfem::ElementTransformation::BDR_ELEMENT) {
return T.Attribute == m_vacuum_attr - 1;
// TODO: In a more robust code this should really be read from the stroid API to ensure that the vacuum boundary is really 1 - the vacuum material attribute
}
return false;
}
void DomainMapper::SetDisplacement(const mfem::GridFunction &d) {
if (m_dim != d.FESpace()->GetMesh()->Dimension()) {
const std::string err_msg = std::format(
"Dimension mismatch: DomainMapper is initialized for dimension {}, but provided displacement field has dimension {}.",
m_dim, d.FESpace()->GetMesh()->Dimension());
throw std::invalid_argument(err_msg);
}
m_d = &d;
InvalidateCache();
}
bool DomainMapper::IsIdentity() const {
return (m_d == nullptr);
}
void DomainMapper::ResetDisplacement() {
m_d = nullptr;
InvalidateCache();
}
void DomainMapper::ComputeJacobian(mfem::ElementTransformation &T, mfem::DenseMatrix &J) const {
J.SetSize(m_dim, m_dim);
J = 0.0;
m_J_D = 0.0;
if (IsIdentity()) {
for (int i = 0; i < m_dim; ++i) {
m_J_D(i, i) = 1.0; // Identity mapping
}
} else {
UpdateElementCache(T);
m_dshape.SetSize(m_fe->GetDof(), m_dim);
m_fe->CalcPhysDShape(T, m_dshape);
mfem::MultAtB(m_dof_mat, m_dshape, m_J_D);
for (int i = 0; i < m_dim; ++i) {
m_J_D(i, i) += 1.0;
}
}
if (is_vacuum(T)) {
T.Transform(T.GetIntPoint(), m_x_ref);
if (IsIdentity()) {
m_x_disp = m_x_ref;
} else {
m_shape.SetSize(m_fe->GetDof());
m_fe->CalcShape(T.GetIntPoint(), m_shape);
m_dof_mat.MultTranspose(m_shape, m_d_val);
add(m_x_ref, m_d_val, m_x_disp);
}
ComputeKelvinJacobian(m_x_ref, m_x_disp, m_J_D, J);
} else {
J = m_J_D;
}
}
double DomainMapper::ComputeDetJ(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) const {
if (IsIdentity() && !is_vacuum(T)) return 1.0; // If no mapping, the determinant of the Jacobian is 1
T.SetIntPoint(&ip);
mfem::DenseMatrix J;
ComputeJacobian(T, J);
return J.Det();
}
void DomainMapper::ComputeMappedDiffusionTensor(mfem::ElementTransformation &T, mfem::DenseMatrix &D) const {
ComputeJacobian(T, m_J_temp);
const double detJ = m_J_temp.Det();
mfem::CalcInverse(m_J_temp, m_JInv_temp);
D.SetSize(m_dim, m_dim);
mfem::MultABt(m_JInv_temp, m_JInv_temp, D);
D *= fabs(detJ);
}
void DomainMapper::ComputeInverseJacobian(mfem::ElementTransformation &T, mfem::DenseMatrix &JInv) const {
ComputeJacobian(T, m_J_temp);
JInv.SetSize(m_dim, m_dim);
mfem::CalcInverse(m_J_temp, JInv);
}
DomainMapper::VolumeQuadratureContext DomainMapper::GetQuadratureContext(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) const {
const int dim = T.GetSpaceDim();
mfem::DenseMatrix J_map(dim, dim), J_inv(dim, dim);
ComputeJacobian(T, J_map);
mfem::DenseMatrix J_full(dim, dim);
mfem::Mult(J_map, T.Jacobian(), J_full);
mfem::CalcInverse(J_full, J_inv);
const double detJ = std::fabs(ComputeDetJ(T, ip));
const double weight = ip.weight * T.Weight() * detJ;
return {.J_inv = J_inv, .detJ = detJ, .weight = weight};
}
DomainMapper::FaceQuadratureContext DomainMapper::GetFaceQuadratureContext(mfem::FaceElementTransformations &T, const mfem::IntegrationPoint &ip) const {
const int dim = T.GetSpaceDim();
T.SetAllIntPoints(&ip);
mfem::Vector n_raw(dim);
mfem::CalcOrtho(T.Jacobian(), n_raw);
if (IsIdentity()) {
const double n_raw_mag = n_raw.Norml2();
mfem::Vector n_unit(dim);
n_unit = n_raw;
n_unit /= n_raw_mag;
return FaceQuadratureContext{.normal=n_unit, .ds=ip.weight * n_raw_mag, .v_dot_n_scale = 1.0};
}
// Nanson's Formula (https://en.wikiversity.org/wiki/Continuum_mechanics/Volume_change_and_area_change)
// Since the displacement field lives in H1 it should be irrelevant if we pick Elem1 or Elem2
mfem::DenseMatrix J_map(dim, dim);
ComputeJacobian(*T.Elem1, J_map);
const double detJ_map = J_map.Det();
mfem::DenseMatrix J_map_inv(dim, dim);
mfem::CalcInverse(J_map, J_map_inv);
mfem::Vector n_phys(dim);
J_map_inv.MultTranspose(n_raw, n_phys);
n_phys *= detJ_map;
const double n_phys_mag = n_phys.Norml2();
mfem::Vector n_unit(dim);
n_unit = n_phys;
n_unit /= n_phys_mag;
const double n_raw_mag = n_raw.Norml2();
return FaceQuadratureContext{
.normal = n_unit,
.ds = ip.weight * n_raw_mag,
.v_dot_n_scale = n_phys_mag / n_raw_mag
};
}
void DomainMapper::GetPhysicalPoint(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip, mfem::Vector &x_phys) const {
x_phys.SetSize(m_dim);
T.Transform(ip, m_x_ref);
if (IsIdentity()) {
x_phys = m_x_ref;
} else {
UpdateElementCache(T);
m_shape.SetSize(m_fe->GetDof());
m_fe->CalcShape(ip, m_shape);
m_dof_mat.MultTranspose(m_shape, m_d_val);
add(m_x_ref, m_d_val, x_phys);
}
if (is_vacuum(T)) {
ApplyKelvinMapping(m_x_ref, x_phys);
}
}
void DomainMapper::GetVectorValue(const int i, const mfem::IntegrationPoint &ip, mfem::Vector &val) const {
m_d->GetVectorValue(i, ip, val);
}
const mfem::GridFunction *DomainMapper::GetDisplacement() const { return m_d; }
double DomainMapper::GetPhysInfRadius() const {
return 1.0 - m_xi_clamp;
}
size_t DomainMapper::GetCacheHits() const {
return m_cache_hits;
}
size_t DomainMapper::GetCacheMisses() const {
return m_cache_misses;
}
double DomainMapper::GetCacheHitRate() const {
return (static_cast<double>(m_cache_hits)) / static_cast<double>(m_cache_misses + m_cache_hits);
}
void DomainMapper::ResetCacheStats() const {
m_cache_hits = 0;
m_cache_misses = 0;
}
void DomainMapper::InitAllScratchSpaces() const {
m_J_D.SetSize(m_dim, m_dim);
m_J_temp.SetSize(m_dim, m_dim);
m_JInv_temp.SetSize(m_dim, m_dim);
m_x_ref.SetSize(m_dim);
m_x_disp.SetSize(m_dim);
m_d_val.SetSize(m_dim);
}
void DomainMapper::ApplyKelvinMapping(const mfem::Vector &x_ref, mfem::Vector &x_phys) const {
const double r_ref = x_ref.Norml2();
double xi = (r_ref - m_r_star_ref) / (m_r_inf_ref - m_r_star_ref);
xi = std::clamp(xi, 0.0, m_xi_clamp);
const double factor = m_r_star_ref / (r_ref * (1 - xi));
x_phys *= factor;
}
void DomainMapper::ComputeKelvinJacobian(const mfem::Vector &x_ref, const mfem::Vector &x_disp, const mfem::DenseMatrix &J_D,
mfem::DenseMatrix &J) const {
const double r_ref = x_ref.Norml2();
const double delta_R = m_r_inf_ref - m_r_star_ref;
double xi = (r_ref - m_r_star_ref) / delta_R;
xi = std::clamp(xi, 0.0, m_xi_clamp);
const double denom = 1.0 - xi;
const double k = m_r_star_ref / (r_ref * denom);
const double dk_dr = m_r_star_ref * ((1.0 / (delta_R * r_ref * denom * denom)) - (
1.0 / (r_ref * r_ref * denom)));
J.SetSize(m_dim, m_dim);
const double outer_factor = dk_dr / r_ref;
for (int i = 0; i < m_dim; ++i) {
for (int j = 0; j < m_dim; ++j) {
J(i, j) = outer_factor * x_disp(i) * x_ref(j) + k * J_D(i, j);
}
}
}
void DomainMapper::InvalidateCache() const {
m_cached_elem_id = -1;
}
void DomainMapper::UpdateElementCache(const mfem::ElementTransformation &T) const {
if (IsIdentity()) return;
if (T.ElementNo != m_cached_elem_id || T.ElementType != m_cached_elem_type) {
m_cache_misses++;
m_cached_elem_id = T.ElementNo;
m_cached_elem_type = T.ElementType;
const mfem::FiniteElementSpace *fes = m_d->FESpace();
mfem::Array<int> vdofs;
if (T.ElementType == mfem::ElementTransformation::ELEMENT) {
m_fe = fes->GetFE(m_cached_elem_id);
fes->GetElementVDofs(m_cached_elem_id, vdofs);
} else {
m_fe = fes->GetBE(m_cached_elem_id);
fes->GetBdrElementVDofs(m_cached_elem_id, vdofs);
}
m_d->GetSubVector(vdofs, m_elem_dofs);
const int nd = m_fe->GetDof();
const int vd = fes->GetVDim();
m_dof_mat.UseExternalData(m_elem_dofs.GetData(), nd, vd);
} else {
m_cache_hits++;
}
}
}

View File

@@ -0,0 +1,297 @@
module;
#include "mfem.hpp"
#include <source_location>
#include <cmath>
#include <string_view>
#include <unordered_map>
#include <format>
module mean_field;
import :mapping.coefficients;
import :analysis.integral;
namespace {
double centrifugal_potential(const mfem::Vector &phys_x, const double omega) {
const double s2 = std::pow(phys_x(0), 2) + std::pow(phys_x(1), 2);
return -0.5 * s2 * std::pow(omega, 2);
}
}
namespace mean_field::physics {
GravitySolution grav_potential(
fem::FEM &f,
const utils::Args &args,
const mfem::GridFunction &rho,
const bool phi_warm
) {
mfem::Array<int> outer_bdr_marker(f.mesh->bdr_attributes.Max());
outer_bdr_marker = 0;
outer_bdr_marker[1] = 1;
mfem::ParLinearForm g_rhs(f.RT_fes.get());
// ReSharper disable once CppTooWideScope
std::unique_ptr<mfem::Coefficient> boundary_potential_coeff;
if (!f.has_mapping()) { // We only need to explicitly add a boundary integrator if a mapping is not being used. In the case where the outer domain has been compactified the φ=0 boundary condition is the natural condition and MFEM automatically handles this
auto boundary_potential = [&f](const mfem::Vector& x_physical) {
return l2_multipole_potential(f, utils::MASS, x_physical);
};
boundary_potential_coeff = std::make_unique<mfem::FunctionCoefficient>(boundary_potential);
auto boundary_integrator = std::make_unique<mfem::VectorFEBoundaryFluxLFIntegrator>(*boundary_potential_coeff);
const mfem::FiniteElement& boundary_element = *f.RT_fes->GetTypicalTraceElement();
f.quadrature_factory->configure_gravity_boundary(*boundary_integrator, quadrature::QuadratureRole::discretization, boundary_element, utils::DOMAINS::VACUUM, quadrature::MappingKind::none);
g_rhs.AddBoundaryIntegrator(boundary_integrator.release(), outer_bdr_marker);
}
g_rhs.Assemble();
mfem::GridFunctionCoefficient rho_coeff(&rho);
mfem::ConstantCoefficient G4pi(4.0 * M_PI * utils::G);
mfem::ProductCoefficient source_coeff(G4pi, rho_coeff);
mfem::ParLinearForm f_rhs(f.L2_fes.get());
std::unique_ptr<mfem::Coefficient> mapped_source_coeff;
mfem::Coefficient* active_source_coeff = &source_coeff;
quadrature::MappingKind source_mapping_kind = quadrature::MappingKind::none;
if (f.has_mapping()) {
mapped_source_coeff = std::make_unique<mapping::MappedScalarCoefficient>(*f.mapping, source_coeff);
active_source_coeff = mapped_source_coeff.get();
source_mapping_kind = quadrature::MappingKind::general;
}
auto source_integrator = std::make_unique<mfem::DomainLFIntegrator>(*active_source_coeff);
const mfem::FiniteElement& source_test_element = *f.L2_fes->GetTypicalFE();
const mfem::ElementTransformation& source_transformation = *f.mesh->GetElementTransformation(0);
const int source_coefficient_order = f.L2_fes->GetMaxElementOrder();
f.quadrature_factory->configure_gravity_source(*source_integrator, quadrature::QuadratureRole::discretization, source_test_element, source_transformation, source_coefficient_order, utils::DOMAINS::STELLAR, source_mapping_kind);
f_rhs.AddDomainIntegrator(source_integrator.release(), f.gravity_context.stellar_mask);
f_rhs.Assemble();
mfem::BlockVector RHS(f.gravity_block_true_offsets);
RHS.GetBlock(0) = *g_rhs.ParallelAssemble();
RHS.GetBlock(1) = *f_rhs.ParallelAssemble();
mfem::BlockVector X(f.gravity_block_true_offsets);
X = 0.0;
f.gravity_context.minres->SetOperator(*f.gravity_context.block_A);
f.gravity_context.minres->Mult(RHS, X);
GravitySolution solution(f);
solution.gradPhi.SetFromTrueDofs(X.GetBlock(0));
solution.phi.SetFromTrueDofs(X.GetBlock(1));
return solution;
}
mfem::GridFunction get_potential(
fem::FEM &fem,
const utils::Args &args,
const mfem::GridFunction &rho,
const bool warm
) {
auto phi = grav_potential(fem, args, rho, warm);
if (args.r.enabled) {
auto rot = [&fem, &args](const mfem::Vector &x) {
mfem::Vector rel_x = x;
rel_x -= fem.com;
return centrifugal_potential(rel_x, args.r.omega);
};
std::unique_ptr<mfem::Coefficient> centrifugal_coeff;
if (fem.has_mapping()) {
centrifugal_coeff = std::make_unique<mapping::PhysicalPositionFunctionCoefficient>(*fem.mapping, rot);
} else {
centrifugal_coeff = std::make_unique<mfem::FunctionCoefficient>(rot);
}
mfem::GridFunction centrifugal_gf(fem.H1_fes.get());
centrifugal_gf.ProjectCoefficient(*centrifugal_coeff);
phi.phi += centrifugal_gf;
}
return phi.phi;
}
mfem::DenseMatrix compute_quadrupole_moment_tensor(
const fem::FEM &fem,
const mfem::GridFunction &rho,
const mfem::Vector &com
) {
const int dim = fem.mesh->Dimension();
mfem::DenseMatrix local_Q(dim, dim);
local_Q = 0.0;
for (int i = 0; i < fem.H1_fes->GetNE(); ++i) {
if (fem.mesh->GetAttribute(i) == 3) continue;
mfem::ElementTransformation *trans = fem.mesh->GetElementTransformation(i);
const mfem::IntegrationRule &ir = *fem.int_rule;
for (int j = 0; j < ir.GetNPoints(); ++j) {
const mfem::IntegrationPoint &ip = ir.IntPoint(j);
trans->SetIntPoint(&ip);
double weight = trans->Weight() * ip.weight;
if (fem.has_mapping()) {
weight *= fem.mapping->ComputeDetJ(*trans, ip);
}
const double rho_val = rho.GetValue(i, ip);
mfem::Vector phys_point(dim);
if (fem.has_mapping()) {
fem.mapping->GetPhysicalPoint(*trans, ip, phys_point);
} else {
trans->Transform(ip, phys_point);
}
mfem::Vector x_prime(dim);
double r_sq = 0.0;
for (int d = 0; d < dim; ++d) {
x_prime(d) = phys_point(d) - com(d);
r_sq += x_prime(d) * x_prime(d);
}
for (int m = 0; m < dim; ++m) {
for (int n = 0; n < dim; ++n) {
const double delta = (m == n) ? 1.0 : 0.0;
const double contrib = 3.0 * x_prime(m) * x_prime(n) - delta * r_sq;
local_Q(m, n) += rho_val * contrib * weight;
}
}
}
}
mfem::DenseMatrix global_Q(dim, dim);
MPI_Allreduce(local_Q.GetData(), global_Q.GetData(), dim * dim, MPI_DOUBLE, MPI_SUM, fem.H1_fes->GetComm());
return global_Q;
}
double l2_multipole_potential(
const fem::FEM &fem,
const double total_mass,
const mfem::Vector &phys_x
) {
const double r = phys_x.Norml2();
if (r < 1e-12) return 0.0;
const int dim = fem.mesh->Dimension();
mfem::Vector n(phys_x);
n /= r;
double l2_mult_factor = 0.0;
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j) {
l2_mult_factor += fem.Q(i, j) * n(i) * n(j);
}
}
const double l2_contrib = -(utils::G / (2.0 * std::pow(r, 3))) * l2_mult_factor;
const double l0_contrib = -utils::G * total_mass / r;
// l1 contribution is zero for a system centered on its COM
return l0_contrib + l2_contrib;
}
void update_stiffness_matrix(fem::FEM &f) {
mfem::Array<int> empty_tdofs;
// ==========================================
// 1. Partially Assemble the High-Order Mass Block
// ==========================================
f.gravity_context.m_form = std::make_unique<mfem::ParBilinearForm>(f.RT_fes.get());
f.gravity_context.m_form->SetAssemblyLevel(mfem::AssemblyLevel::PARTIAL);
std::unique_ptr<mfem::VectorFEMassIntegrator> hdiv_mass_integrator;
if (f.has_mapping()) {
f.gravity_context.mapped_hdiv_mass_coeff = std::make_unique<mapping::MappedHDivMassCoefficient>(*f.mapping, f.mesh->Dimension());
hdiv_mass_integrator = std::make_unique<mfem::VectorFEMassIntegrator>(*f.gravity_context.mapped_hdiv_mass_coeff);
} else {
f.gravity_context.mapped_hdiv_mass_coeff.reset();
hdiv_mass_integrator = std::make_unique<mfem::VectorFEMassIntegrator>();
}
const mfem::FiniteElement& hdiv_element = *f.RT_fes->GetTypicalFE();
const mfem::ElementTransformation& hdiv_transformation = *f.mesh->GetElementTransformation(0);
const quadrature::MappingKind mapping_kind = f.has_mapping() ? quadrature::MappingKind::general : quadrature::MappingKind::none;
f.quadrature_factory->configure_gravity_hdiv_mass(*hdiv_mass_integrator, quadrature::QuadratureRole::discretization, hdiv_element, hdiv_transformation, utils::DOMAINS::ALL, mapping_kind);
f.gravity_context.m_form->AddDomainIntegrator(hdiv_mass_integrator.release());
f.gravity_context.m_form->Assemble();
// ==========================================
// 2. Partially Assemble the High-Order Divergence Block
// ==========================================
f.gravity_context.b_form = std::make_unique<mfem::ParMixedBilinearForm>(f.RT_fes.get(), f.L2_fes.get());
f.gravity_context.b_form->SetAssemblyLevel(mfem::AssemblyLevel::PARTIAL);
auto divergence_discretization_integrator = std::make_unique<mfem::VectorFEDivergenceIntegrator>();
const mfem::FiniteElement& divergence_discretization_test_element = *f.L2_fes->GetTypicalFE();
f.quadrature_factory->configure_gravity_divergence(*divergence_discretization_integrator, quadrature::QuadratureRole::discretization, hdiv_element, divergence_discretization_test_element, hdiv_transformation, utils::DOMAINS::ALL, quadrature::MappingKind::none);
f.gravity_context.b_form->AddDomainIntegrator(divergence_discretization_integrator.release());
f.gravity_context.b_form->Assemble();
// ==========================================
// 3. Assemble Global Block Operator
// ==========================================
f.gravity_context.BT = std::make_unique<mfem::TransposeOperator>(f.gravity_context.b_form.get());
f.gravity_context.block_A = std::make_unique<mfem::BlockOperator>(f.gravity_block_true_offsets);
f.gravity_context.block_A->SetBlock(0, 0, f.gravity_context.m_form.get());
f.gravity_context.block_A->SetBlock(0, 1, f.gravity_context.BT.get());
f.gravity_context.block_A->SetBlock(1, 0, f.gravity_context.b_form.get());
// ==========================================
// 4. Construct a mapped Schur preconditioner
// ==========================================
mfem::Vector mass_diagonal(f.RT_fes->GetTrueVSize());
f.gravity_context.m_form->AssembleDiagonal(mass_diagonal);
mfem::Vector inverse_mass_diagonal(mass_diagonal);
for (int i = 0; i < inverse_mass_diagonal.Size(); ++i) {
MFEM_VERIFY(std::isfinite(inverse_mass_diagonal(i)) && inverse_mass_diagonal(i) > 0.0, "Mapped RT mass matrix has a non-positive or non-finite diagonal entry.");
inverse_mass_diagonal(i) = 1.0 / inverse_mass_diagonal(i);
}
mfem::ParMixedBilinearForm b_preconditioner(f.RT_fes.get(), f.L2_fes.get());
auto divergence_preconditioner_integrator = std::make_unique<mfem::VectorFEDivergenceIntegrator>();
const mfem::FiniteElement& divergence_trial_element = *f.RT_fes->GetTypicalFE();
const mfem::FiniteElement& divergence_test_element = *f.L2_fes->GetTypicalFE();
const mfem::ElementTransformation& divergence_transformation = *f.mesh->GetElementTransformation(0);
f.quadrature_factory->configure_gravity_divergence(*divergence_preconditioner_integrator, quadrature::QuadratureRole::preconditioner, divergence_trial_element, divergence_test_element, divergence_transformation, utils::DOMAINS::ALL, quadrature::MappingKind::none);
b_preconditioner.AddDomainIntegrator(divergence_preconditioner_integrator.release());
b_preconditioner.Assemble();
b_preconditioner.Finalize();
std::unique_ptr<mfem::HypreParMatrix> b_matrix(b_preconditioner.ParallelAssemble());
std::unique_ptr<mfem::HypreParMatrix> inverse_mass_b_transpose(b_matrix->Transpose());
inverse_mass_b_transpose->ScaleRows(inverse_mass_diagonal);
f.gravity_context.Schur.reset(mfem::ParMult(b_matrix.get(), inverse_mass_b_transpose.get()));
// ==========================================
// 5. Wire Up the preconditioners
// ==========================================
f.gravity_context.prec_M = std::make_unique<mfem::OperatorJacobiSmoother>(mass_diagonal, empty_tdofs);
f.gravity_context.prec_Phi->SetOperator(*f.gravity_context.Schur);
f.gravity_context.block_prec->SetDiagonalBlock(0, f.gravity_context.prec_M.get());
f.gravity_context.block_prec->SetDiagonalBlock(1, f.gravity_context.prec_Phi.get());
}
}

View File

@@ -0,0 +1,38 @@
module;
#include "mean_field.h"
module mean_field;
namespace mean_field::physics {
double compute_moment_of_inertia(const fem::FEM &fem, const mfem::GridFunction &rho_ref) {
double local_I = 0.0;
for (int i = 0; i < fem.mesh->GetNE(); i++) {
if (fem.mesh->GetAttribute(i) == 3) continue;
mfem::ElementTransformation *T = fem.mesh->GetElementTransformation(i);
const mfem::IntegrationRule &ir = *fem.int_rule;
for (int j = 0; j < ir.GetNPoints(); j++) {
const mfem::IntegrationPoint &ip = ir.IntPoint(j);
T->SetIntPoint(&ip);
const double rho_hat = rho_ref.GetValue(i, ip);
mfem::Vector x_phys;
fem.mapping->GetPhysicalPoint(*T, ip, x_phys);
const double r_cyl_sq = x_phys(0) * x_phys(0) + x_phys(1) * x_phys(1);
const double detJ = std::fabs(fem.mapping->ComputeDetJ(*T, ip));
const double weight = T->Weight() * ip.weight * detJ;
local_I += rho_hat * r_cyl_sq * weight;
}
}
double global_I = 0.0;
MPI_Allreduce(&local_I, &global_I, 1, MPI_DOUBLE, MPI_SUM, fem.H1_fes->GetComm());
return global_I;
}
}

View File

@@ -0,0 +1,188 @@
module;
#include <mfem.hpp>
module mean_field;
namespace mean_field::utils {
bool GetReferencePoint(
const fem::FEM &fem,
const mfem::Vector &x_phys_target,
mfem::Vector &x_ref
) {
const int dim = fem.mesh->Dimension();
x_ref = x_phys_target;
mfem::Array<int> init_elem;
mfem::Array<mfem::IntegrationPoint> init_ip;
mfem::DenseMatrix init_P(dim, 1);
init_P.SetCol(0, x_ref);
fem.mesh->FindPoints(init_P, init_elem, init_ip, false);
if (init_elem.Size() == 0 || init_elem[0] < 0) {
mfem::Vector origin(dim);
origin = 0.0;
mfem::DenseMatrix P_origin(dim, 1);
P_origin.SetCol(0, origin);
mfem::Array<int> origin_elem;
mfem::Array<mfem::IntegrationPoint> origin_ip;
fem.mesh->FindPoints(P_origin, origin_elem, origin_ip, false);
if (origin_elem.Size() > 0 && origin_elem[0] >= 0 && !fem.mapping->IsIdentity()) {
mfem::ElementTransformation *T0 = fem.mesh->GetElementTransformation(origin_elem[0]);
T0->SetIntPoint(&origin_ip[0]);
mfem::DenseMatrix J0(dim, dim), J0_inv(dim, dim);
fem.mapping->ComputeJacobian(*T0, J0);
mfem::CalcInverse(J0, J0_inv);
J0_inv.Mult(x_phys_target, x_ref);
}
init_P.SetCol(0, x_ref);
fem.mesh->FindPoints(init_P, init_elem, init_ip, false);
if (init_elem.Size() == 0 || init_elem[0] < 0) {
double norm = x_ref.Norml2();
if (norm > 1e-15) {
double scale = 0.9 * RADIUS / norm;
if (scale < 1.0) {
x_ref *= scale;
}
}
init_P.SetCol(0, x_ref);
fem.mesh->FindPoints(init_P, init_elem, init_ip, false);
if (init_elem.Size() == 0 || init_elem[0] < 0) {
x_ref = 0.0;
}
}
}
constexpr int max_iter = 50;
mfem::Array<int> elem_ids;
mfem::Array<mfem::IntegrationPoint> ips;
mfem::DenseMatrix P(dim, 1);
mfem::Vector d(dim);
mfem::Vector residual(dim);
mfem::Vector step(dim);
mfem::DenseMatrix J_map(dim, dim);
mfem::DenseMatrix J_map_inv(dim, dim);
int find_failures = 0;
for (int iter = 0; iter < max_iter; ++iter) {
P.SetCol(0, x_ref);
fem.mesh->FindPoints(P, elem_ids, ips, false);
if (elem_ids.Size() == 0 || elem_ids[0] < 0) {
find_failures++;
if (find_failures > 10) return false;
double norm = x_ref.Norml2();
if (norm > 1e-15) {
x_ref *= 0.5 * RADIUS / norm;
} else {
x_ref = 0.0;
}
continue;
}
int elemID = elem_ids[0];
const mfem::IntegrationPoint &ip = ips[0];
mfem::ElementTransformation *T = fem.mesh->GetElementTransformation(elemID);
T->SetIntPoint(&ip);
mfem::Vector current_x_phys(dim);
fem.mapping->GetPhysicalPoint(*T, ip, current_x_phys);
for (int i = 0; i < dim; ++i) {
residual(i) = current_x_phys(i) - x_phys_target(i);
}
if (constexpr double tol = 1e-12; residual.Norml2() < tol) {
return true;
}
fem.mapping->ComputeJacobian(*T, J_map);
mfem::CalcInverse(J_map, J_map_inv);
J_map_inv.Mult(residual, step);
double alpha = 1.0;
mfem::Vector x_ref_candidate(dim);
bool found_valid = false;
for (int ls = 0; ls < 8; ++ls) {
x_ref_candidate = x_ref;
x_ref_candidate.Add(-alpha, step);
P.SetCol(0, x_ref_candidate);
fem.mesh->FindPoints(P, elem_ids, ips, false);
if (elem_ids.Size() > 0 && elem_ids[0] >= 0) {
found_valid = true;
break;
}
alpha *= 0.5;
}
if (found_valid) {
x_ref = x_ref_candidate;
} else {
find_failures++;
if (find_failures > 10) return false;
if (double norm = x_ref.Norml2(); norm > 1e-15) {
x_ref *= 0.5 * RADIUS / norm;
} else {
x_ref = 0.0;
}
}
}
return false;
}
double EvalGridFunctionAtPoint(
const fem::FEM &fem,
const mfem::ParGridFunction &u,
const mfem::Vector &x,
const mapping::COORDINATE_SPACE vspace,
const mapping::COORDINATE_SPACE rspace
) {
mfem::Vector x_search;
if (vspace == mapping::COORDINATE_SPACE::PHYSICAL && fem.has_mapping()) {
GetReferencePoint(fem, x, x_search);
} else {
x_search = x;
}
mfem::Array<int> elem_ids;
mfem::Array<mfem::IntegrationPoint> ips;
mfem::DenseMatrix P(x_search.Size(), 1);
P.SetCol(0, x_search);
fem.mesh->FindPoints(P, elem_ids, ips, false);
double local_val = 0.0;
if (elem_ids.Size() > 0 && elem_ids[0] >= 0) {
const double val = u.GetValue(elem_ids[0], ips[0]);
if (rspace == mapping::COORDINATE_SPACE::PHYSICAL && !fem.has_mapping()) {
MFEM_ABORT("Physical evaluation mode requested but no mapping provided. Check domain bounds and mapping setup.");
}
local_val = val;
}
double global_val = 0.0;
MPI_Allreduce(&local_val, &global_val, 1, MPI_DOUBLE, MPI_MAX, fem.H1_fes->GetComm());
return global_val;
}
}

View File

@@ -0,0 +1,124 @@
module;
#include <mfem.hpp>
#include <expected>
module mean_field;
import :boundary.contexts;
namespace mean_field::utils {
DOMAINS operator|(
DOMAINS lhs,
DOMAINS rhs
) {
return static_cast<DOMAINS>(static_cast<uint8_t>(lhs) | static_cast<uint8_t>(rhs));
}
DOMAINS operator&(
DOMAINS lhs,
DOMAINS rhs
) {
return static_cast<DOMAINS>(static_cast<uint8_t>(lhs) & static_cast<uint8_t>(rhs));
}
void populate_element_mask(
const mfem::Mesh* mesh,
const DOMAINS domain,
mfem::Array<int> &mask
) {
const int max_attr = mesh->attributes.Max();
mask.SetSize(max_attr);
mask = 0;
if ((domain & DOMAINS::CORE) == DOMAINS::CORE && max_attr >= 1) {
mask[0] = 1;
}
if ((domain & DOMAINS::ENVELOPE) == DOMAINS::ENVELOPE && max_attr >= 2) {
mask[1] = 1;
}
if ((domain & DOMAINS::VACUUM) == DOMAINS::VACUUM && max_attr >= 3) {
mask[2] = 1;
}
}
void populate_domain_tdofs(
const mfem::ParFiniteElementSpace *fes,
const mfem::Array<int> &element_mask,
mfem::Array<int> &ess_tdof
) {
mfem::Array<int> vdof_marker(fes->GetVSize());
vdof_marker = 0;
for (int i = 0; i < fes->GetMesh()->GetNE(); i++) {
const int attr = fes->GetMesh()->GetAttribute(i);
if (element_mask[attr - 1]) {
mfem::Array<int> dofs;
fes->GetElementVDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++) {
int index = dofs[j];
if (index < 0) index = -1 - index;
vdof_marker[index] = 1;
}
}
}
fes->MarkerToList(vdof_marker, ess_tdof);
}
std::expected<boundary::Bounds, boundary::BoundsError> discover_bounds(
const mfem::Mesh *mesh,
const int vacuum_attr
) {
double local_min_r = std::numeric_limits<double>::max();
double local_max_r = -std::numeric_limits<double>::max();
bool found_vacuum = false;
for (int i = 0; i < mesh->GetNE(); ++i) {
if (mesh->GetAttribute(i) == vacuum_attr) {
found_vacuum = true;
mfem::Array<int> vertices;
mesh->GetElementVertices(i, vertices);
for (const int v: vertices) {
const double *coords = mesh->GetVertex(v);
double r = std::sqrt(coords[0] * coords[0] + coords[1] * coords[1] + coords[2] * coords[2]);
local_min_r = std::min(local_min_r, r);
local_max_r = std::max(local_max_r, r);
}
}
}
double global_min_r, global_max_r;
int global_found_vacuum;
int l_found = found_vacuum ? 1 : 0;
MPI_Comm comm = MPI_COMM_WORLD;
if (const auto *pmesh = dynamic_cast<const mfem::ParMesh *>(mesh)) {
comm = pmesh->GetComm();
}
MPI_Allreduce(&local_min_r, &global_min_r, 1, MPI_DOUBLE, MPI_MIN, comm);
MPI_Allreduce(&local_max_r, &global_max_r, 1, MPI_DOUBLE, MPI_MAX, comm);
MPI_Allreduce(&l_found, &global_found_vacuum, 1, MPI_INT, MPI_MAX, comm);
if (global_found_vacuum) {
return boundary::Bounds(global_min_r, global_max_r);
}
return std::unexpected(boundary::BoundsError::CANNOT_FIND_VACUUM);
}
int get_mesh_order(
const mfem::Mesh &mesh
) {
if (mesh.GetNodes() != nullptr) {
return mesh.GetNodes()->FESpace()->GetMaxElementOrder();
}
return 1;
}
}

View File

@@ -0,0 +1,4 @@
#pragma once
#include <mfem.hpp>
#include <stroid/stroid.h>

View File

@@ -0,0 +1,11 @@
#pragma once
#include <type_traits>
#if defined(_LIBCPP_VERSION)
namespace std {
template <class... Args>
struct __promote {
using type = double;
};
}
#endif

View File

@@ -0,0 +1,41 @@
module;
#include "mean_field.h"
export module mean_field:analysis.integral;
export import :fem;
export import :utils.domain;
export import :mapping.domain_mapper;
export import :mapping.types;
export namespace mean_field::analysis {
double domain_integrate_grid_function(
const fem::FEM &fem,
const mfem::GridFunction &gf,
utils::DOMAINS domain = utils::DOMAINS::ALL,
mapping::COORDINATE_SPACE coord_space = mapping::COORDINATE_SPACE::PHYSICAL
);
mfem::Vector get_com(
const fem::FEM &fem,
const mfem::GridFunction &rho
);
void conserve_mass(
const fem::FEM &fem,
mfem::GridFunction &rho,
double target_mass
);
double get_moment_of_inertia(
const fem::FEM &fem,
const mfem::GridFunction &rho
);
double get_mesh_volume(
const fem::FEM& fem,
mapping::COORDINATE_SPACE coordinate_space = mapping::COORDINATE_SPACE::PHYSICAL,
utils::DOMAINS domain = utils::DOMAINS::STELLAR
);
}

View File

@@ -0,0 +1,34 @@
module;
#include "mean_field.h"
export module mean_field:boundary.contexts;
export namespace mean_field::boundary {
struct BoundaryContext {
mfem::Array<int> inf_bounds;
mfem::Array<int> stellar_bounds;
};
enum class Boundaries : uint8_t {
STELLAR_SURFACE = 1,
INF_SURFACE = 2
};
int operator-(
Boundaries b,
const int a
) {
return static_cast<int>(static_cast<uint8_t>(b) - static_cast<uint8_t>(a));
}
struct Bounds {
double r_star_ref;
double r_inf_ref;
};
enum BoundsError : uint8_t {
CANNOT_FIND_VACUUM
};
}

View File

@@ -0,0 +1,95 @@
module;
#include <stroid/stroid.h>
#include <memory>
#include <mfem.hpp>
export module mean_field:fem;
export import :physics.contexts;
export import :boundary.contexts;
export import :mapping.domain_mapper;
export import :utils.misc;
export import :utils.user;
export import :quadrature.mfem;
export namespace mean_field::fem {
struct FEM {
stroid::StroidMesh smesh;
std::unique_ptr<mfem::ParMesh> mesh;
// =====================================
// 2. Finite Element Collections
// =====================================
// H1 (Continuous): For Gravitational Potential (Phi) and Velocity (v)
std::unique_ptr<mfem::FiniteElementCollection> H1_fec;
// L2 (Discontinuous): For Density (rho) to fix O-grid boundary scalloping
std::unique_ptr<mfem::FiniteElementCollection> L2_fec;
// H(div)/RT space for gravitational field
std::unique_ptr<mfem::RT_FECollection> RT_fec;
// =====================================
// 3. Finite Element Spaces
// =====================================
std::unique_ptr<mfem::ParFiniteElementSpace> H1_fes; // Scalar continuous (Gravity)
std::unique_ptr<mfem::ParFiniteElementSpace> Vec_H1_fes; // Vector continuous (Velocity field)
std::unique_ptr<mfem::ParFiniteElementSpace> L2_fes; // Scalar discontinuous (Density)
std::unique_ptr<mfem::ParFiniteElementSpace> RT_fes; // H(div)/RT space for gravitational field
// Preconditioning for Gravity
std::unique_ptr<mfem::ParLORDiscretization> H1_lor_disc;
const mfem::ParFiniteElementSpace *H1_lor_fes{nullptr};
// =====================================
// 4. Domain Mapping
// =====================================
std::unique_ptr<mapping::DomainMapper> mapping;
// =====================================
// 5. Global System Tracking
// =====================================
// [ Velocity | Density | Mapping Parameters (Surface) ]
mfem::Array<int> block_true_offsets;
mfem::Array<int> gravity_block_true_offsets;
// Essential Boundary Conditions for the fluid (e.g., surface stress-free)
mfem::Array<int> ess_v_tdofs;
// Elements entirely in the vacuum domain where fluid equations are not solved
mfem::Array<int> vacuum_tdof_rho;
mfem::Array<int> vacuum_tdof_v;
// =====================================
// 6. Multiphysics State & Integration
// =====================================
mfem::Vector com;
mfem::DenseMatrix Q;
int int_order{3};
std::unique_ptr<mfem::IntegrationRule> int_rule;
physics::GravityContext gravity_context;
boundary::BoundaryContext boundary_context;
std::unique_ptr<quadrature::RuleFactory> quadrature_factory;
// =====================================
// 7. Utilities
// =====================================
[[nodiscard]] bool okay() const {
return (mesh != nullptr) &&
(H1_fec != nullptr) && (L2_fec != nullptr) && (RT_fec != nullptr) &&
(H1_fes != nullptr) && (Vec_H1_fes != nullptr) && (L2_fes != nullptr) && (RT_fes != nullptr);
}
[[nodiscard]] bool has_mapping() const { return mapping != nullptr; }
};
FEM setup_fem(const std::string &filename, const utils::Args &args, int extra_refine = 0);
}

View File

@@ -0,0 +1,28 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.advection;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class AdvectionIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
explicit AdvectionIntegrator(const mapping::DomainMapper &map);
void AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) override;
void AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
const mapping::DomainMapper &m_map;
};
}

View File

@@ -0,0 +1,32 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.centrifugal;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class CentrifugalForceIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
CentrifugalForceIntegrator(const mapping::DomainMapper& map, const mfem::Vector& omega);
void SetOmega(const mfem::Vector& omega);
void AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) override;
void AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
const mapping::DomainMapper& m_map;
mfem::Vector m_omega;
};
}

View File

@@ -0,0 +1,28 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.coriolis;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class CoriolisIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
CoriolisIntegrator(const mapping::DomainMapper& map, const mfem::Vector& omega);
void AssembleElementVector(const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec) override;
void AssembleElementGrad(const mfem::Array<const mfem::FiniteElement*> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats) override;
private:
const mapping::DomainMapper& m_map;
mfem::Vector m_omega;
mfem::DenseMatrix m_omega_mat;
};
}

View File

@@ -0,0 +1,32 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.gravity;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class GravityForceIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
GravityForceIntegrator(const mapping::DomainMapper& map, const mfem::GridFunction& phi);
void SetPotential(const mfem::GridFunction& phi);
void AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) override;
void AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
const mapping::DomainMapper& m_map;
const mfem::GridFunction* m_phi;
};
}

View File

@@ -0,0 +1,62 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.mass_continuity;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class ContinuityVolumeIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
explicit ContinuityVolumeIntegrator(const mapping::DomainMapper& map);
void AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) override;
void AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
const mapping::DomainMapper& m_map;
};
class ContinuityFaceIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
explicit ContinuityFaceIntegrator(const mapping::DomainMapper& map);
void AssembleFaceVector(
const mfem::Array<const mfem::FiniteElement *> &el1,
const mfem::Array<const mfem::FiniteElement *> &el2,
mfem::FaceElementTransformations &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvect
) override;
void AssembleFaceGrad(
const mfem::Array<const mfem::FiniteElement *> &el1,
const mfem::Array<const mfem::FiniteElement *> &el2,
mfem::FaceElementTransformations &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
static bool skip_face(const mfem::FaceElementTransformations& Tr);
static double compute_u_n(
const mfem::Vector& v_dofs,
const mfem::Vector& shape_v_minus,
const mfem::Vector& n_unit,
int dof_v_minus,
int dim
);
private:
const mapping::DomainMapper& m_map;
};
}

View File

@@ -0,0 +1,168 @@
module;
#include <mfem.hpp>
#include "xad_promote_polyfill.h"
#include <XAD/XAD.hpp>
export module mean_field:integrators.pressure_gradient;
import :mapping.domain_mapper;
import :utils.misc;
export namespace mean_field::integrators {
template <utils::is_xad EOS_T>
class PressureGradientIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
PressureGradientIntegrator(const mapping::DomainMapper& map, utils::EOS_P<EOS_T> eos);
void AssembleElementVector(const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec) override;
void AssembleElementGrad(const mfem::Array<const mfem::FiniteElement*> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats) override;
private:
const mapping::DomainMapper& m_map;
utils::EOS_P<EOS_T> m_eos;
};
template <utils::is_xad EOS_T>
PressureGradientIntegrator<EOS_T>::PressureGradientIntegrator(
const mapping::DomainMapper& map,
utils::EOS_P<EOS_T> eos
) : m_map(map), m_eos(std::move(eos)) {}
template <utils::is_xad EOS_T>
void PressureGradientIntegrator<EOS_T>::AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) {
if (utils::is_vacuum(Tr, elvec)) {
return;
}
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& rho_dofs = *elfun[1];
mfem::Vector& r_v = *elvec[0];
r_v.SetSize(dof_v * dim);
r_v = 0.0;
if (elvec[1]) {
elvec[1]->SetSize(dof_rho);
*elvec[1] = 0.0;
}
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
mfem::Vector shape_rho(dof_rho);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
fe_rho->CalcShape(ip, shape_rho);
double rho_val = 0.0;
for (int i = 0; i < dof_rho; ++i) rho_val += rho_dofs(i) * shape_rho(i);
// Guard against negative density from Newton solver overshoots
if (rho_val < 1e-15) rho_val = 1e-15;
// Evaluate the exact Equation of State Pressure
EOS_T x_rho = rho_val;
double P_val = m_eos(x_rho, EOS_T(0.0)).value();
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
r_v(i + c * dof_v) -= dshape_v_phys(i, c) * P_val * weight;
}
}
}
}
template <utils::is_xad EOS_T>
void PressureGradientIntegrator<EOS_T>::AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement*> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) {
const mfem::FiniteElement* fe_v = el[0];
const mfem::FiniteElement* fe_rho = el[1];
const int dof_v = fe_v->GetDof();
const int dof_rho = fe_rho->GetDof();
const int dim = Tr.GetSpaceDim();
const mfem::Vector& rho_dofs = *elfun[1];
mfem::DenseMatrix* dv_dv = elmats(0, 0);
mfem::DenseMatrix* dv_drho = elmats(0, 1);
if (dv_dv) *dv_dv = 0.0;
if (dv_drho) *dv_drho = 0.0;
if (!dv_drho) return;
mfem::DenseMatrix dshape_v_ref(dof_v, dim), dshape_v_phys(dof_v, dim);
mfem::Vector shape_rho(dof_rho);
const mfem::IntegrationRule* ir = &mfem::IntRules.Get(fe_v->GetGeomType(), 2 * fe_v->GetOrder());
for (int q = 0; q < ir->GetNPoints(); ++q) {
using Scalar = EOS_T::value_type;
xad::Tape<Scalar> tape;
const mfem::IntegrationPoint& ip = ir->IntPoint(q);
Tr.SetIntPoint(&ip);
auto [J_inv, detJ, weight] = m_map.GetQuadratureContext(Tr, ip);
fe_v->CalcDShape(ip, dshape_v_ref);
mfem::Mult(dshape_v_ref, J_inv, dshape_v_phys);
fe_rho->CalcShape(ip, shape_rho);
EOS_T x_rho(0.0);
tape.registerInput(x_rho);
tape.newRecording();
for (int i = 0; i < dof_rho; ++i) {
x_rho += rho_dofs(i) * shape_rho(i);
}
if (x_rho < 1e-15) x_rho = EOS_T(1e-15);
EOS_T x_P = m_eos(x_rho, EOS_T(0.0));
tape.registerOutput(x_P);
x_P.setAdjoint(1.0);
tape.computeAdjoints();
double dP_drho = x_rho.getAdjoint();
double debug_K = 1.5;
double debug_n = 3.0;
double analytic_dp = debug_K * (1.0 + 1.0 / debug_n) * std::pow(xad::value(x_rho), 1.0 / debug_n);
double ad_err = std::abs(dP_drho - analytic_dp);
for (int i = 0; i < dof_v; ++i) {
for (int c = 0; c < dim; ++c) {
int row = i + c * dof_v;
for (int j = 0; j < dof_rho; ++j) {
int col = j;
double term = dshape_v_phys(i, c) * dP_drho * shape_rho(j);
(*dv_drho)(row, col) -= term * weight;
}
}
}
}
}
}

View File

@@ -0,0 +1,32 @@
module;
#include <mfem.hpp>
export module mean_field:integrators.viscosity;
import :mapping.domain_mapper;
export namespace mean_field::integrators {
class ViscosityIntegrator : public mfem::BlockNonlinearFormIntegrator {
public:
ViscosityIntegrator(const mapping::DomainMapper& map, double mu, int quad_boost);
void SetMu(const double mu);
void AssembleElementVector(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array<mfem::Vector *> &elvec
) override;
void AssembleElementGrad(
const mfem::Array<const mfem::FiniteElement *> &el,
mfem::ElementTransformation &Tr,
const mfem::Array<const mfem::Vector *> &elfun,
const mfem::Array2D<mfem::DenseMatrix *> &elmats
) override;
private:
const mapping::DomainMapper& m_map;
double m_mu;
int m_quad_boost;
};
}

View File

@@ -0,0 +1,95 @@
module;
#include "mean_field.h"
export module mean_field:mapping.coefficients;
export import :mapping.domain_mapper;
export import :mapping.types;
export namespace mean_field::mapping {
class MappedScalarCoefficient : public mfem::Coefficient {
public:
MappedScalarCoefficient(
const DomainMapper &map,
mfem::Coefficient &coeff,
COORDINATE_SPACE coord_space = COORDINATE_SPACE::PHYSICAL
);
double Eval(
mfem::ElementTransformation &T,
const mfem::IntegrationPoint &ip
) override;
private:
static double eval_at_point(
mfem::Coefficient &c,
mfem::ElementTransformation &T,
const mfem::IntegrationPoint &ip
);
private:
const DomainMapper &m_map;
mfem::Coefficient &m_coeff;
COORDINATE_SPACE m_coord_space;
};
class MappedDiffusionCoefficient : public mfem::MatrixCoefficient {
public:
MappedDiffusionCoefficient(
const DomainMapper &map,
mfem::Coefficient &sigma,
int dim
);
MappedDiffusionCoefficient(
const DomainMapper &map,
mfem::MatrixCoefficient &sigma
);
void Eval(mfem::DenseMatrix &K, mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) override;
private:
const DomainMapper &m_map;
mfem::Coefficient *m_scalar;
mfem::MatrixCoefficient *m_tensor;
};
class MappedVectorCoefficient : public mfem::VectorCoefficient {
public:
MappedVectorCoefficient(
const DomainMapper &map,
mfem::VectorCoefficient &coeff
);
void Eval(mfem::Vector &V, mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) override;
private:
const DomainMapper &m_map;
mfem::VectorCoefficient &m_coeff;
};
class PhysicalPositionFunctionCoefficient : public mfem::Coefficient {
public:
using Func = std::function<double(const mfem::Vector &x)>;
PhysicalPositionFunctionCoefficient(
const DomainMapper &map,
Func f
);
double Eval(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) override;
private:
Func m_f;
const DomainMapper &m_map;
};
class MappedHDivMassCoefficient final : public mfem::MatrixCoefficient {
public:
MappedHDivMassCoefficient(const DomainMapper& map, const int dim);
void Eval(mfem::DenseMatrix& matrix, mfem::ElementTransformation& transformation, const mfem::IntegrationPoint& integration_point) override;
private:
const DomainMapper& m_map;
};
}

View File

@@ -0,0 +1,103 @@
module;
#include "mean_field.h"
export module mean_field:mapping.domain_mapper;
export namespace mean_field::mapping {
class DomainMapper {
public:
struct VolumeQuadratureContext {
mfem::DenseMatrix J_inv;
double detJ;
double weight;
};
struct FaceQuadratureContext {
mfem::Vector normal;
double ds;
double v_dot_n_scale;
};
public:
explicit DomainMapper(const double r_star_ref, const double r_inf_ref);
explicit DomainMapper(const mfem::GridFunction &d, const double r_star_ref, const double r_inf_ref);
[[nodiscard]] bool is_vacuum(const mfem::ElementTransformation &T) const;
void SetDisplacement(const mfem::GridFunction &d);
[[nodiscard]] bool IsIdentity() const;
void ResetDisplacement();
void ComputeJacobian(mfem::ElementTransformation &T, mfem::DenseMatrix &J) const;
double ComputeDetJ(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) const;
void ComputeMappedDiffusionTensor(mfem::ElementTransformation &T, mfem::DenseMatrix &D) const;
void ComputeInverseJacobian(mfem::ElementTransformation &T, mfem::DenseMatrix &JInv) const;
VolumeQuadratureContext GetQuadratureContext(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip) const;
FaceQuadratureContext GetFaceQuadratureContext(mfem::FaceElementTransformations &T, const mfem::IntegrationPoint &ip) const;
void GetPhysicalPoint(mfem::ElementTransformation &T, const mfem::IntegrationPoint &ip, mfem::Vector &x_phys) const;
void GetVectorValue(const int i, const mfem::IntegrationPoint &ip, mfem::Vector &val) const;
[[nodiscard]] const mfem::GridFunction *GetDisplacement() const;
[[nodiscard]] double GetPhysInfRadius() const;
[[nodiscard]] size_t GetCacheHits() const;
[[nodiscard]] size_t GetCacheMisses() const;
[[nodiscard]] double GetCacheHitRate() const;
void ResetCacheStats() const;
private:
void InitAllScratchSpaces() const;
void ApplyKelvinMapping(const mfem::Vector &x_ref, mfem::Vector &x_phys) const;
void ComputeKelvinJacobian(const mfem::Vector &x_ref, const mfem::Vector &x_disp, const mfem::DenseMatrix &J_D, mfem::DenseMatrix &J) const;
void InvalidateCache() const;
void UpdateElementCache(const mfem::ElementTransformation &T) const;
private:
const mfem::GridFunction *m_d;
std::unique_ptr<mfem::GridFunction> m_internal_d;
const int m_dim{3};
const int m_vacuum_attr{3};
const double m_r_star_ref{1.0};
const double m_r_inf_ref{2.0};
const double m_xi_clamp{0.9999};
mutable int m_cached_elem_id{-1};
mutable int m_cached_elem_type{mfem::ElementTransformation::ELEMENT};
mutable const mfem::FiniteElement *m_fe{nullptr};
mutable mfem::Vector m_elem_dofs;
mutable mfem::DenseMatrix m_dof_mat;
mutable mfem::DenseMatrix m_dshape;
mutable mfem::Vector m_shape;
mutable size_t m_cache_hits{0};
mutable size_t m_cache_misses{0};
mutable mfem::DenseMatrix m_J_D;
mutable mfem::DenseMatrix m_J_temp;
mutable mfem::DenseMatrix m_JInv_temp;
mutable mfem::Vector m_x_ref;
mutable mfem::Vector m_x_disp;
mutable mfem::Vector m_d_val;
};
}

View File

@@ -0,0 +1,10 @@
module;
#include <cstdint>
export module mean_field:mapping.types;
namespace mean_field::mapping {
enum class COORDINATE_SPACE : uint8_t {
PHYSICAL,
REFERENCE
};
}

View File

@@ -0,0 +1,21 @@
export module mean_field;
export import :fem;
export import :utils.misc;
export import :utils.user;
export import :utils.domain;
export import :physics.gravity;
export import :physics.contexts;
export import :boundary.contexts;
export import :analysis.integral;
export import :mapping.domain_mapper;
export import :mapping.coefficients;
export import :integrators.advection;
export import :integrators.centrifugal;
export import :integrators.gravity;
export import :integrators.coriolis;
export import :integrators.mass_continuity;
export import :integrators.pressure_gradient;
export import :integrators.viscosity;
export import :quadrature.policy;
export import :quadrature.mfem;

View File

@@ -0,0 +1,28 @@
module;
#include <mfem.hpp>
export module mean_field:physics.contexts;
export import :mapping.coefficients;
export namespace mean_field::physics {
struct GravityContext {
std::unique_ptr<mfem::ParBilinearForm> m_form;
std::unique_ptr<mfem::ParMixedBilinearForm> b_form;
std::unique_ptr<mfem::BlockOperator> block_A;
std::unique_ptr<mfem::Solver> prec_M;
std::unique_ptr<mfem::HypreBoomerAMG> prec_Phi;
std::unique_ptr<mfem::BlockDiagonalPreconditioner> block_prec;
std::unique_ptr<mfem::MINRESSolver> minres;
mfem::Array<int> stellar_mask;
std::unique_ptr<mfem::TransposeOperator> BT;
std::unique_ptr<mfem::HypreParMatrix> Schur;
std::unique_ptr<mfem::MatrixCoefficient> mapped_hdiv_mass_coeff;
};
}

View File

@@ -0,0 +1,45 @@
module;
#include <mfem.hpp>
export module mean_field:physics.gravity;
export import :fem;
export namespace mean_field::physics {
struct GravitySolution {
mfem::ParGridFunction gradPhi;
mfem::ParGridFunction phi;
explicit GravitySolution(fem::FEM& fem): gradPhi(fem.RT_fes.get()), phi(fem.L2_fes.get()) {}
};
GravitySolution grav_potential(
fem::FEM &f,
const utils::Args &args,
const mfem::GridFunction &rho,
bool phi_warm = false
);
mfem::GridFunction get_potential(
fem::FEM &fem,
const utils::Args &args,
const mfem::GridFunction &rho,
bool warm = false
);
mfem::DenseMatrix compute_quadrupole_moment_tensor(
const fem::FEM &fem,
const mfem::GridFunction &rho,
const mfem::Vector &com
);
double l2_multipole_potential(
const fem::FEM &fem,
double total_mass,
const mfem::Vector &phys_x
);
void update_stiffness_matrix(fem::FEM &fem);
}

View File

@@ -0,0 +1,9 @@
module;
#include <mfem.hpp>
export module mean_field:physics.solid_body;
export import :fem;
export namespace mean_field::physics {
double compute_moment_of_inertia(const fem::FEM &fem, const mfem::GridFunction &rho_ref);
}

View File

@@ -0,0 +1,198 @@
module;
#include <mfem.hpp>
#include <utility>
export module mean_field:quadrature.mfem;
export import :quadrature.policy;
export namespace mean_field::quadrature {
struct MfemRule {
Resolution resolution;
const mfem::IntegrationRule* integration_rule;
};
class RuleFactory {
public:
explicit RuleFactory(
Policy policy
);
MfemRule get(
const Query& query,
mfem::Geometry::Type geometry
) const;
MfemRule get(
Term term,
QuadratureRole role,
mfem::Geometry::Type geometry,
int base_order,
utils::DOMAINS domain = utils::DOMAINS::ALL,
MappingKind mapping = MappingKind::none
) const;
Resolution configure_gravity_hdiv_mass(
mfem::VectorFEMassIntegrator& integrator,
QuadratureRole role,
const mfem::FiniteElement& element,
const mfem::ElementTransformation& transformation,
utils::DOMAINS domain = utils::DOMAINS::ALL,
MappingKind mapping = MappingKind::none
) const;
Resolution configure_gravity_divergence(
mfem::VectorFEDivergenceIntegrator& integrator,
QuadratureRole role,
const mfem::FiniteElement& trial_element,
const mfem::FiniteElement& test_element,
const mfem::ElementTransformation& transformation,
utils::DOMAINS domain = utils::DOMAINS::ALL,
MappingKind mapping = MappingKind::none
) const;
Resolution configure_gravity_boundary(
mfem::VectorFEBoundaryFluxLFIntegrator& integrator,
QuadratureRole role,
const mfem::FiniteElement& boundary_element,
utils::DOMAINS domain = utils::DOMAINS::VACUUM,
MappingKind mapping = MappingKind::none
) const;
Resolution configure_gravity_source(
mfem::DomainLFIntegrator& integrator,
QuadratureRole role,
const mfem::FiniteElement& test_element,
const mfem::ElementTransformation& transformation,
int coefficient_order,
utils::DOMAINS domain = utils::DOMAINS::STELLAR,
MappingKind mapping = MappingKind::none
) const;
template<typename IntegratorType>
Resolution configure(
IntegratorType& integrator,
Term term,
QuadratureRole role,
mfem::Geometry::Type geometry,
int base_order,
utils::DOMAINS domain = utils::DOMAINS::ALL,
MappingKind mapping = MappingKind::none
) const;
private:
Policy policy;
};
RuleFactory::RuleFactory(Policy policy) : policy(std::move(policy)) {}
MfemRule RuleFactory::get(
const Query& query,
const mfem::Geometry::Type geometry
) const {
const Resolution resolution = policy.resolve(query);
const mfem::IntegrationRule& integration_rule = mfem::IntRules.Get(geometry, resolution.order);
return {.resolution = resolution, .integration_rule = &integration_rule};
}
MfemRule RuleFactory::get(
const Term term,
const QuadratureRole role,
const mfem::Geometry::Type geometry,
const int base_order,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
Query query{.term = term};
query.domain = domain;
query.mapping = mapping;
query.role = role;
query.base_order = base_order;
return get(query, geometry);
}
Resolution RuleFactory::configure_gravity_hdiv_mass(
mfem::VectorFEMassIntegrator& integrator,
const QuadratureRole role,
const mfem::FiniteElement& element,
const mfem::ElementTransformation& transformation,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
const int base_order = 2 * element.GetOrder() + transformation.OrderW();
return configure(integrator, Term::gravity_hdiv_mass, role, element.GetGeomType(), base_order, domain, mapping);
}
Resolution RuleFactory::configure_gravity_divergence(
mfem::VectorFEDivergenceIntegrator& integrator,
const QuadratureRole role,
const mfem::FiniteElement& trial_element,
const mfem::FiniteElement& test_element,
const mfem::ElementTransformation& transformation,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
const Query query = {
.term = Term::gravity_divergence,
.role = role,
.domain = domain,
.mapping = mapping,
.trial_order = trial_element.GetOrder(),
.test_order = test_element.GetOrder(),
.geometry_weight_order = transformation.OrderW()
};
const auto [resolution, integration_rule] = get(query, trial_element.GetGeomType());
integrator.SetIntegrationRule(*integration_rule);
return resolution;
}
Resolution RuleFactory::configure_gravity_boundary(
mfem::VectorFEBoundaryFluxLFIntegrator& integrator,
const QuadratureRole role,
const mfem::FiniteElement& boundary_element,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
const int base_order = 2 * boundary_element.GetOrder();
return configure(integrator, Term::gravity_boundary, role, boundary_element.GetGeomType(), base_order, domain, mapping);
}
Resolution RuleFactory::configure_gravity_source(
mfem::DomainLFIntegrator& integrator,
const QuadratureRole role,
const mfem::FiniteElement& test_element,
const mfem::ElementTransformation& transformation,
const int coefficient_order,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
const Query query = {
.term = Term::gravity_source,
.role = role,
.domain = domain,
.mapping = mapping,
.test_order = test_element.GetOrder(),
.coefficient_order = coefficient_order,
.geometry_weight_order = transformation.OrderW()
};
const auto [resolution, integration_rule] = get(query, test_element.GetGeomType());
integrator.SetIntegrationRule(*integration_rule);
return resolution;
}
template<typename IntegratorType>
Resolution RuleFactory::configure(
IntegratorType& integrator,
const Term term,
const QuadratureRole role,
const mfem::Geometry::Type geometry,
const int base_order,
const utils::DOMAINS domain,
const MappingKind mapping
) const {
const auto [resolution, integration_rule] = get(term, role, geometry, base_order, domain, mapping);
integrator.SetIntegrationRule(*integration_rule);
return resolution;
}
}

View File

@@ -0,0 +1,256 @@
module;
#include <algorithm>
#include <optional>
#include <stdexcept>
#include <utility>
export module mean_field:quadrature.policy;
export import :utils.misc;
export namespace mean_field::quadrature {
enum class Term {
gravity_hdiv_mass,
gravity_divergence,
gravity_source,
gravity_boundary,
density_projection,
mass_conservation,
center_of_mass,
quadrupole,
gravitational_energy,
virial,
error_norm
};
enum class QuadratureRole {
discretization,
preconditioner,
diagnostic,
projection
};
enum class MappingKind {
none,
affine,
general,
kelvin
};
enum class Mode {
fast,
production,
reference,
convergence
};
struct RuleControl {
std::optional<int> fixed_order;
int boost = 0;
};
struct RoleControls {
RuleControl discretization;
RuleControl preconditioner;
RuleControl diagnostic;
RuleControl projection;
};
struct RuleSet {
RuleControl gravity_hdiv_mass;
RuleControl gravity_divergence;
RuleControl gravity_source;
RuleControl gravity_boundary;
RuleControl density_projection;
RuleControl mass_conservation;
RuleControl center_of_mass;
RuleControl quadrupole;
RuleControl gravitational_energy;
RuleControl virial;
RuleControl error_norm;
RoleControls roles;
RuleControl fallback;
};
struct Query {
Term term;
QuadratureRole role = QuadratureRole::discretization;
utils::DOMAINS domain = utils::DOMAINS::ALL;
MappingKind mapping = MappingKind::none;
int trial_order = 0;
int test_order = 0;
int coefficient_order = 0;
int geometry_weight_order = 0;
std::optional<int> base_order;
};
struct Resolution {
int base_order;
int boost;
int order;
bool used_fixed_order;
};
struct QuadratureTermOptions {
std::optional<int> fixed_order;
int additional_boost = 0;
};
struct QuadratureManifestOptions {
bool enabled = false;
bool include_repeated_queries = false;
std::optional<std::string> output_file;
};
struct QuadratureValidationOptions {
bool require_explicit_base_order = false;
bool require_explicit_mfem_rule = false;
bool reject_negative_boosts = true;
bool report_unused_overrides = true;
};
struct QuadratureRoleOptions {
QuadratureTermOptions discretization;
QuadratureTermOptions preconditioner;
QuadratureTermOptions diagnostic;
QuadratureTermOptions projection;
};
struct QuadratureOptions {
Mode mode = Mode::production;
int global_boost = 0;
std::optional<int> fallback_fixed_order;
QuadratureTermOptions gravity_hdiv_mass;
QuadratureTermOptions gravity_divergence;
QuadratureTermOptions gravity_source;
QuadratureTermOptions gravity_boundary;
QuadratureTermOptions density_projection;
QuadratureTermOptions mass_conservation;
QuadratureTermOptions center_of_mass;
QuadratureTermOptions quadrupole;
QuadratureTermOptions gravitational_energy;
QuadratureTermOptions virial;
QuadratureTermOptions error_norm;
QuadratureRoleOptions roles;
std::vector<int> convergence_boosts = {0, 2, 4};
QuadratureManifestOptions manifest;
QuadratureValidationOptions validation;
};
RuleSet make_rule_set(Mode mode, int global_boost = 0);
class Policy {
public:
explicit Policy(RuleSet rule_set);
Resolution resolve(const Query& query) const;
private:
const RuleControl& get_control(Term term) const;
static int compute_base_order(const Query& query) ;
const RuleControl& get_role_control(QuadratureRole role) const;
RuleSet rule_set;
};
RuleSet make_rule_set(const Mode mode, const int global_boost) {
RuleSet rule_set;
switch (mode) {
case Mode::fast:
case Mode::production:
case Mode::convergence:
rule_set.fallback.boost = global_boost;
break;
case Mode::reference:
rule_set.fallback.boost = global_boost + 8;
break;
}
return rule_set;
}
Policy::Policy(RuleSet rule_set) : rule_set(std::move(rule_set)) {}
Resolution Policy::resolve(const Query& query) const {
const int base_order = compute_base_order(query);
const RuleControl& term_control = get_control(query.term);
const RuleControl& role_control = get_role_control(query.role);
std::optional<int> fixed_order;
if (term_control.fixed_order.has_value()) {
fixed_order = term_control.fixed_order;
} else if (role_control.fixed_order.has_value()) {
fixed_order = role_control.fixed_order;
} else {
fixed_order = rule_set.fallback.fixed_order;
}
if (fixed_order.has_value()) {
if (*fixed_order < 0) {
throw std::invalid_argument("Quadrature fixed order cannot be negative.");
}
return {.base_order = base_order, .boost = 0, .order = *fixed_order, .used_fixed_order = true};
}
const int boost = rule_set.fallback.boost + role_control.boost + term_control.boost;
const int order = base_order + boost;
if (order < 0) {
throw std::invalid_argument("Resolved quadrature order cannot be negative.");
}
return {.base_order = base_order, .boost = boost, .order = order, .used_fixed_order = false};
}
const RuleControl& Policy::get_control(const Term term) const {
switch (term) {
case Term::gravity_hdiv_mass: return rule_set.gravity_hdiv_mass;
case Term::gravity_divergence: return rule_set.gravity_divergence;
case Term::gravity_source: return rule_set.gravity_source;
case Term::gravity_boundary: return rule_set.gravity_boundary;
case Term::density_projection: return rule_set.density_projection;
case Term::mass_conservation: return rule_set.mass_conservation;
case Term::center_of_mass: return rule_set.center_of_mass;
case Term::quadrupole: return rule_set.quadrupole;
case Term::gravitational_energy: return rule_set.gravitational_energy;
case Term::virial: return rule_set.virial;
case Term::error_norm: return rule_set.error_norm;
}
throw std::logic_error("Unknown quadrature term.");
}
int Policy::compute_base_order(const Query& query) {
if (query.base_order.has_value()) {
if (*query.base_order < 0) {
throw std::invalid_argument("Quadrature base order cannot be negative.");
}
return *query.base_order;
}
if (query.trial_order < 0 || query.test_order < 0 || query.coefficient_order < 0 || query.geometry_weight_order < 0) {
throw std::invalid_argument("Quadrature query orders cannot be negative.");
}
int trial_order = query.trial_order;
if (query.term == Term::gravity_divergence) {
trial_order = std::max(0, trial_order - 1);
}
return trial_order + query.test_order + query.coefficient_order + query.geometry_weight_order;
}
const RuleControl& Policy::get_role_control(const QuadratureRole role) const {
switch (role) {
case QuadratureRole::discretization: return rule_set.roles.discretization;
case QuadratureRole::preconditioner: return rule_set.roles.preconditioner;
case QuadratureRole::diagnostic: return rule_set.roles.diagnostic;
case QuadratureRole::projection: return rule_set.roles.projection;
}
throw std::logic_error("Unknown quadrature role.");
}
}

View File

@@ -0,0 +1,24 @@
module;
#include <mfem.hpp>
export module mean_field:utils.domain;
export import :fem;
export import :mapping.domain_mapper;
export import :boundary.contexts;
export namespace mean_field::utils {
bool get_reference_point(
const fem::FEM &fem,
const mfem::Vector &x_phys_target,
mfem::Vector &x_ref
);
double eval_grid_function_at_point(
const fem::FEM &fem,
const mfem::GridFunction &u,
const mfem::Vector &x,
mapping::COORDINATE_SPACE vspace = mapping::COORDINATE_SPACE::REFERENCE,
mapping::COORDINATE_SPACE rspace = mapping::COORDINATE_SPACE::PHYSICAL
);
}

View File

@@ -0,0 +1,101 @@
module;
#include <string_view>
#include <functional>
#include <expected>
#include <mfem.hpp>
#include "xad_promote_polyfill.h"
#include <XAD/XAD.hpp>
export module mean_field:utils.misc;
import :boundary.contexts;
export namespace mean_field::utils {
constexpr double APPROX_MAX_ACCEPTABLE_POTENTIAL_ERROR_SI_BURNING = 1e-4;
bool is_vacuum(const mfem::ElementTransformation &Tr, mfem::Array<mfem::Vector*> elvec) {
if (Tr.Attribute == 3) {
const int size_elvec = elvec.Size();
for (int i = 0; i < size_elvec; i++) {
if (elvec[i]) {
*elvec[i] = 0.0;
}
}
return true;
}
return false;
}
constexpr std::string_view ANSI_GREEN = "\033[32m";
constexpr std::string_view ANSI_RED = "\033[31m";
constexpr std::string_view ANSI_YELLOW = "\033[33m";
constexpr std::string_view ANSI_BLUE = "\033[34m";
constexpr std::string_view ANSI_MAGENTA = "\033[35m";
constexpr std::string_view ANSI_CYAN = "\033[36m";
constexpr std::string_view ANSI_RESET = "\033[0m";
constexpr std::string_view ANSI_BCYAN = "\033[1;36m";
constexpr double G = 1.0;
constexpr double MASS = 1.0;
constexpr double RADIUS = 1.0;
[[maybe_unused]] constexpr char HOST[10] = "localhost";
[[maybe_unused]] constexpr int PORT = 19916;
template<typename T>
concept is_xad =
std::is_same_v<T, xad::AReal<long double> >
|| std::is_same_v<T, xad::AReal<double> >
|| std::is_same_v<T, xad::AReal<float> >;
template<typename T>
concept is_real = std::is_floating_point_v<T> || is_xad<T>;
template<is_real T>
using EOS_P = std::function<T(const T& rho, const T& temp)>;
enum class DOMAINS : uint8_t {
CORE = 1 << 0,
ENVELOPE = 1 << 1,
VACUUM = 1 << 2,
STELLAR = CORE | ENVELOPE,
ALL = CORE | ENVELOPE | VACUUM
};
DOMAINS operator|(
DOMAINS lhs,
DOMAINS rhs
);
DOMAINS operator&(
DOMAINS lhs,
DOMAINS rhs
);
void populate_element_mask(
const mfem::Mesh* mesh,
DOMAINS domain,
mfem::Array<int> &mask
);
void populate_domain_tdofs(
const mfem::ParFiniteElementSpace *fes,
const mfem::Array<int> &element_mask,
mfem::Array<int> &ess_tdof
);
std::expected<boundary::Bounds, boundary::BoundsError> discover_bounds(
const mfem::Mesh *mesh,
int vacuum_attr
);
int get_mesh_order(
const mfem::Mesh &mesh
);
}

View File

@@ -0,0 +1,36 @@
module;
#include <string>
export module mean_field:utils.user;
export import :quadrature.policy;
export namespace mean_field::utils {
struct potential {
double rtol;
double atol;
int max_iters;
};
struct rot {
bool enabled;
double omega;
double L;
};
struct Args {
std::string mesh_file;
potential p{};
rot r{};
bool verbose{};
double index{};
double mass{};
double c{};
int quad_boost{0};
int max_iters{};
double tol{};
quadrature::QuadratureOptions quadrature{};
};
}

50
readme.md Normal file
View File

@@ -0,0 +1,50 @@
# mean_field C++ module
## Emily M. Boudreaux
### July 15, 2026
### Dartmouth College
> Funded by the European Research Council: No. 101071505: 4D-STAR
This is a simple module testing the numerical implementation of mean_field eqautions of stellar structure in 3D using
Finite Elements.
This module is not intended for scientific use; rather, this will inform latter development of SERiF
# Key Goals
- Validation of discritization, truncation, and projection errors in MFEM in the context of pulsation mode identification. More specifically, we aim to confirm that a solution to the mean field equations may be found on a reasonably sized and ordered mesh such that the uncertainties introduced into mode identification by our model are below the order of accuracy of the forthcoming PLATO instrument.
- Further, we aim to validate that, when solved with a polytropic equation of state, a model in this framework can virialize to within one part in 10^6
- We aim to develope numerical instrumentation which will be incorporated into SERiF including, but not limited to, preconditioners, integrators, and operators
- We aim to develope utility infrastructure which will be incorporated into SERiF including, but not limited to, quadrature boost policies, domain mapping, and user experience tools.
# Current Status [as of July 15, 2026]
- Integrators for all mean field equations have been written. In other code these have been validated as self-consistent and consistent with analytic solutions generated with symbolic algebra tools. These tests will be incorporated into this module
- Gravitational Potential calculations have been rigorously tested for a number of cases including uniform spherical densities, polynomial spherical densities, rational spherical densities, uniform ellipsoidal densities, and rational ellipsoidal densities. These potentials only apply the density profile and the potential at infinity boundary condition
- We have shown that we can reach sufficient self-consistency and accuracy with the gravitational field such that the gravitational field representation will not prevent us achiveing the required virial ratio or mode identification accuracy.
# Building
Unlike the rest of the SERiF ecosystem this project is built with CMake (due to some experimentation with C++ modules, which are not well supported by meson). Note that
this project is developed for internal 4D-STAR testing and has not been developed with the intention of being portable. Numerous packages are required to be preinstalled
and no testing has been done to confirm if this works over a variety of targets. Broadly one must install
- stroid
- CLI11
- mfem (with MPI, Hypre, and UMFPack)
- libconfig
- cmake
- a recent version of clang or gcc which supports modules (note the default clang on mac will not work, you must use homebrew clang)
- ninja
- cmake
once those are installed then the following commands will in theory build mean_field
```bash
mkdir build
cd build & cmake .. -Gninja && ninja
./build/tests
```
should you wish to build this and you run into issues (as you likely will) you are welcome to email Emily Boudreaux (emily.boudreaux@dartmouth.edu); however, maintenance and support of this module
are not guaranteed. If SERiF has been released when you are reading this documentation we encourage you to look for that project on the 4D-STAR webpage (https://4d-star.org) as it inherits any and all scientific merit from this exploratory project.
# Funding
> 4D-STAR is funded by European Research Council (ERC) under the Horizon Europe programme (Synergy Grant agreement No. 101071505: 4D-STAR). Work for this project is funded by the European Union. Views and opinions expressed are however those of the author(s) only and do not necessarily reflect those of the European Union or the European Research Council.

165507
sandbox.smesh Normal file

File diff suppressed because it is too large Load Diff

25
tests/geometry/volume.cpp Normal file
View File

@@ -0,0 +1,25 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <catch2/benchmark/catch_benchmark.hpp>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <mfem.hpp>
#include <mpi.h>
import mean_field;
import test_helpers;
using namespace mean_field;
TEST_CASE("STROID Volume vs sphere", tags::geometry & tags::volume) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
const double analytic_vol = (4.0 / 3.0) * M_PI * std::pow(utils::RADIUS, 3);
const double stroid_vol = analysis::get_mesh_volume(f);
double s = analytic_vol / stroid_vol;
CHECK_THAT(stroid_vol, Catch::Matchers::WithinRel(analytic_vol, 1e-6));
}

600
tests/physics/gravity.cpp Normal file
View File

@@ -0,0 +1,600 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <algorithm>
#include <cmath>
#include <memory>
#include <cassert>
#include <boost/math/quadrature/gauss_kronrod.hpp>
#include <mfem.hpp>
#include <mpi.h>
import mean_field;
import test_helpers;
using namespace mean_field;
namespace {
struct GravitationalEnergies {
double binding;
double virial;
};
struct HomogeneousEllipsoidAnalytic {
double coefficient_x;
double coefficient_y;
double coefficient_z;
double energy_kernel;
};
template <typename GravitySolutionType>
GravitationalEnergies compute_gravitational_energies(fem::FEM& f, const mfem::GridFunction& rho,
const GravitySolutionType& gravity_solution,
const int quadrature_order) {
const int dim = f.mesh->Dimension();
double local_bind_integral = 0.0;
double local_virial_integral = 0.0;
mfem::Vector x_physical(dim);
mfem::Vector grad_phi_element(dim);
mfem::Vector grad_phi_physical(dim);
mfem::DenseMatrix map_jacobian(dim, dim);
for (int elem_id = 0; elem_id < f.mesh->GetNE(); ++elem_id) {
if (f.mesh->GetAttribute(elem_id) == 3) {
continue;
}
mfem::ElementTransformation* transformation = f.mesh->GetElementTransformation(elem_id);
const mfem::IntegrationRule& integration_rule =
mfem::IntRules.Get(transformation->GetGeometryType(), quadrature_order);
for (int q = 0; q < integration_rule.GetNPoints(); ++q) {
const mfem::IntegrationPoint& integration_point = integration_rule.IntPoint(q);
transformation->SetIntPoint(&integration_point);
double weight = transformation->Weight() * integration_point.weight;
if (f.has_mapping()) {
const double map_determinant = f.mapping->ComputeDetJ(*transformation, integration_point);
MFEM_VERIFY(map_determinant > 0.0, "Domain mapping has a non-positive Jacobian determinant.");
weight *= map_determinant;
f.mapping->GetPhysicalPoint(*transformation, integration_point, x_physical);
gravity_solution.gradPhi.GetVectorValue(elem_id, integration_point, grad_phi_element);
f.mapping->ComputeJacobian(*transformation, map_jacobian);
map_jacobian.Mult(grad_phi_element, grad_phi_physical);
grad_phi_physical /= map_determinant;
} else {
transformation->Transform(integration_point, x_physical);
gravity_solution.gradPhi.GetVectorValue(elem_id, integration_point, grad_phi_physical);
}
const double rho_value = rho.GetValue(elem_id, integration_point);
const double phi_value = gravity_solution.phi.GetValue(elem_id, integration_point);
double radius_dot_gradient = 0.0;
for (int d = 0; d < dim; ++d) {
radius_dot_gradient += (x_physical(d) - f.com(d)) * grad_phi_physical(d);
}
local_bind_integral += rho_value * phi_value * weight;
local_virial_integral += rho_value * radius_dot_gradient * weight;
}
}
const double local_w_bind = 0.5 * local_bind_integral;
const double local_w_vir = -local_virial_integral;
double global_w_bind = 0.0;
double global_w_vir = 0.0;
MPI_Comm communicator = f.L2_fes->GetComm();
MPI_Allreduce(&local_w_bind, &global_w_bind, 1, MPI_DOUBLE, MPI_SUM, communicator);
MPI_Allreduce(&local_w_vir, &global_w_vir, 1, MPI_DOUBLE, MPI_SUM, communicator);
return {.binding = global_w_bind, .virial = global_w_vir};
}
void zero_vacuum_density(const fem::FEM& f, mfem::GridFunction& rho) {
for (int i = 0; i < f.vacuum_tdof_rho.Size(); ++i) {
rho(f.vacuum_tdof_rho[i]) = 0.0;
}
}
int get_gravity_quadrature_order(const fem::FEM& f) {
return 2 * std::max(f.L2_fes->GetMaxElementOrder(), f.RT_fes->GetMaxElementOrder()) + 8;
}
double compute_ellipsoid_coefficient(const double normalized_axis_x, const double normalized_axis_y,
const double normalized_axis_z, const double target_axis_squared) {
auto integrand = [=](const double t) {
if (t <= 0.0 || t >= 1.0) {
return 0.0;
}
const double one_minus_t = 1.0 - t;
const double s = t / one_minus_t;
const double s_squared = s * s;
const double ds_squared_dt = 2.0 * s / (one_minus_t * one_minus_t);
const double delta = std::sqrt(
(normalized_axis_x * normalized_axis_x + s_squared) *
(normalized_axis_y * normalized_axis_y + s_squared) *
(normalized_axis_z * normalized_axis_z + s_squared)
);
return normalized_axis_x * normalized_axis_y * normalized_axis_z * ds_squared_dt /
((target_axis_squared + s_squared) * delta);
};
double integration_error = 0.0;
return boost::math::quadrature::gauss_kronrod<double, 61>::integrate(
integrand, 0.0, 1.0, 15, 1.0e-13, &integration_error
);
}
double compute_ellipsoid_energy_kernel(const double normalized_axis_x, const double normalized_axis_y,
const double normalized_axis_z, const double length_scale) {
auto integrand = [=](const double t) {
if (t <= 0.0) {
return 0.0;
}
if (t >= 1.0) {
return 2.0;
}
const double one_minus_t = 1.0 - t;
const double s = t / one_minus_t;
const double s_squared = s * s;
const double ds_squared_dt = 2.0 * s / (one_minus_t * one_minus_t);
const double delta = std::sqrt(
(normalized_axis_x * normalized_axis_x + s_squared) *
(normalized_axis_y * normalized_axis_y + s_squared) *
(normalized_axis_z * normalized_axis_z + s_squared)
);
return ds_squared_dt / delta;
};
double integration_error = 0.0;
const double dimensionless_integral = boost::math::quadrature::gauss_kronrod<double, 61>::integrate(
integrand, 0.0, 1.0, 15, 1.0e-13, &integration_error
);
return dimensionless_integral / length_scale;
}
HomogeneousEllipsoidAnalytic compute_homogeneous_ellipsoid_analytic(
const double semi_axis_x, const double semi_axis_y, const double semi_axis_z
) {
const double length_scale = std::cbrt(semi_axis_x * semi_axis_y * semi_axis_z);
const double normalized_axis_x = semi_axis_x / length_scale;
const double normalized_axis_y = semi_axis_y / length_scale;
const double normalized_axis_z = semi_axis_z / length_scale;
const double coefficient_x = compute_ellipsoid_coefficient(
normalized_axis_x, normalized_axis_y, normalized_axis_z, normalized_axis_x * normalized_axis_x
);
const double coefficient_y = compute_ellipsoid_coefficient(
normalized_axis_x, normalized_axis_y, normalized_axis_z, normalized_axis_y * normalized_axis_y
);
const double coefficient_z = compute_ellipsoid_coefficient(
normalized_axis_x, normalized_axis_y, normalized_axis_z, normalized_axis_z * normalized_axis_z
);
const double energy_kernel = compute_ellipsoid_energy_kernel(
normalized_axis_x, normalized_axis_y, normalized_axis_z, length_scale
);
return {
.coefficient_x = coefficient_x,
.coefficient_y = coefficient_y,
.coefficient_z = coefficient_z,
.energy_kernel = energy_kernel
};
}
}
TEST_CASE("Uniform Potential Matches Analytic", tags::gravity & tags::analytic_comparison) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
f.mapping->ResetDisplacement();
physics::update_stiffness_matrix(f);
const double radius = utils::RADIUS;
const double mass = utils::MASS;
const double analytic_volume = (4.0 / 3.0) * M_PI * std::pow(radius, 3.0);
const double density = mass / analytic_volume;
mfem::GridFunction rho_uniform(f.L2_fes.get());
rho_uniform = density;
zero_vacuum_density(f, rho_uniform);
analysis::conserve_mass(f, rho_uniform, mass);
f.com = analysis::get_com(f, rho_uniform);
f.Q = physics::compute_quadrupole_moment_tensor(f, rho_uniform, f.com);
const auto gravity_solution = physics::grav_potential(f, args, rho_uniform);
constexpr double potential_tolerance = utils::APPROX_MAX_ACCEPTABLE_POTENTIAL_ERROR_SI_BURNING;
double local_max_abs_error = 0.0;
double local_max_rel_error = 0.0;
const int num_elements_to_test = std::min(30, f.mesh->GetNE());
for (int elem_id = 0; elem_id < num_elements_to_test; ++elem_id) {
mfem::ElementTransformation* transformation = f.mesh->GetElementTransformation(elem_id);
const mfem::IntegrationRule& integration_rule = mfem::IntRules.Get(transformation->GetGeometryType(), 2);
const mfem::IntegrationPoint& integration_point = integration_rule.IntPoint(0);
transformation->SetIntPoint(&integration_point);
mfem::Vector x_physical;
f.mapping->GetPhysicalPoint(*transformation, integration_point, x_physical);
const double radial_coordinate = x_physical.Norml2();
if (radial_coordinate < 1.0e-9) {
continue;
}
const double phi_analytic = -(utils::G * mass / (2.0 * std::pow(radius, 3.0))) *
(3.0 * radius * radius - radial_coordinate * radial_coordinate);
const double phi_fem = gravity_solution.phi.GetValue(elem_id, integration_point);
const double absolute_error = std::abs(phi_fem - phi_analytic);
const double relative_error = absolute_error / std::abs(phi_analytic);
local_max_abs_error = std::max(local_max_abs_error, absolute_error);
local_max_rel_error = std::max(local_max_rel_error, relative_error);
CHECK_THAT(relative_error, Catch::Matchers::WithinAbs(0.0, 0.1 * potential_tolerance));
}
double global_max_abs_error = 0.0;
double global_max_rel_error = 0.0;
MPI_Comm communicator = f.L2_fes->GetComm();
MPI_Allreduce(&local_max_abs_error, &global_max_abs_error, 1, MPI_DOUBLE, MPI_MAX, communicator);
MPI_Allreduce(&local_max_rel_error, &global_max_rel_error, 1, MPI_DOUBLE, MPI_MAX, communicator);
const int quadrature_order = get_gravity_quadrature_order(f);
const GravitationalEnergies energies = compute_gravitational_energies(f, rho_uniform, gravity_solution, quadrature_order);
const double analytic_binding_energy = -(3.0 / 5.0) * utils::G * mass * mass / radius;
const double relative_binding_error = std::abs(energies.binding - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_virial_error = std::abs(energies.virial - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_consistency_error = std::abs(energies.binding - energies.virial) / std::abs(energies.binding);
INFO("Analytic binding energy = " << analytic_binding_energy);
INFO("Computed binding energy = " << energies.binding);
INFO("Computed virial energy = " << energies.virial);
INFO("Relative virial consistency error = " << relative_consistency_error);
constexpr double energy_tolerance = 1.0e-5;
constexpr double consistency_tolerance = 1.0e-6;
CHECK_THAT(global_max_rel_error, Catch::Matchers::WithinAbs(0.0, 0.1 * potential_tolerance));
CHECK_THAT(global_max_abs_error, Catch::Matchers::WithinAbs(0.0, 0.1 * potential_tolerance));
CHECK_THAT(relative_binding_error, Catch::Matchers::WithinAbs(0.0, energy_tolerance));
CHECK_THAT(relative_virial_error, Catch::Matchers::WithinAbs(0.0, energy_tolerance));
CHECK_THAT(relative_consistency_error, Catch::Matchers::WithinAbs(0.0, consistency_tolerance));
}
TEST_CASE("Parabolic Density Virial Self-Consistency", tags::gravity & tags::analytic_comparison) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
f.mapping->ResetDisplacement();
physics::update_stiffness_matrix(f);
const double radius = utils::RADIUS;
const double mass = utils::MASS;
const double central_density = (15.0 * mass) / (8.0 * M_PI * std::pow(radius, 3.0));
auto parabolic_rho = [central_density, radius](const mfem::Vector& x) {
const double radial_coordinate = x.Norml2();
return central_density * (1.0 - radial_coordinate * radial_coordinate / (radius * radius));
};
std::unique_ptr<mfem::Coefficient> rho_coeff;
if (f.has_mapping()) {
rho_coeff = std::make_unique<mapping::PhysicalPositionFunctionCoefficient>(*f.mapping, parabolic_rho);
} else {
rho_coeff = std::make_unique<mfem::FunctionCoefficient>(parabolic_rho);
}
mfem::GridFunction rho_grid(f.L2_fes.get());
rho_grid.ProjectCoefficient(*rho_coeff);
zero_vacuum_density(f, rho_grid);
analysis::conserve_mass(f, rho_grid, mass);
f.com = analysis::get_com(f, rho_grid);
f.Q = physics::compute_quadrupole_moment_tensor(f, rho_grid, f.com);
const auto gravity_solution = physics::grav_potential(f, args, rho_grid);
const int quadrature_order = get_gravity_quadrature_order(f);
const GravitationalEnergies energies = compute_gravitational_energies(f, rho_grid, gravity_solution, quadrature_order);
const double analytic_binding_energy = -(5.0 / 7.0) * utils::G * mass * mass / radius;
const double relative_binding_error = std::abs(energies.binding - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_virial_error = std::abs(energies.virial - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_consistency_error = std::abs(energies.binding - energies.virial) / std::abs(energies.binding);
INFO("Analytic binding energy = " << analytic_binding_energy);
INFO("Computed binding energy = " << energies.binding);
INFO("Computed virial energy = " << energies.virial);
INFO("Relative virial consistency error = " << relative_consistency_error);
constexpr double analytic_tolerance = 1.0e-5;
constexpr double consistency_tolerance = 1.0e-6;
CHECK_THAT(relative_binding_error, Catch::Matchers::WithinAbs(0.0, analytic_tolerance));
CHECK_THAT(relative_virial_error, Catch::Matchers::WithinAbs(0.0, analytic_tolerance));
CHECK_THAT(relative_consistency_error, Catch::Matchers::WithinAbs(0.0, consistency_tolerance));
}
TEST_CASE("Rational Density Virial Self-Consistency", tags::gravity & tags::self_consistency) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
f.mapping->ResetDisplacement();
physics::update_stiffness_matrix(f);
const double radius = utils::RADIUS;
const double mass = utils::MASS;
// Larger values are more centrally concentrated and generally harder for a polynomial to represent.
// A regression would be considered if this test does not pass for concentrations <= 16.0.
constexpr double concentration = 16.0;
const double density_scale = mass / std::pow(radius, 3.0);
auto rational_rho = [radius, density_scale](const mfem::Vector& x) {
const double normalized_radius_squared = (x * x) / (radius * radius);
if (normalized_radius_squared >= 1.0) {
return 0.0;
}
const double denominator = 1.0 + concentration * normalized_radius_squared;
return density_scale * (1.0 - normalized_radius_squared) / (denominator * denominator);
};
std::unique_ptr<mfem::Coefficient> rho_coeff;
if (f.has_mapping()) {
rho_coeff = std::make_unique<mapping::PhysicalPositionFunctionCoefficient>(*f.mapping, rational_rho);
} else {
rho_coeff = std::make_unique<mfem::FunctionCoefficient>(rational_rho);
}
mfem::GridFunction rho_grid(f.L2_fes.get());
rho_grid.ProjectCoefficient(*rho_coeff);
zero_vacuum_density(f, rho_grid);
analysis::conserve_mass(f, rho_grid, mass);
f.com = analysis::get_com(f, rho_grid);
f.Q = physics::compute_quadrupole_moment_tensor(f, rho_grid, f.com);
const auto gravity_solution = physics::grav_potential(f, args, rho_grid);
const int quadrature_order = get_gravity_quadrature_order(f);
const GravitationalEnergies energies = compute_gravitational_energies(f, rho_grid, gravity_solution, quadrature_order);
REQUIRE(energies.binding < 0.0);
REQUIRE(energies.virial < 0.0);
const double relative_consistency_error = std::abs(energies.binding - energies.virial) / std::abs(energies.binding);
INFO("W_bind = " << energies.binding);
INFO("W_vir = " << energies.virial);
INFO("Relative virial consistency error = " << relative_consistency_error);
constexpr double virial_tolerance = 1.0e-5;
CHECK_THAT(relative_consistency_error, Catch::Matchers::WithinAbs(0.0, virial_tolerance));
}
TEST_CASE("Homogeneous Ellipsoid Analytic Gravity", tags::gravity & tags::analytic_comparison) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
const double radius = utils::RADIUS;
const double mass = utils::MASS;
constexpr double x_scale = 1.15;
constexpr double y_scale = 0.95;
constexpr double z_scale = 1.0 / (x_scale * y_scale);
assert(std::abs(x_scale * y_scale * z_scale - 1.0) < 1.0e-14);
const double semi_axis_x = x_scale * radius;
const double semi_axis_y = y_scale * radius;
const double semi_axis_z = z_scale * radius;
auto affine_displacement = [](const mfem::Vector& x, mfem::Vector& displacement_value) {
displacement_value.SetSize(3);
displacement_value(0) = (x_scale - 1.0) * x(0);
displacement_value(1) = (y_scale - 1.0) * x(1);
displacement_value(2) = (z_scale - 1.0) * x(2);
};
mfem::VectorFunctionCoefficient displacement_coeff(3, affine_displacement);
mfem::ParGridFunction displacement(f.Vec_H1_fes.get());
displacement.ProjectCoefficient(displacement_coeff);
f.mapping->SetDisplacement(displacement);
physics::update_stiffness_matrix(f);
const double analytic_volume = (4.0 / 3.0) * M_PI * semi_axis_x * semi_axis_y * semi_axis_z;
const double density = mass / analytic_volume;
mfem::GridFunction rho_grid(f.L2_fes.get());
rho_grid = density;
zero_vacuum_density(f, rho_grid);
const double projected_mass = analysis::domain_integrate_grid_function(f, rho_grid, utils::DOMAINS::STELLAR);
const double numerical_density = density * mass / projected_mass;
analysis::conserve_mass(f, rho_grid, mass);
f.com = analysis::get_com(f, rho_grid);
f.Q = physics::compute_quadrupole_moment_tensor(f, rho_grid, f.com);
const HomogeneousEllipsoidAnalytic analytic =
compute_homogeneous_ellipsoid_analytic(semi_axis_x, semi_axis_y, semi_axis_z);
const double coefficient_sum = analytic.coefficient_x + analytic.coefficient_y + analytic.coefficient_z;
INFO("A_x = " << analytic.coefficient_x);
INFO("A_y = " << analytic.coefficient_y);
INFO("A_z = " << analytic.coefficient_z);
INFO("A_x + A_y + A_z = " << coefficient_sum);
REQUIRE_THAT(coefficient_sum, Catch::Matchers::WithinAbs(2.0, 1.0e-11));
mfem::DenseMatrix analytic_quadrupole(3, 3);
analytic_quadrupole = 0.0;
analytic_quadrupole(0, 0) = (mass / 5.0) * (2.0 * semi_axis_x * semi_axis_x - semi_axis_y * semi_axis_y - semi_axis_z * semi_axis_z);
analytic_quadrupole(1, 1) = (mass / 5.0) * (2.0 * semi_axis_y * semi_axis_y - semi_axis_x * semi_axis_x - semi_axis_z * semi_axis_z);
analytic_quadrupole(2, 2) = (mass / 5.0) * (2.0 * semi_axis_z * semi_axis_z - semi_axis_x * semi_axis_x - semi_axis_y * semi_axis_y);
mfem::DenseMatrix quadrupole_difference(f.Q);
quadrupole_difference -= analytic_quadrupole;
const double relative_quadrupole_error = quadrupole_difference.FNorm() / analytic_quadrupole.FNorm();
INFO("Relative quadrupole error = " << relative_quadrupole_error);
const auto gravity_solution = physics::grav_potential(f, args, rho_grid);
const int quadrature_order = get_gravity_quadrature_order(f);
double local_field_error_squared = 0.0;
double local_field_norm_squared = 0.0;
mfem::Vector x_physical(3);
mfem::Vector grad_phi_element(3);
mfem::Vector grad_phi_physical(3);
mfem::Vector grad_phi_analytic(3);
mfem::Vector grad_phi_difference(3);
mfem::DenseMatrix map_jacobian(3, 3);
for (int elem_id = 0; elem_id < f.mesh->GetNE(); ++elem_id) {
if (f.mesh->GetAttribute(elem_id) == 3) {
continue;
}
mfem::ElementTransformation* transformation = f.mesh->GetElementTransformation(elem_id);
const mfem::IntegrationRule& integration_rule =
mfem::IntRules.Get(transformation->GetGeometryType(), quadrature_order);
for (int q = 0; q < integration_rule.GetNPoints(); ++q) {
const mfem::IntegrationPoint& integration_point = integration_rule.IntPoint(q);
transformation->SetIntPoint(&integration_point);
const double map_determinant = f.mapping->ComputeDetJ(*transformation, integration_point);
MFEM_VERIFY(map_determinant > 0.0, "Domain mapping has a non-positive Jacobian determinant.");
const double weight = transformation->Weight() * integration_point.weight * map_determinant;
f.mapping->GetPhysicalPoint(*transformation, integration_point, x_physical);
gravity_solution.gradPhi.GetVectorValue(elem_id, integration_point, grad_phi_element);
f.mapping->ComputeJacobian(*transformation, map_jacobian);
map_jacobian.Mult(grad_phi_element, grad_phi_physical);
grad_phi_physical /= map_determinant;
grad_phi_analytic(0) = 2.0 * M_PI * utils::G * numerical_density * analytic.coefficient_x * x_physical(0);
grad_phi_analytic(1) = 2.0 * M_PI * utils::G * numerical_density * analytic.coefficient_y * x_physical(1);
grad_phi_analytic(2) = 2.0 * M_PI * utils::G * numerical_density * analytic.coefficient_z * x_physical(2);
grad_phi_difference = grad_phi_physical;
grad_phi_difference -= grad_phi_analytic;
local_field_error_squared += (grad_phi_difference * grad_phi_difference) * weight;
local_field_norm_squared += (grad_phi_analytic * grad_phi_analytic) * weight;
}
}
double global_field_error_squared = 0.0;
double global_field_norm_squared = 0.0;
MPI_Comm communicator = f.L2_fes->GetComm();
MPI_Allreduce(&local_field_error_squared, &global_field_error_squared, 1, MPI_DOUBLE, MPI_SUM, communicator);
MPI_Allreduce(&local_field_norm_squared, &global_field_norm_squared, 1, MPI_DOUBLE, MPI_SUM, communicator);
const double relative_field_error = std::sqrt(global_field_error_squared / global_field_norm_squared);
const GravitationalEnergies energies = compute_gravitational_energies(f, rho_grid, gravity_solution, quadrature_order);
const double analytic_binding_energy = -(3.0 / 10.0) * utils::G * mass * mass * analytic.energy_kernel;
const double relative_binding_energy_error = std::abs(energies.binding - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_virial_energy_error = std::abs(energies.virial - analytic_binding_energy) / std::abs(analytic_binding_energy);
const double relative_consistency_error = std::abs(energies.binding - energies.virial) / std::abs(energies.binding);
INFO("Analytic binding energy = " << analytic_binding_energy);
INFO("Computed binding energy = " << energies.binding);
INFO("Computed virial energy = " << energies.virial);
INFO("Relative field L2 error = " << relative_field_error);
INFO("Relative binding energy error = " << relative_binding_energy_error);
INFO("Relative virial energy error = " << relative_virial_energy_error);
INFO("Relative virial consistency error = " << relative_consistency_error);
constexpr double quadrupole_tolerance = 2.0e-4;
constexpr double field_tolerance = 1.0e-5;
constexpr double energy_tolerance = 1.0e-5;
constexpr double consistency_tolerance = 1.0e-5;
CHECK_THAT(relative_quadrupole_error, Catch::Matchers::WithinAbs(0.0, quadrupole_tolerance));
CHECK_THAT(relative_field_error, Catch::Matchers::WithinAbs(0.0, field_tolerance));
CHECK_THAT(relative_binding_energy_error, Catch::Matchers::WithinAbs(0.0, energy_tolerance));
CHECK_THAT(relative_virial_energy_error, Catch::Matchers::WithinAbs(0.0, energy_tolerance));
CHECK_THAT(relative_consistency_error, Catch::Matchers::WithinAbs(0.0, consistency_tolerance));
}
TEST_CASE("Deformed Rational Density Virial Self-Consistency", tags::gravity & tags::self_consistency) {
auto args = test_utils::setup_args();
fem::FEM f = fem::setup_fem(args.mesh_file, args, 0);
const double radius = utils::RADIUS;
const double mass = utils::MASS;
constexpr double x_scale = 1.15;
constexpr double y_scale = 0.95;
constexpr double z_scale = 1.0 / (x_scale * y_scale);
assert(std::abs(x_scale * y_scale * z_scale - 1.0) < 1.0e-14);
const double semi_axis_x = x_scale * radius;
const double semi_axis_y = y_scale * radius;
const double semi_axis_z = z_scale * radius;
auto affine_displacement = [](const mfem::Vector& x, mfem::Vector& displacement_value) {
displacement_value.SetSize(3);
displacement_value(0) = (x_scale - 1.0) * x(0);
displacement_value(1) = (y_scale - 1.0) * x(1);
displacement_value(2) = (z_scale - 1.0) * x(2);
};
mfem::VectorFunctionCoefficient displacement_coeff(3, affine_displacement);
mfem::ParGridFunction displacement(f.Vec_H1_fes.get());
displacement.ProjectCoefficient(displacement_coeff);
f.mapping->SetDisplacement(displacement);
physics::update_stiffness_matrix(f);
constexpr double concentration = 16.0;
const double density_scale = mass / std::pow(radius, 3.0);
auto ellipsoidal_rho = [semi_axis_x, semi_axis_y, semi_axis_z, density_scale](const mfem::Vector& x) {
const double ellipsoidal_radius_squared =
x(0) * x(0) / (semi_axis_x * semi_axis_x) +
x(1) * x(1) / (semi_axis_y * semi_axis_y) +
x(2) * x(2) / (semi_axis_z * semi_axis_z);
if (ellipsoidal_radius_squared >= 1.0) {
return 0.0;
}
const double denominator = 1.0 + concentration * ellipsoidal_radius_squared;
return density_scale * (1.0 - ellipsoidal_radius_squared) / (denominator * denominator);
};
std::unique_ptr<mfem::Coefficient> rho_coeff;
if (f.has_mapping()) {
rho_coeff = std::make_unique<mapping::PhysicalPositionFunctionCoefficient>(*f.mapping, ellipsoidal_rho);
} else {
rho_coeff = std::make_unique<mfem::FunctionCoefficient>(ellipsoidal_rho);
}
mfem::GridFunction rho_grid(f.L2_fes.get());
rho_grid.ProjectCoefficient(*rho_coeff);
zero_vacuum_density(f, rho_grid);
analysis::conserve_mass(f, rho_grid, mass);
f.com = analysis::get_com(f, rho_grid);
f.Q = physics::compute_quadrupole_moment_tensor(f, rho_grid, f.com);
const double normalized_quadrupole = f.Q.FNorm() / (mass * radius * radius);
INFO("Normalized quadrupole = " << normalized_quadrupole);
REQUIRE(normalized_quadrupole > 1.0e-3);
const auto gravity_solution = physics::grav_potential(f, args, rho_grid);
const int quadrature_order = get_gravity_quadrature_order(f);
const GravitationalEnergies energies = compute_gravitational_energies(f, rho_grid, gravity_solution, quadrature_order);
REQUIRE(energies.binding < 0.0);
REQUIRE(energies.virial < 0.0);
const double relative_consistency_error = std::abs(energies.binding - energies.virial) / std::abs(energies.binding);
INFO("W_bind = " << energies.binding);
INFO("W_vir = " << energies.virial);
INFO("Relative virial consistency error = " << relative_consistency_error);
constexpr double virial_tolerance = 1.0e-5;
CHECK_THAT(relative_consistency_error, Catch::Matchers::WithinAbs(0.0, virial_tolerance));
}

331
tests/quadrature/policy.cpp Normal file
View File

@@ -0,0 +1,331 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <array>
#include <cmath>
#include <stdexcept>
#include <string_view>
#include <utility>
#include <mfem.hpp>
import mean_field;
import test_helpers;
using namespace mean_field;
namespace {
std::string_view get_term_name(const quadrature::Term term) {
switch (term) {
case quadrature::Term::gravity_hdiv_mass: return "gravity_hdiv_mass";
case quadrature::Term::gravity_divergence: return "gravity_divergence";
case quadrature::Term::gravity_source: return "gravity_source";
case quadrature::Term::gravity_boundary: return "gravity_boundary";
case quadrature::Term::density_projection: return "density_projection";
case quadrature::Term::mass_conservation: return "mass_conservation";
case quadrature::Term::center_of_mass: return "center_of_mass";
case quadrature::Term::quadrupole: return "quadrupole";
case quadrature::Term::gravitational_energy: return "gravitational_energy";
case quadrature::Term::virial: return "virial";
case quadrature::Term::error_norm: return "error_norm";
}
return "unknown";
}
quadrature::Query make_query(const quadrature::Term term, const int base_order) {
return {.term = term, .base_order = base_order};
}
}
TEST_CASE("Quadrature Policy Computes Base Orders", tags::unit & tags::quadrature) {
const quadrature::Policy policy(quadrature::make_rule_set(quadrature::Mode::production));
quadrature::Query generic_query = {
.term = quadrature::Term::gravitational_energy,
.trial_order = 3,
.test_order = 4,
.coefficient_order = 2,
.geometry_weight_order = 5
};
const quadrature::Resolution generic_resolution = policy.resolve(generic_query);
CHECK(generic_resolution.base_order == 14);
CHECK(generic_resolution.boost == 0);
CHECK(generic_resolution.order == 14);
CHECK_FALSE(generic_resolution.used_fixed_order);
quadrature::Query divergence_query = {
.term = quadrature::Term::gravity_divergence,
.trial_order = 3,
.test_order = 2,
.coefficient_order = 1,
.geometry_weight_order = 4
};
CHECK(policy.resolve(divergence_query).base_order == 9);
divergence_query.trial_order = 0;
CHECK(policy.resolve(divergence_query).base_order == 7);
quadrature::Query explicit_query = {
.term = quadrature::Term::gravity_hdiv_mass,
.trial_order = 20,
.test_order = 20,
.coefficient_order = 20,
.geometry_weight_order = 20,
.base_order = 11
};
CHECK(policy.resolve(explicit_query).base_order == 11);
CHECK(policy.resolve(explicit_query).order == 11);
}
TEST_CASE("Quadrature Policy Composes Global and Term Boosts", tags::unit & tags::quadrature) {
quadrature::RuleSet rule_set = quadrature::make_rule_set(quadrature::Mode::production, 3);
rule_set.gravity_hdiv_mass.boost = 5;
rule_set.error_norm.boost = 2;
const quadrature::Policy policy(rule_set);
const quadrature::Resolution mass_resolution = policy.resolve(make_query(quadrature::Term::gravity_hdiv_mass, 7));
CHECK(mass_resolution.base_order == 7);
CHECK(mass_resolution.boost == 8);
CHECK(mass_resolution.order == 15);
CHECK_FALSE(mass_resolution.used_fixed_order);
const quadrature::Resolution error_resolution = policy.resolve(make_query(quadrature::Term::error_norm, 7));
CHECK(error_resolution.boost == 5);
CHECK(error_resolution.order == 12);
const quadrature::Resolution source_resolution = policy.resolve(make_query(quadrature::Term::gravity_source, 7));
CHECK(source_resolution.boost == 3);
CHECK(source_resolution.order == 10);
}
TEST_CASE("Quadrature Fixed Orders Have Defined Precedence", tags::unit & tags::quadrature) {
quadrature::RuleSet rule_set = quadrature::make_rule_set(quadrature::Mode::production, 4);
rule_set.fallback.fixed_order = 17;
rule_set.gravity_hdiv_mass.fixed_order = 23;
rule_set.gravity_hdiv_mass.boost = 100;
rule_set.gravity_source.boost = 100;
const quadrature::Policy policy(rule_set);
const quadrature::Resolution term_resolution = policy.resolve(make_query(quadrature::Term::gravity_hdiv_mass, 8));
CHECK(term_resolution.base_order == 8);
CHECK(term_resolution.boost == 0);
CHECK(term_resolution.order == 23);
CHECK(term_resolution.used_fixed_order);
const quadrature::Resolution fallback_resolution = policy.resolve(make_query(quadrature::Term::gravity_source, 8));
CHECK(fallback_resolution.base_order == 8);
CHECK(fallback_resolution.boost == 0);
CHECK(fallback_resolution.order == 17);
CHECK(fallback_resolution.used_fixed_order);
}
TEST_CASE("Quadrature Modes Apply Their Expected Baseline Boosts", tags::unit & tags::quadrature) {
constexpr int base_order = 6;
constexpr int global_boost = 3;
for (const quadrature::Mode mode : {quadrature::Mode::fast, quadrature::Mode::production, quadrature::Mode::convergence}) {
const quadrature::Policy policy(quadrature::make_rule_set(mode, global_boost));
const quadrature::Resolution resolution = policy.resolve(make_query(quadrature::Term::error_norm, base_order));
CHECK(resolution.boost == global_boost);
CHECK(resolution.order == base_order + global_boost);
}
const quadrature::Policy reference_policy(quadrature::make_rule_set(quadrature::Mode::reference, global_boost));
const quadrature::Resolution reference_resolution = reference_policy.resolve(make_query(quadrature::Term::error_norm, base_order));
CHECK(reference_resolution.boost == global_boost + 8);
CHECK(reference_resolution.order == base_order + global_boost + 8);
}
TEST_CASE("Quadrature Policy Routes Every Term to Its Control", tags::unit & tags::quadrature) {
quadrature::RuleSet rule_set;
rule_set.gravity_hdiv_mass.boost = 1;
rule_set.gravity_divergence.boost = 2;
rule_set.gravity_source.boost = 3;
rule_set.gravity_boundary.boost = 4;
rule_set.density_projection.boost = 5;
rule_set.mass_conservation.boost = 6;
rule_set.center_of_mass.boost = 7;
rule_set.quadrupole.boost = 8;
rule_set.gravitational_energy.boost = 9;
rule_set.virial.boost = 10;
rule_set.error_norm.boost = 11;
const quadrature::Policy policy(rule_set);
const std::array<std::pair<quadrature::Term, int>, 11> cases = {{
{quadrature::Term::gravity_hdiv_mass, 1},
{quadrature::Term::gravity_divergence, 2},
{quadrature::Term::gravity_source, 3},
{quadrature::Term::gravity_boundary, 4},
{quadrature::Term::density_projection, 5},
{quadrature::Term::mass_conservation, 6},
{quadrature::Term::center_of_mass, 7},
{quadrature::Term::quadrupole, 8},
{quadrature::Term::gravitational_energy, 9},
{quadrature::Term::virial, 10},
{quadrature::Term::error_norm, 11}
}};
for (const auto& [term, expected_boost] : cases) {
DYNAMIC_SECTION(get_term_name(term)) {
const quadrature::Resolution resolution = policy.resolve(make_query(term, 20));
CHECK(resolution.boost == expected_boost);
CHECK(resolution.order == 20 + expected_boost);
}
}
}
TEST_CASE("Quadrature Policy Rejects Invalid Orders", tags::unit & tags::quadrature) {
const quadrature::Policy policy(quadrature::make_rule_set(quadrature::Mode::production));
quadrature::Query negative_component_query = {
.term = quadrature::Term::error_norm,
.trial_order = -1
};
REQUIRE_THROWS_AS(policy.resolve(negative_component_query), std::invalid_argument);
quadrature::Query negative_base_query = {
.term = quadrature::Term::error_norm,
.base_order = -1
};
REQUIRE_THROWS_AS(policy.resolve(negative_base_query), std::invalid_argument);
quadrature::RuleSet negative_fixed_rule_set;
negative_fixed_rule_set.error_norm.fixed_order = -1;
const quadrature::Policy negative_fixed_policy(negative_fixed_rule_set);
REQUIRE_THROWS_AS(negative_fixed_policy.resolve(make_query(quadrature::Term::error_norm, 3)), std::invalid_argument);
quadrature::RuleSet negative_resolved_rule_set;
negative_resolved_rule_set.fallback.boost = -4;
const quadrature::Policy negative_resolved_policy(negative_resolved_rule_set);
REQUIRE_THROWS_AS(negative_resolved_policy.resolve(make_query(quadrature::Term::error_norm, 3)), std::invalid_argument);
}
TEST_CASE("MFEM Rule Factory Returns the Resolved Rule", tags::unit & tags::quadrature) {
quadrature::RuleSet rule_set = quadrature::make_rule_set(quadrature::Mode::production, 2);
rule_set.error_norm.boost = 3;
const quadrature::RuleFactory factory{quadrature::Policy(rule_set)};
const quadrature::MfemRule selected_rule = factory.get(make_query(quadrature::Term::error_norm, 4), mfem::Geometry::CUBE);
const mfem::IntegrationRule& expected_rule = mfem::IntRules.Get(mfem::Geometry::CUBE, 9);
REQUIRE(selected_rule.integration_rule != nullptr);
CHECK(selected_rule.resolution.base_order == 4);
CHECK(selected_rule.resolution.boost == 5);
CHECK(selected_rule.resolution.order == 9);
CHECK(selected_rule.integration_rule == &expected_rule);
CHECK(selected_rule.integration_rule->GetNPoints() > 0);
}
TEST_CASE("MFEM Quadrature Rule Integrates Tensor Polynomial Exactly", tags::unit & tags::quadrature) {
constexpr int polynomial_degree = 7;
const quadrature::RuleFactory factory{quadrature::Policy(quadrature::make_rule_set(quadrature::Mode::production))};
const quadrature::MfemRule selected_rule = factory.get(make_query(quadrature::Term::error_norm, polynomial_degree), mfem::Geometry::CUBE);
double numerical_integral = 0.0;
for (int i = 0; i < selected_rule.integration_rule->GetNPoints(); ++i) {
const mfem::IntegrationPoint& integration_point = selected_rule.integration_rule->IntPoint(i);
numerical_integral += integration_point.weight * std::pow(integration_point.x, polynomial_degree) * std::pow(integration_point.y, polynomial_degree) * std::pow(integration_point.z, polynomial_degree);
}
const double one_dimensional_integral = 1.0 / static_cast<double>(polynomial_degree + 1);
const double analytic_integral = one_dimensional_integral * one_dimensional_integral * one_dimensional_integral;
CHECK_THAT(numerical_integral, Catch::Matchers::WithinAbs(analytic_integral, 5.0e-14));
}
TEST_CASE("Policy Controlled Hdiv Mass Assembly Matches Overintegrated Reference", tags::quadrature & tags::solver & tags::integration) {
mfem::Mesh mesh = mfem::Mesh::MakeCartesian3D(1, 1, 1, mfem::Element::HEXAHEDRON, 1.0, 1.0, 1.0);
mfem::RT_FECollection rt_collection(2, 3);
mfem::FiniteElementSpace rt_space(&mesh, &rt_collection);
const mfem::FiniteElement* rt_element = rt_space.GetTypicalFE();
mfem::ElementTransformation* transformation = mesh.GetElementTransformation(0);
const int base_order = 2 * rt_element->GetOrder() + transformation->OrderW();
const quadrature::RuleFactory production_factory{quadrature::Policy(quadrature::make_rule_set(quadrature::Mode::production))};
const quadrature::MfemRule production_rule = production_factory.get(make_query(quadrature::Term::gravity_hdiv_mass, base_order), rt_element->GetGeomType());
quadrature::RuleSet reference_rule_set = quadrature::make_rule_set(quadrature::Mode::production);
reference_rule_set.gravity_hdiv_mass.boost = 8;
const quadrature::RuleFactory reference_factory{quadrature::Policy(reference_rule_set)};
const quadrature::MfemRule reference_rule = reference_factory.get(make_query(quadrature::Term::gravity_hdiv_mass, base_order), rt_element->GetGeomType());
mfem::BilinearForm production_mass(&rt_space);
auto* production_integrator = new mfem::VectorFEMassIntegrator();
production_integrator->SetIntegrationRule(*production_rule.integration_rule);
production_mass.AddDomainIntegrator(production_integrator);
production_mass.Assemble();
production_mass.Finalize();
mfem::BilinearForm reference_mass(&rt_space);
auto* reference_integrator = new mfem::VectorFEMassIntegrator();
reference_integrator->SetIntegrationRule(*reference_rule.integration_rule);
reference_mass.AddDomainIntegrator(reference_integrator);
reference_mass.Assemble();
reference_mass.Finalize();
mfem::Vector input(rt_space.GetVSize());
mfem::Vector production_output(rt_space.GetVSize());
mfem::Vector reference_output(rt_space.GetVSize());
for (int i = 0; i < input.Size(); ++i) {
input(i) = std::sin(0.37 * static_cast<double>(i + 1));
}
production_mass.Mult(input, production_output);
reference_mass.Mult(input, reference_output);
mfem::Vector difference(production_output);
difference -= reference_output;
const double relative_difference = difference.Norml2() / reference_output.Norml2();
INFO("Production quadrature order = " << production_rule.resolution.order);
INFO("Reference quadrature order = " << reference_rule.resolution.order);
INFO("Relative operator difference = " << relative_difference);
CHECK_THAT(relative_difference, Catch::Matchers::WithinAbs(0.0, 1.0e-12));
}
TEST_CASE("HDiv Mass Helper Resolves the MFEM Baseline", tags::unit & tags::quadrature & tags::solver) {
mfem::Mesh mesh = mfem::Mesh::MakeCartesian3D(1, 1, 1, mfem::Element::HEXAHEDRON);
mfem::RT_FECollection rt_collection(2, 3);
mfem::FiniteElementSpace rt_space(&mesh, &rt_collection);
quadrature::RuleSet rule_set = quadrature::make_rule_set(quadrature::Mode::production);
rule_set.gravity_hdiv_mass.boost = 3;
quadrature::RuleFactory factory{quadrature::Policy(std::move(rule_set))};
const mfem::FiniteElement& element = *rt_space.GetTypicalFE();
const mfem::ElementTransformation& transformation = *mesh.GetElementTransformation(0);
mfem::VectorFEMassIntegrator integrator;
const quadrature::Resolution resolution = factory.configure_gravity_hdiv_mass(integrator, quadrature::QuadratureRole::discretization, element, transformation);
const int expected_base_order = 2 * element.GetOrder() + transformation.OrderW();
CHECK(resolution.base_order == expected_base_order);
CHECK(resolution.boost == 3);
CHECK(resolution.order == expected_base_order + 3);
}
TEST_CASE("Gravity Divergence Helper Resolves Preconditioner Rule", tags::unit & tags::quadrature & tags::solver) {
mfem::Mesh mesh = mfem::Mesh::MakeCartesian3D(1, 1, 1, mfem::Element::HEXAHEDRON);
mfem::RT_FECollection rt_collection(2, 3);
mfem::L2_FECollection l2_collection(2, 3);
mfem::FiniteElementSpace rt_space(&mesh, &rt_collection);
mfem::FiniteElementSpace l2_space(&mesh, &l2_collection);
quadrature::RuleSet rule_set = quadrature::make_rule_set(quadrature::Mode::production);
rule_set.gravity_divergence.boost = 2;
rule_set.roles.preconditioner.boost = 3;
quadrature::RuleFactory factory{quadrature::Policy(std::move(rule_set))};
const mfem::FiniteElement& trial_element = *rt_space.GetTypicalFE();
const mfem::FiniteElement& test_element = *l2_space.GetTypicalFE();
const mfem::ElementTransformation& transformation = *mesh.GetElementTransformation(0);
mfem::VectorFEDivergenceIntegrator integrator;
const quadrature::Resolution resolution = factory.configure_gravity_divergence(integrator, quadrature::QuadratureRole::preconditioner, trial_element, test_element, transformation);
const int expected_base_order = std::max(0, trial_element.GetOrder() - 1) + test_element.GetOrder() + transformation.OrderW();
CHECK(resolution.base_order == expected_base_order);
CHECK(resolution.boost == 5);
CHECK(resolution.order == expected_base_order + 5);
}

97
tests/test_helpers.cppm Normal file
View File

@@ -0,0 +1,97 @@
module;
#include <string>
#include <array>
#include <algorithm>
#include <catch2/internal/catch_stringref.hpp>
#include <optional>
#include <utility>
export module test_helpers;
import mean_field;
template <std::size_t N>
struct Tag {
std::array<char, N> chars{};
// ReSharper disable once CppNonExplicitConvertingConstructor
consteval Tag(std::array<char, N> arr) : chars(arr) {}
// ReSharper disable once CppNonExplicitConversionOperator
constexpr operator const char*() const { return chars.data(); }
// ReSharper disable once CppNonExplicitConversionOperator
constexpr operator Catch::StringRef() const {
return Catch::StringRef(chars.data(), N - 1);
}
template <std::size_t M>
consteval Tag<N + M - 1> operator&(const Tag<M>& other) const {
std::array<char, N + M - 1> res{};
std::ranges::copy(chars.begin(), chars.end() - 1, res.begin());
std::ranges::copy(other.chars, res.begin() + (N - 1));
return {res};
}
};
template <std::size_t N>
consteval auto make_tag(const char (&str)[N]) {
std::array<char, N + 2> res{};
res[0] = '[';
std::ranges::copy(str, str + N - 1, res.begin() + 1);
res[N] = ']';
res[N + 1] = '\0';
return Tag<N + 2>{res};
}
template <std::size_t N, std::size_t M>
consteval auto sub_tag(const Tag<N>& parent, const char (&str)[M]) {
return parent & make_tag(str);
}
namespace test_utils::detail {
std::optional<mean_field::utils::Args> configured_args;
mean_field::utils::Args make_default_args() {
mean_field::utils::Args args;
args.mesh_file = "sandbox.smesh";
args.p.rtol = 1.0e-12;
args.p.atol = 1.0e-12;
return args;
}
}
export namespace test_utils {
void set_args(mean_field::utils::Args args) {
detail::configured_args = std::move(args);
}
mean_field::utils::Args setup_args() {
if (detail::configured_args.has_value()) {
return *detail::configured_args;
}
return detail::make_default_args();
}
}
export namespace tags {
inline constexpr auto geometry = make_tag("geometry");
inline constexpr auto physics = make_tag("physics");
inline constexpr auto unit = make_tag("unit");
inline constexpr auto mesh = make_tag("mesh");
inline constexpr auto integration = make_tag("integration");
inline constexpr auto solver = make_tag("solver");
inline constexpr auto gravity = sub_tag(physics, "gravity");
inline constexpr auto hydro = sub_tag(physics, "hydro");
inline constexpr auto jacobian = sub_tag(integration & physics , "jacobian");
inline constexpr auto residuals = sub_tag(integration & physics , "residuals");
inline constexpr auto h_refinement = sub_tag(mesh & solver , "h_refinement");
inline constexpr auto volume = sub_tag(mesh & geometry , "volume");
inline constexpr auto quadrature = sub_tag(mesh & geometry & solver , "quadrature");
inline constexpr auto analytic_comparison = sub_tag(solver & physics & residuals , "analytic_comparison");
inline constexpr auto self_consistency = sub_tag(solver & physics , "self_consistency");
}

223
tests/test_main.cpp Normal file
View File

@@ -0,0 +1,223 @@
#include <catch2/catch_session.hpp>
#include <catch2/reporters/catch_reporter_streaming_base.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <catch2/catch_test_case_info.hpp>
#include <iostream>
#include <mfem.hpp>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <sstream>
#include <string_view>
#include <fourdst/config/config.h>
#include <CLI/CLI.hpp>
import mean_field;
import test_helpers;
class CheckReporter : public Catch::StreamingReporterBase {
// Accumulate failure messages for the current test case
std::vector<std::string> m_currentFailures;
public:
using StreamingReporterBase::StreamingReporterBase;
static std::string getDescription() {
return "Fixed-width table reporter with detailed assertion failures.";
}
void testRunStarting(Catch::TestRunInfo const& _testRunInfo) override {
StreamingReporterBase::testRunStarting(_testRunInfo);
std::cout << '\n';
std::cout << std::left << std::setw(55) << "Test Case Name"
<< "Status "
<< std::right << std::setw(8) << "Passed"
<< std::setw(8) << "Failed" << '\n';
std::cout << std::string(81, '-') << '\n';
}
// 1. Hook into every assertion to catch failures
void assertionEnded(Catch::AssertionStats const& assertionStats) override {
StreamingReporterBase::assertionEnded(assertionStats);
// If the assertion failed, build a detailed message
if (!assertionStats.assertionResult.isOk()) {
auto const& result = assertionStats.assertionResult;
std::ostringstream oss;
// Format: -> FAILED: [file:line]
oss << " \033[31m-> FAILED:\033[0m "
<< result.getSourceInfo().file << ":" << result.getSourceInfo().line << '\n';
// Print the macro used (e.g., REQUIRE, CHECK) and the expression
oss << " " << result.getTestMacroName() << "( " << result.getExpression() << " )\n";
// Print what it actually evaluated to (e.g., 1 == 2)
if (result.hasExpandedExpression()) {
oss << " with expansion:\n"
<< " " << result.getExpandedExpression() << '\n';
}
// Capture any INFO() messages attached to this assertion
for (auto const& msg : assertionStats.infoMessages) {
oss << " info: " << msg.message << '\n';
}
m_currentFailures.push_back(oss.str());
}
}
void testCaseEnded(Catch::TestCaseStats const& stats) override {
StreamingReporterBase::testCaseEnded(stats);
bool passed = stats.totals.assertions.allPassed();
std::string mark = passed ? "\033[32m✓\033[0m" : "\033[31m✗\033[0m";
std::string name = stats.testInfo->name;
if (name.length() > 53) {
name = name.substr(0, 50) + "...";
}
// Print the table row
std::cout << std::left << std::setw(55) << name
<< mark << " "
<< std::right << std::setw(8) << stats.totals.assertions.passed
<< std::setw(8) << stats.totals.assertions.failed << '\n';
// 2. Print all accumulated failures under the row
if (!m_currentFailures.empty()) {
std::cout << '\n';
for (auto const& failure : m_currentFailures) {
std::cout << failure << '\n';
}
// Add a separator so multiple failing tests don't blur together
std::cout << std::string(81, '-') << '\n';
// Clear the buffer for the next test case
m_currentFailures.clear();
}
}
void testRunEnded(Catch::TestRunStats const& _testRunStats) override {
StreamingReporterBase::testRunEnded(_testRunStats);
std::cout << std::string(81, '=') << '\n';
auto const& tc = _testRunStats.totals.testCases;
auto const& as = _testRunStats.totals.assertions;
std::string tc_passed_str = tc.passed > 0 ? "\033[32m" + std::to_string(tc.passed) + " passed\033[0m" : "0 passed";
std::string tc_failed_str = tc.failed > 0 ? "\033[31m" + std::to_string(tc.failed) + " failed\033[0m" : "0 failed";
std::string as_passed_str = as.passed > 0 ? "\033[32m" + std::to_string(as.passed) + " passed\033[0m" : "0 passed";
std::string as_failed_str = as.failed > 0 ? "\033[31m" + std::to_string(as.failed) + " failed\033[0m" : "0 failed";
std::cout << "Test Cases: " << tc_passed_str << ", " << tc_failed_str << ", " << tc.total() << " total\n";
std::cout << "Assertions: " << as_passed_str << ", " << as_failed_str << ", " << as.total() << " total\n\n";
}
};
CATCH_REGISTER_REPORTER("check", CheckReporter)
int main(int argc, char* argv[]) {
fourdst::config::Config<mean_field::utils::Args> cfg;
CLI::App app{"Mean Field Tests"};
app.allow_extras();
app.set_help_flag("--config-help", "Show mean-field configuration options");
fourdst::config::register_as_cli(cfg, app);
std::vector<std::string> config_arguments;
std::vector<std::string> forced_catch_arguments;
config_arguments.emplace_back(argv[0]);
bool parsing_catch_arguments = false;
for (int i = 1; i < argc; ++i) {
if (std::string_view(argv[i]) == "--catch2") {
parsing_catch_arguments = true;
continue;
}
if (parsing_catch_arguments) {
forced_catch_arguments.emplace_back(argv[i]);
} else {
config_arguments.emplace_back(argv[i]);
}
}
std::vector<const char*> config_argv;
config_argv.reserve(config_arguments.size());
for (const std::string& argument : config_arguments) {
config_argv.push_back(argument.c_str());
}
try {
app.parse(static_cast<int>(config_argv.size()), config_argv.data());
} catch (const CLI::ParseError& error) {
return app.exit(error);
}
std::vector<std::string> catch_arguments;
catch_arguments.emplace_back(argv[0]);
for (const std::string& argument : app.remaining()) {
catch_arguments.push_back(argument);
}
for (const std::string& argument : forced_catch_arguments) {
catch_arguments.push_back(argument);
}
const auto is_reporter_option = [](const std::string& argument) {
return argument == "-r" || argument == "--reporter" || argument.starts_with("-r=") || argument.starts_with("--reporter=");
};
if (const bool has_reporter = std::ranges::any_of(catch_arguments, is_reporter_option); !has_reporter) {
catch_arguments.emplace_back("--reporter");
catch_arguments.emplace_back("check");
}
std::vector<const char*> catch_argv;
catch_argv.reserve(catch_arguments.size());
for (const std::string& argument : catch_arguments) {
catch_argv.push_back(argument.c_str());
}
Catch::Session session;
if (const int catch_parse_result = session.applyCommandLine(static_cast<int>(catch_argv.size()), catch_argv.data()); catch_parse_result != 0) {
return catch_parse_result;
}
mfem::Mpi::Init(argc, argv);
constexpr std::string device_config = "cpu";
mfem::Device device(device_config);
const int hdiv_max_q1d = mfem::DeviceDofQuadLimits::Get().HDIV_MAX_Q1D;
std::cout << "H(div) maximum Q1D = " << hdiv_max_q1d << '\n';
std::cout << "Approximate maximum safe integration order = " << 2 * hdiv_max_q1d - 1 << '\n';
mean_field::utils::Args test_args = cfg.main();
if (app.count("--mesh_file") == 0) {
test_args.mesh_file = "sandbox.smesh";
}
if (app.count("--p.rtol") == 0) {
test_args.p.rtol = 1.0e-12;
}
if (app.count("--p.atol") == 0) {
test_args.p.atol = 1.0e-12;
}
test_utils::set_args(std::move(test_args));
return session.run();
}