Merge branch 'main' into feature/pointwisePolytrope

This commit is contained in:
2025-03-26 11:38:07 -04:00
86 changed files with 15850 additions and 2170 deletions

View File

@@ -7,24 +7,34 @@ on:
pull_request:
jobs:
build-and-test:
build-and-test-ubuntu:
strategy:
matrix:
os: [ubuntu-latest]
os: [ubuntu-24.04]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set GCC 13 as default
run: |
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 100 --slave /usr/bin/g++ g++ /usr/bin/g++-13
- name: Verify GCC Version
run: gcc --version # Should output 13.x if alternatives were updated, or check gcc-13 --version
- name: Set up dependencies
run: |
sudo apt-get update
sudo apt-get install -y cmake build-essential meson ninja-build python3 python3-pip libgtest-dev
pip install meson==1.6.0
# Compile gtest manually for Ubuntu
cd /usr/src/googletest/googletest && sudo cmake . && sudo make && sudo cp lib/*.a /usr/lib
sudo apt-get install -y python3 python3-pip
- name: Install Dependencies and Build
run: |
yes | ./mk
- name: Run build and tests
run: ./mk
- name: Run Tests
run: |
source ~/.4DSSE_env/bin/activate
meson test -C build

5
.gitignore vendored
View File

@@ -63,9 +63,14 @@ subprojects/tetgen/
subprojects/yaml-cpp/
subprojects/quill/
subprojects/googletest-1.15.2/
subprojects/opat-core/
.vscode/
*.log
output/
.boost_installed
4DSSE_logs/
.last_build_flags

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>.

View File

@@ -1,469 +0,0 @@
CODATA 2022 + astrophysical constants
Most quantities have been converted to CGS
Generated on Feb 10, 2025
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Reference:
Mohr, P. , Tiesinga, E. , Newell, D. and Taylor, B. (2024), Codata Internationally Recommended 2022 Values of the Fundamental Physical Constants,
Codata Internationally Recommended 2022 Values of the Fundamental Physical Constants,
[online], https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=958002, https://physics.nist.gov/constants (Accessed February 10, 2025)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Symbol Name Value Unit Uncertainty Source
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
weinK Wien displacement law constant 2.89776850e-01 K cm 5.10000000e-07 CODATA2022
au1Hyper atomic unit of 1st hyperpolarizablity 3.20636151e-53 C^3 m^3 J^-2 2.80000000e-60 CODATA2022
au2Hyper atomic unit of 2nd hyperpolarizablity 6.23538080e-65 C^4 m^4 J^-3 1.10000000e-71 CODATA2022
auEDip atomic unit of electric dipole moment 8.47835309e-30 C m 7.30000000e-37 CODATA2022
auEPol atomic unit of electric polarizablity 1.64877727e-41 C^2 m^2 J^-1 1.60000000e-49 CODATA2022
auEQuad atomic unit of electric quadrupole moment 4.48655124e-40 C m^2 3.90000000e-47 CODATA2022
auMDip atomic unit of magn. dipole moment 1.85480190e-23 J T^-1 1.60000000e-30 CODATA2022
auMFlux atomic unit of magn. flux density 2.35051757e+09 G 7.10000000e-01 CODATA2022
muD deuteron magn. moment 4.33073482e-27 J T^-1 3.80000000e-34 CODATA2022
muD_Bhor deuteron magn. moment to Bohr magneton ratio 4.66975457e-04 5.00000000e-12 CODATA2022
muD_Nuc deuteron magn. moment to nuclear magneton ratio 8.57438233e-01 9.20000000e-09 CODATA2022
muD_e deuteron-electron magn. moment ratio -4.66434555e-04 5.00000000e-12 CODATA2022
muD_p deuteron-proton magn. moment ratio 3.07012208e-01 4.50000000e-09 CODATA2022
muD_n deuteron-neutron magn. moment ratio -4.48206520e-01 1.10000000e-07 CODATA2022
rgE electron gyromagn. ratio 1.76085963e+11 s^-1 T^-1 5.30000000e+01 CODATA2022
rgE_2pi electron gyromagn. ratio over 2 pi 2.80249532e+04 MHz T^-1 2.40000000e-03 CODATA2022
muE electron magn. moment -9.28476412e-24 J T^-1 8.00000000e-31 CODATA2022
muE_Bhor electron magn. moment to Bohr magneton ratio -1.00115965e+00 3.80000000e-12 CODATA2022
muE_Nuc electron magn. moment to nuclear magneton ratio -1.83828197e+03 8.50000000e-07 CODATA2022
muE_anom electron magn. moment anomaly 1.15965219e-03 3.80000000e-12 CODATA2022
muE_muP_shield electron to shielded proton magn. moment ratio -6.58227596e+02 7.10000000e-06 CODATA2022
muE_muH_shield electron to shielded helion magn. moment ratio 8.64058255e+02 1.00000000e-05 CODATA2022
muE_D electron-deuteron magn. moment ratio -2.14392349e+03 2.30000000e-05 CODATA2022
muE_mu electron-muon magn. moment ratio 2.06766989e+02 5.40000000e-06 CODATA2022
muE_n electron-neutron magn. moment ratio 9.60920500e+02 2.30000000e-04 CODATA2022
muE_p electron-proton magn. moment ratio -6.58210686e+02 6.60000000e-06 CODATA2022
mu0 magn. constant 1.25663706e-06 N A^-2 0.00000000e+00 CODATA2022
phi0 magn. flux quantum 2.06783385e-15 Wb 0.00000000e+00 CODATA2022
muMu muon magn. moment -4.49044799e-26 J T^-1 4.00000000e-33 CODATA2022
muMu_Bhor muon magn. moment to Bohr magneton ratio -4.84197045e-03 1.30000000e-10 CODATA2022
muMu_Nuc muon magn. moment to nuclear magneton ratio -8.89059698e+00 2.30000000e-07 CODATA2022
muMu_p muon-proton magn. moment ratio -3.18334512e+00 8.90000000e-08 CODATA2022
rgN neutron gyromagn. ratio 1.83247171e+08 s^-1 T^-1 4.30000000e+01 CODATA2022
rgN_2pi neutron gyromagn. ratio over 2 pi 2.91646950e+01 MHz T^-1 7.30000000e-06 CODATA2022
muN neutron magn. moment -9.66236450e-27 J T^-1 2.40000000e-33 CODATA2022
muN_Bhor neutron magn. moment to Bohr magneton ratio -1.04187563e-03 2.50000000e-10 CODATA2022
muN_Nuc neutron magn. moment to nuclear magneton ratio -1.91304273e+00 4.50000000e-07 CODATA2022
muN_p_shield neutron to shielded proton magn. moment ratio -6.84996940e-01 1.60000000e-07 CODATA2022
muN_e neutron-electron magn. moment ratio 1.04066882e-03 2.50000000e-10 CODATA2022
muN_p neutron-proton magn. moment ratio -6.84979340e-01 1.60000000e-07 CODATA2022
rgP proton gyromagn. ratio 2.67522187e+08 s^-1 T^-1 1.10000000e-01 CODATA2022
rgP_2pi proton gyromagn. ratio over 2 pi 4.25774813e+01 MHz T^-1 3.70000000e-06 CODATA2022
muP proton magn. moment 1.41060671e-26 J T^-1 1.20000000e-33 CODATA2022
muP_Bhor proton magn. moment to Bohr magneton ratio 1.52103221e-03 1.50000000e-11 CODATA2022
muP_Nuc proton magn. moment to nuclear magneton ratio 2.79284735e+00 2.80000000e-08 CODATA2022
muP_shield proton magn. shielding correction 2.56890000e-05 1.10000000e-08 CODATA2022
muP_n proton-neutron magn. moment ratio -1.45989805e+00 3.40000000e-07 CODATA2022
rgH shielded helion gyromagn. ratio 2.03789457e+08 s^-1 T^-1 2.40000000e+00 CODATA2022
rgH_2pi shielded helion gyromagn. ratio over 2 pi 3.24341015e+01 MHz T^-1 2.80000000e-06 CODATA2022
muH_shield shielded helion magn. moment -1.07455302e-26 J T^-1 9.30000000e-34 CODATA2022
muH_shield_Bhor shielded helion magn. moment to Bohr magneton rati -1.15867147e-03 1.40000000e-11 CODATA2022
muH_shield_Nuc shielded helion magn. moment to nuclear magneton r -2.12749772e+00 2.50000000e-08 CODATA2022
muH_shield_p shielded helion to proton magn. moment ratio -7.61766562e-01 1.20000000e-08 CODATA2022
muH_shield_p_shield shielded helion to shielded proton magn. moment ra -7.61786131e-01 3.30000000e-09 CODATA2022
muP_shield shielded proton magn. moment 1.41057047e-26 J T^-1 1.20000000e-33 CODATA2022
muP_shield_Bhor shielded proton magn. moment to Bohr magneton rati 1.52099313e-03 1.60000000e-11 CODATA2022
muP_shield_Nuc shielded proton magn. moment to nuclear magneton r 2.79277560e+00 3.00000000e-08 CODATA2022
aSi_220 {220} lattice spacing of silicon 1.92015571e-08 cm 3.20000000e-16 CODATA2022
aSi lattice spacing of silicon 1.92015576e-08 cm 5.00000000e-16 CODATA2022
mAlpha_e alpha particle-electron mass ratio 7.29429954e+03 2.40000000e-07 CODATA2022
mAlpha alpha particle mass 6.64465734e-24 g 2.00000000e-33 CODATA2022
EAlpha alpha particle mass energy equivalent 5.97192019e-03 erg 1.80000000e-12 CODATA2022
EAlpha_MeV alpha particle mass energy equivalent in MeV 5.97192019e-03 erg 1.76239430e-12 CODATA2022
mAlpha_u alpha particle mass in u 6.64465734e-24 g 1.04613961e-34 CODATA2022
MAlpha alpha particle molar mass 4.00150618e+00 g / mol 1.20000000e-09 CODATA2022
mAlpha_p alpha particle-proton mass ratio 3.97259969e+00 2.20000000e-10 CODATA2022
angstromStar Angstrom star 1.00001495e-08 cm 9.00000000e-15 CODATA2022
mU atomic mass constant 1.66053907e-24 g 5.00000000e-34 CODATA2022
mU_E atomic mass constant energy equivalent 1.49241809e-03 erg 4.50000000e-13 CODATA2022
mU_E_MeV atomic mass constant energy equivalent in MeV 1.49241809e-03 erg 4.48609458e-13 CODATA2022
mU_eV atomic mass unit-electron volt relationship 1.49241809e-03 erg 4.48609458e-13 CODATA2022
mU_hartree atomic mass unit-hartree relationship 3.42317769e+07 E_h 1.00000000e-02 CODATA2022
mU_Hz atomic mass unit-hertz relationship 2.25234272e+23 1 / s 6.80000000e+13 CODATA2022
mU_invm atomic mass unit-inverse meter relationship 7.51300661e+12 1 / cm 2.30000000e+03 CODATA2022
mU_J atomic mass unit-joule relationship 1.49241809e-03 erg 4.50000000e-13 CODATA2022
mU_K atomic mass unit-kelvin relationship 1.08095402e+13 K 3.30000000e+03 CODATA2022
mU_kg atomic mass unit-kilogram relationship 1.66053907e-24 g 5.00000000e-34 CODATA2022
au1Hyper atomic unit of 1st hyperpolarizability 3.20636131e-53 C^3 m^3 J^-2 1.50000000e-62 CODATA2022
au2Hyper atomic unit of 2nd hyperpolarizability 6.23537999e-65 C^4 m^4 J^-3 3.80000000e-74 CODATA2022
auAct atomic unit of action 1.05457182e-27 erg s 0.00000000e+00 CODATA2022
auC atomic unit of charge 1.60217663e-19 C 0.00000000e+00 CODATA2022
auCrho atomic unit of charge density 1.08120238e+12 C m^-3 4.90000000e+02 CODATA2022
auI atomic unit of current 6.62361824e-03 A 1.30000000e-14 CODATA2022
auMu atomic unit of electric dipole mom. 8.47835363e-30 C m 1.30000000e-39 CODATA2022
auE atomic unit of electric field 5.14220675e+11 V m^-1 7.80000000e+01 CODATA2022
auEFG atomic unit of electric field gradient 9.71736243e+21 V m^-2 2.90000000e+12 CODATA2022
auPol atomic unit of electric polarizability 1.64877727e-41 C^2 m^2 J^-1 5.00000000e-51 CODATA2022
auV atomic unit of electric potential 2.72113862e+01 V 5.30000000e-11 CODATA2022
auQuad atomic unit of electric quadrupole mom. 4.48655152e-40 C m^2 1.40000000e-49 CODATA2022
Eh atomic unit of energy 4.35974472e-11 erg 8.50000000e-23 CODATA2022
auF atomic unit of force 8.23872350e-03 dyn 1.20000000e-12 CODATA2022
auL atomic unit of length 5.29177211e-09 cm 8.00000000e-19 CODATA2022
auM atomic unit of mag. dipole mom. 1.85480202e-23 J T^-1 5.60000000e-33 CODATA2022
auB atomic unit of mag. flux density 2.35051757e+09 G 7.10000000e-01 CODATA2022
auChi atomic unit of magnetizability 7.89103660e-29 J T^-2 4.80000000e-38 CODATA2022
amu atomic unit of mass 9.10938370e-28 g 2.80000000e-37 CODATA2022
aup atomic unit of momentum 1.99285191e-19 dyn s 3.00000000e-29 CODATA2022
auEps atomic unit of permittivity 1.11265006e-10 F m^-1 1.70000000e-20 CODATA2022
aut atomic unit of time 2.41888433e-17 s 4.70000000e-29 CODATA2022
auv atomic unit of velocity 2.18769126e+08 cm / s 3.30000000e-02 CODATA2022
N_a Avogadro constant 6.02214076e+23 1 / mol 0.00000000e+00 CODATA2022
mu_B Bohr magneton 9.27401008e-24 J T^-1 2.80000000e-33 CODATA2022
mu_B_eV_T Bohr magneton in eV/T 5.78838181e-05 eV T^-1 1.70000000e-14 CODATA2022
mu_B_Hz_T Bohr magneton in Hz/T 1.39962449e+10 Hz T^-1 4.20000000e+00 CODATA2022
mu_B__mT Bohr magneton in inverse meters per tesla 4.66864481e+01 m^-1 T^-1 2.90000000e-07 CODATA2022
muB_K_T Bohr magneton in K/T 6.71713816e-01 K T^-1 2.00000000e-10 CODATA2022
rBhor Bohr radius 5.29177211e-09 cm 8.00000000e-19 CODATA2022
kB Boltzmann constant 1.38064900e-16 erg / K 0.00000000e+00 CODATA2022
kB_eV_K Boltzmann constant in eV/K 1.38064900e-16 erg / K 0.00000000e+00 CODATA2022
kB_Hz_K Boltzmann constant in Hz/K 2.08366191e+10 1 / (K s) 0.00000000e+00 CODATA2022
kB__MK Boltzmann constant in inverse meters per kelvin 6.95034570e-01 1 / (K cm) 4.00000000e-07 CODATA2022
Z0 characteristic impedance of vacuum 3.76730314e+02 ohm 5.61366546e-08 CODATA2022
re classical electron radius 2.81794033e-13 cm 1.30000000e-22 CODATA2022
lambda_compt Compton wavelength 2.42631024e-10 cm 7.30000000e-20 CODATA2022
lambda_compt_2pi Compton wavelength over 2 pi 3.86159268e-11 cm 1.80000000e-20 CODATA2022
G0 conductance quantum 7.74809173e-05 S 0.00000000e+00 CODATA2022
K_J-90 conventional value of Josephson constant 4.83597900e+14 Hz V^-1 0.00000000e+00 CODATA2022
R_K-90 conventional value of von Klitzing constant 2.58128070e+04 ohm 0.00000000e+00 CODATA2022
xu(CuKa1) Cu x unit 1.00207697e-11 cm 2.80000000e-18 CODATA2022
muD_e deuteron-electron mag. mom. ratio -4.66434555e-04 1.20000000e-12 CODATA2022
mD_e deuteron-electron mass ratio 3.67048297e+03 1.30000000e-07 CODATA2022
g_D deuteron g factor 8.57438234e-01 2.20000000e-09 CODATA2022
muD deuteron mag. mom. 4.33073509e-27 J T^-1 1.10000000e-35 CODATA2022
muD_Bhor deuteron mag. mom. to Bohr magneton ratio 4.66975457e-04 1.20000000e-12 CODATA2022
muD_Nuc deuteron mag. mom. to nuclear magneton ratio 8.57438234e-01 2.20000000e-09 CODATA2022
mD deuteron mass 3.34358377e-24 g 1.00000000e-33 CODATA2022
mD_E deuteron mass energy equivalent 3.00506323e-03 erg 9.10000000e-13 CODATA2022
mD_E_MeV deuteron mass energy equivalent in MeV 3.00506323e-03 erg 9.13240681e-13 CODATA2022
mD_u deuteron mass in u 3.34358377e-24 g 6.64215627e-35 CODATA2022
MD deuteron molar mass 2.01355321e+00 g / mol 6.10000000e-10 CODATA2022
muD_n deuteron-neutron mag. mom. ratio -4.48206530e-01 1.10000000e-07 CODATA2022
muD_p deuteron-proton mag. mom. ratio 3.07012209e-01 7.90000000e-10 CODATA2022
mD_p deuteron-proton mass ratio 1.99900750e+00 1.10000000e-10 CODATA2022
RrmsD deuteron rms charge radius 2.12799000e-13 cm 7.40000000e-17 CODATA2022
eps_0 electric constant 8.85418781e-12 F m^-1 1.30000000e-21 CODATA2022
qE_m electron charge to mass quotient -1.75882001e+11 C kg^-1 5.30000000e+01 CODATA2022
muE_D electron-deuteron mag. mom. ratio -2.14392349e+03 5.60000000e-06 CODATA2022
mE_D electron-deuteron mass ratio 2.72443711e-04 9.60000000e-15 CODATA2022
g_e electron g factor -2.00231930e+00 3.50000000e-13 CODATA2022
rg_e electron gyromag. ratio 1.76085963e+11 s^-1 T^-1 5.30000000e+01 CODATA2022
rg_e_2pi electron gyromag. ratio over 2 pi 2.80249516e+04 MHz T^-1 1.70000000e-04 CODATA2022
muE electron mag. mom. -9.28476470e-24 J T^-1 2.80000000e-33 CODATA2022
muE_anom electron mag. mom. anomaly 1.15965218e-03 1.80000000e-13 CODATA2022
muE_Bhor electron mag. mom. to Bohr magneton ratio -1.00115965e+00 1.80000000e-13 CODATA2022
muE_Nuc electron mag. mom. to nuclear magneton ratio -1.83828197e+03 1.10000000e-07 CODATA2022
mE electron mass 9.10938370e-28 g 2.80000000e-37 CODATA2022
mE_E electron mass energy equivalent 8.18710578e-07 erg 2.50000000e-16 CODATA2022
mE_MeV electron mass energy equivalent in MeV 8.18710578e-07 erg 2.40326495e-16 CODATA2022
mE_u electron mass in u 9.10938370e-28 g 2.65686251e-38 CODATA2022
ME electron molar mass 5.48579909e-04 g / mol 1.70000000e-13 CODATA2022
muE_mu electron-muon mag. mom. ratio 2.06766988e+02 4.60000000e-06 CODATA2022
mE_mu electron-muon mass ratio 4.83633169e-03 1.10000000e-10 CODATA2022
muE_n electron-neutron mag. mom. ratio 9.60920500e+02 2.30000000e-04 CODATA2022
mE_n electron-neutron mass ratio 5.43867344e-04 2.60000000e-13 CODATA2022
muE_p electron-proton mag. mom. ratio -6.58210688e+02 2.00000000e-07 CODATA2022
mE_p electron-proton mass ratio 5.44617021e-04 3.30000000e-14 CODATA2022
mE_tau electron-tau mass ratio 2.87585000e-04 1.90000000e-08 CODATA2022
mE_alpha electron to alpha particle mass ratio 1.37093355e-04 4.50000000e-15 CODATA2022
muE_H_shield electron to shielded helion mag. mom. ratio 8.64058257e+02 1.00000000e-05 CODATA2022
muE_p_shield electron to shielded proton mag. mom. ratio -6.58227597e+02 7.20000000e-06 CODATA2022
eV electron volt 1.60217663e-12 erg 0.00000000e+00 CODATA2022
eV_amu electron volt-atomic mass unit relationship 1.78266192e-33 g 5.31372501e-43 CODATA2022
eV_hartree electron volt-hartree relationship 3.67493222e-02 E_h 7.10000000e-14 CODATA2022
eV_Hz electron volt-hertz relationship 2.41798924e+14 1 / s 0.00000000e+00 CODATA2022
eV_invm electron volt-inverse meter relationship 8.06554394e+03 1 / cm 0.00000000e+00 CODATA2022
eV_J electron volt-joule relationship 1.60217663e-12 erg 0.00000000e+00 CODATA2022
eV_K electron volt-kelvin relationship 1.16045181e+04 K 0.00000000e+00 CODATA2022
eV_kg electron volt-kilogram relationship 1.78266192e-33 g 0.00000000e+00 CODATA2022
e elementary charge 1.60217663e-19 C 0.00000000e+00 CODATA2022
e_h elementary charge over h 2.41798926e+14 A J^-1 1.50000000e+06 CODATA2022
F Faraday constant 9.64853321e+04 C mol^-1 0.00000000e+00 CODATA2022
F_conv Faraday constant for conventional electric current 9.64853251e+04 C_90 mol^-1 1.20000000e-03 CODATA2022
G_F Fermi coupling constant 4.54379566e+00 s4 / (g2 cm4) 2.33738613e-06 CODATA2022
alpha fine-structure constant 7.29735257e-03 1.10000000e-12 CODATA2022
c1 first radiation constant 3.74177185e-05 St erg 0.00000000e+00 CODATA2022
c1L first radiation constant for spectral radiance 1.19104297e-05 St erg / rad2 0.00000000e+00 CODATA2022
Eh_amu hartree-atomic mass unit relationship 4.85087021e-32 g 1.46127438e-41 CODATA2022
Eh_eV hartree-electron volt relationship 4.35974472e-11 erg 8.49153616e-23 CODATA2022
Eh Hartree energy 4.35974472e-11 erg 8.50000000e-23 CODATA2022
Eh_E_eV Hartree energy in eV 4.35974472e-11 erg 8.49153616e-23 CODATA2022
Eh_Hz hartree-hertz relationship 6.57968392e+15 1 / s 1.30000000e+04 CODATA2022
Eh_invm hartree-inverse meter relationship 2.19474631e+05 1 / cm 4.30000000e-07 CODATA2022
Eh_J hartree-joule relationship 4.35974472e-11 erg 8.50000000e-23 CODATA2022
Eh_K hartree-kelvin relationship 3.15775025e+05 K 6.10000000e-07 CODATA2022
Eh_kg hartree-kilogram relationship 4.85087021e-32 g 9.40000000e-44 CODATA2022
mH_e helion-electron mass ratio 5.49588528e+03 2.40000000e-07 CODATA2022
mH helion mass 5.00641278e-24 g 1.50000000e-33 CODATA2022
mH_E helion mass energy equivalent 4.49953941e-03 erg 1.40000000e-12 CODATA2022
mH_E_eV helion mass energy equivalent in MeV 4.49953941e-03 erg 1.36185014e-12 CODATA2022
mH_u helion mass in u 5.00641278e-24 g 1.61072289e-34 CODATA2022
MH helion molar mass 3.01493225e+00 g / mol 9.10000000e-10 CODATA2022
mH_p helion-proton mass ratio 2.99315267e+00 1.30000000e-10 CODATA2022
Hz_amu hertz-atomic mass unit relationship 7.37249732e-48 g 2.15870079e-57 CODATA2022
Hz_eV hertz-electron volt relationship 6.62607015e-27 erg 0.00000000e+00 CODATA2022
Hz_Eh hertz-hartree relationship 1.51982985e-16 E_h 2.90000000e-28 CODATA2022
Hz_invm hertz-inverse meter relationship 3.33564095e-11 1 / cm 0.00000000e+00 CODATA2022
Hz_J hertz-joule relationship 6.62607015e-27 erg 0.00000000e+00 CODATA2022
Hz_K hertz-kelvin relationship 4.79924307e-11 K 0.00000000e+00 CODATA2022
Hz_kg hertz-kilogram relationship 7.37249732e-48 g 0.00000000e+00 CODATA2022
invalpha inverse fine-structure constant 1.37035999e+02 2.10000000e-08 CODATA2022
invm_amu inverse meter-atomic mass unit relationship 2.21021909e-39 g 6.64215627e-49 CODATA2022
invm_eV inverse meter-electron volt relationship 1.98644586e-18 erg 0.00000000e+00 CODATA2022
invm_Eh inverse meter-hartree relationship 4.55633525e-08 E_h 8.80000000e-20 CODATA2022
invm_Hz inverse meter-hertz relationship 2.99792458e+08 1 / s 0.00000000e+00 CODATA2022
invm_J inverse meter-joule relationship 1.98644586e-18 erg 0.00000000e+00 CODATA2022
invm_K inverse meter-kelvin relationship 1.43877688e-02 K 0.00000000e+00 CODATA2022
invm_kg inverse meter-kilogram relationship 2.21021909e-39 g 0.00000000e+00 CODATA2022
invG0 inverse of conductance quantum 1.29064037e+04 ohm 0.00000000e+00 CODATA2022
K_J Josephson constant 4.83597848e+14 Hz V^-1 0.00000000e+00 CODATA2022
J_amu joule-atomic mass unit relationship 1.11265006e-14 g 3.32107813e-24 CODATA2022
J_eV joule-electron volt relationship 1.00000000e+07 erg 0.00000000e+00 CODATA2022
J_Eh joule-hartree relationship 2.29371228e+17 E_h 4.50000000e+05 CODATA2022
J_Hz joule-hertz relationship 1.50919018e+33 1 / s 0.00000000e+00 CODATA2022
J_invm joule-inverse meter relationship 5.03411657e+22 1 / cm 0.00000000e+00 CODATA2022
J_K joule-kelvin relationship 7.24297052e+22 K 0.00000000e+00 CODATA2022
J_kg joule-kilogram relationship 1.11265006e-14 g 0.00000000e+00 CODATA2022
K_amu kelvin-atomic mass unit relationship 1.53617919e-37 g 4.64950939e-47 CODATA2022
K_eV kelvin-electron volt relationship 1.38064900e-16 erg 0.00000000e+00 CODATA2022
K_Eh kelvin-hartree relationship 3.16681156e-06 E_h 6.10000000e-18 CODATA2022
K_Hz kelvin-hertz relationship 2.08366191e+10 1 / s 0.00000000e+00 CODATA2022
K_invm kelvin-inverse meter relationship 6.95034800e-01 1 / cm 0.00000000e+00 CODATA2022
K_J kelvin-joule relationship 1.38064900e-16 erg 0.00000000e+00 CODATA2022
K_kg kelvin-kilogram relationship 1.53617919e-37 g 0.00000000e+00 CODATA2022
kg_amu kilogram-atomic mass unit relationship 1.00000000e+03 g 2.98897032e-07 CODATA2022
kg_eV kilogram-electron volt relationship 8.98755179e+23 erg 0.00000000e+00 CODATA2022
kg_Eh kilogram-hartree relationship 2.06148579e+34 E_h 4.00000000e+22 CODATA2022
kg_Hz kilogram-hertz relationship 1.35639249e+50 1 / s 0.00000000e+00 CODATA2022
kg_invm kilogram-inverse meter relationship 4.52443833e+39 1 / cm 0.00000000e+00 CODATA2022
kg_J kilogram-joule relationship 8.98755179e+23 erg 0.00000000e+00 CODATA2022
kg_K kilogram-kelvin relationship 6.50965726e+39 K 0.00000000e+00 CODATA2022
aSi lattice parameter of silicon 5.43102051e-08 cm 8.90000000e-16 CODATA2022
n0 Loschmidt constant (273.15 K, 101.325 kPa) 2.68678011e+19 1 / cm3 0.00000000e+00 CODATA2022
mu0 mag. constant 1.25663706e-06 N A^-2 1.90000000e-16 CODATA2022
Phi0 mag. flux quantum 2.06783385e-15 Wb 0.00000000e+00 CODATA2022
R molar gas constant 8.31446262e+07 erg / (K mol) 0.00000000e+00 CODATA2022
Mu molar mass constant 1.00000000e+00 g / mol 3.00000000e-10 CODATA2022
MC12 molar mass of carbon-12 1.20000000e+01 g / mol 3.60000000e-09 CODATA2022
h_mol molar Planck constant 3.99031271e-03 St g / mol 0.00000000e+00 CODATA2022
ch_mol molar Planck constant times c 1.19626566e+08 cm erg / mol 5.40000000e-02 CODATA2022
v_mol_ideal_100kPa molar volume of ideal gas (273.15 K, 100 kPa) 2.27109546e+04 cm3 / mol 0.00000000e+00 CODATA2022
v_mol_ideal_101.325kPa molar volume of ideal gas (273.15 K, 101.325 kPa) 2.24139695e+04 cm3 / mol 0.00000000e+00 CODATA2022
vSI_mol molar volume of silicon 1.20588320e+01 cm3 / mol 6.00000000e-07 CODATA2022
xu Mo x unit 1.00209952e-11 cm 5.30000000e-18 CODATA2022
lambda_compt_mu muon Compton wavelength 1.17344411e-12 cm 2.60000000e-20 CODATA2022
lambda_compt_mu_2pi muon Compton wavelength over 2 pi 1.86759431e-13 cm 4.20000000e-21 CODATA2022
mMu_e muon-electron mass ratio 2.06768283e+02 4.60000000e-06 CODATA2022
g_mu muon g factor -2.00233184e+00 1.30000000e-09 CODATA2022
muMu muon mag. mom. -4.49044830e-26 J T^-1 1.00000000e-33 CODATA2022
muMu_anom muon mag. mom. anomaly 1.16592089e-03 6.30000000e-10 CODATA2022
muMu_Bhor muon mag. mom. to Bohr magneton ratio -4.84197047e-03 1.10000000e-10 CODATA2022
muMu_Nuc muon mag. mom. to nuclear magneton ratio -8.89059703e+00 2.00000000e-07 CODATA2022
mMu muon mass 1.88353163e-25 g 4.20000000e-33 CODATA2022
mMu_E muon mass energy equivalent 1.69283380e-04 erg 3.80000000e-12 CODATA2022
mMu_E_MeV muon mass energy equivalent in MeV 1.69283380e-04 erg 3.68500626e-12 CODATA2022
mMu_E_u muon mass in u 1.88353163e-25 g 4.15134767e-33 CODATA2022
MMu muon molar mass 1.13428926e-01 g / mol 2.50000000e-09 CODATA2022
mMu_n muon-neutron mass ratio 1.12454517e-01 2.50000000e-09 CODATA2022
muMu_p muon-proton mag. mom. ratio -3.18334514e+00 7.10000000e-08 CODATA2022
mMu_p muon-proton mass ratio 1.12609526e-01 2.50000000e-09 CODATA2022
mMu_tau muon-tau mass ratio 5.94635000e-02 4.00000000e-06 CODATA2022
1 natural unit of action 1.05457182e-27 erg s 0.00000000e+00 CODATA2022
1_eV_s natural unit of action in eV s 1.05457182e-27 erg s 0.00000000e+00 CODATA2022
E natural unit of energy 8.18710578e-07 erg 2.50000000e-16 CODATA2022
E_MeV natural unit of energy in MeV 8.18710578e-07 erg 2.40326495e-16 CODATA2022
L natural unit of length 3.86159268e-11 cm 1.20000000e-20 CODATA2022
M natural unit of mass 9.10938370e-28 g 2.80000000e-37 CODATA2022
p natural unit of momentum 2.73092449e-17 dyn s 3.40000000e-25 CODATA2022
p_MeV_c natural unit of momentum in MeV/c 5.10998946e-01 MeV/c 3.10000000e-09 CODATA2022
t natural unit of time 1.28808867e-21 s 3.90000000e-31 CODATA2022
v natural unit of velocity 2.99792458e+10 cm / s 0.00000000e+00 CODATA2022
lambda_compt_n neutron Compton wavelength 1.31959091e-13 cm 7.50000000e-23 CODATA2022
lambda_compt_n_2pi neutron Compton wavelength over 2 pi 2.10019415e-14 cm 1.40000000e-23 CODATA2022
muN_e neutron-electron mag. mom. ratio 1.04066882e-03 2.50000000e-10 CODATA2022
mN_e neutron-electron mass ratio 1.83868366e+03 8.90000000e-07 CODATA2022
g_n neutron g factor -3.82608545e+00 9.00000000e-07 CODATA2022
rg_n neutron gyromag. ratio 1.83247171e+08 s^-1 T^-1 4.30000000e+01 CODATA2022
rg_n_2pi neutron gyromag. ratio over 2 pi 2.91646933e+01 MHz T^-1 6.90000000e-06 CODATA2022
muN neutron mag. mom. -9.66236510e-27 J T^-1 2.30000000e-33 CODATA2022
muN_Bhor neutron mag. mom. to Bohr magneton ratio -1.04187563e-03 2.50000000e-10 CODATA2022
muN_Nuc neutron mag. mom. to nuclear magneton ratio -1.91304273e+00 4.50000000e-07 CODATA2022
mN neutron mass 1.67492750e-24 g 9.50000000e-34 CODATA2022
mN_E neutron mass energy equivalent 1.50534976e-03 erg 8.60000000e-13 CODATA2022
mN_E_MeV neutron mass energy equivalent in MeV 1.50534976e-03 erg 8.65175382e-13 CODATA2022
mN_u neutron mass in u 1.67492750e-24 g 8.13664143e-34 CODATA2022
MN neutron molar mass 1.00866492e+00 g / mol 5.70000000e-10 CODATA2022
mN_mu neutron-muon mass ratio 8.89248406e+00 2.00000000e-07 CODATA2022
muN_p neutron-proton mag. mom. ratio -6.84979340e-01 1.60000000e-07 CODATA2022
mN_p neutron-proton mass ratio 1.00137842e+00 4.90000000e-10 CODATA2022
mN_tau neutron-tau mass ratio 5.28779000e-01 3.60000000e-05 CODATA2022
muN_p_shield neutron to shielded proton mag. mom. ratio -6.84996940e-01 1.60000000e-07 CODATA2022
G Newtonian constant of gravitation 6.67430000e-08 cm3 / (g s2) 1.50000000e-12 CODATA2022
G_hbar_c Newtonian constant of gravitation over h-bar c 6.70883000e-39 (GeV/c^2)^-2 1.50000000e-43 CODATA2022
mu_N nuclear magneton 5.05078375e-27 J T^-1 1.50000000e-36 CODATA2022
mu_N_eV_T nuclear magneton in eV/T 3.15245126e-08 eV T^-1 9.60000000e-18 CODATA2022
mu_N_invm_T nuclear magneton in inverse meters per tesla 2.54262343e-02 m^-1 T^-1 1.60000000e-10 CODATA2022
mu_N_K_T nuclear magneton in K/T 3.65826778e-04 K T^-1 1.10000000e-13 CODATA2022
mu_N_MHz_T nuclear magneton in MHz/T 7.62259323e+00 MHz T^-1 2.30000000e-09 CODATA2022
h Planck constant 6.62607015e-27 erg s 0.00000000e+00 CODATA2022
h_eV_s Planck constant in eV s 6.62607009e-27 erg s 4.00544159e-35 CODATA2022
hbar Planck constant over 2 pi 1.05457180e-27 erg s 1.30000000e-35 CODATA2022
hbar_eV_s Planck constant over 2 pi in eV s 1.05457181e-27 erg s 6.40870654e-36 CODATA2022
chbar_MeV Planck constant over 2 pi times c in MeV fm 3.16152675e-17 cm erg 1.92261196e-25 CODATA2022
planck_length Planck length 1.61625500e-33 cm 1.80000000e-38 CODATA2022
planck_mass Planck mass 2.17643400e-05 g 2.40000000e-10 CODATA2022
planck_mass_E_GeV Planck mass energy equivalent in GeV 1.95608143e+16 erg 2.24304729e+11 CODATA2022
planck_temp Planck temperature 1.41678400e+32 K 1.60000000e+27 CODATA2022
plank_time Planck time 5.39124700e-44 s 6.00000000e-49 CODATA2022
qP_mP proton charge to mass quotient 9.57883316e+07 C kg^-1 2.90000000e-02 CODATA2022
lambda_compt_p proton Compton wavelength 1.32140986e-13 cm 4.00000000e-23 CODATA2022
lambda_compt_p_2pi proton Compton wavelength over 2 pi 2.10308910e-14 cm 9.70000000e-24 CODATA2022
mP_e proton-electron mass ratio 1.83615267e+03 1.10000000e-07 CODATA2022
g_p proton g factor 5.58569469e+00 1.60000000e-09 CODATA2022
rg_p proton gyromag. ratio 2.67522187e+08 s^-1 T^-1 1.10000000e-01 CODATA2022
rg_p_2pi proton gyromag. ratio over 2 pi 4.25774789e+01 MHz T^-1 2.90000000e-07 CODATA2022
muP proton mag. mom. 1.41060680e-26 J T^-1 6.00000000e-36 CODATA2022
muP_Bhor proton mag. mom. to Bohr magneton ratio 1.52103220e-03 4.60000000e-13 CODATA2022
muP_Nuc proton mag. mom. to nuclear magneton ratio 2.79284734e+00 8.20000000e-10 CODATA2022
muP_shield proton mag. shielding correction 2.56890000e-05 1.10000000e-08 CODATA2022
mP proton mass 1.67262192e-24 g 5.10000000e-34 CODATA2022
mP_E proton mass energy equivalent 1.50327762e-03 erg 4.60000000e-13 CODATA2022
mP_E_MeV proton mass energy equivalent in MeV 1.50327762e-03 erg 4.64631224e-13 CODATA2022
mP_u proton mass in u 1.67262192e-24 g 8.80085705e-35 CODATA2022
MP proton molar mass 1.00727647e+00 g / mol 3.10000000e-10 CODATA2022
mP_mu proton-muon mass ratio 8.88024337e+00 2.00000000e-07 CODATA2022
muP_n proton-neutron mag. mom. ratio -1.45989805e+00 3.40000000e-07 CODATA2022
mP_n proton-neutron mass ratio 9.98623478e-01 4.90000000e-10 CODATA2022
RrmsP proton rms charge radius 8.41400000e-14 cm 1.90000000e-16 CODATA2022
mP_tau proton-tau mass ratio 5.28051000e-01 3.60000000e-05 CODATA2022
kappa quantum of circulation 3.63694755e+00 cm2 / s 1.10000000e-09 CODATA2022
2kappa quantum of circulation times 2 7.27389510e+00 cm2 / s 2.20000000e-09 CODATA2022
Rinf Rydberg constant 1.09737316e+05 1 / cm 2.10000000e-07 CODATA2022
cRinf_Hz Rydberg constant times c in Hz 3.28984196e+15 1 / s 6.40000000e+03 CODATA2022
hcRinf_eV Rydberg constant times hc in eV 2.17987236e-11 erg 4.16565925e-23 CODATA2022
hcRinf_J Rydberg constant times hc in J 2.17987236e-11 erg 4.20000000e-23 CODATA2022
S0_R_100kPa Sackur-Tetrode constant (1 K, 100 kPa) -1.15170754e+00 4.50000000e-10 CODATA2022
S0_R_101.325kPa Sackur-Tetrode constant (1 K, 101.325 kPa) -1.16487052e+00 4.50000000e-10 CODATA2022
c2 second radiation constant 1.43877688e+00 K cm 0.00000000e+00 CODATA2022
rg_h_shield shielded helion gyromag. ratio 2.03789457e+08 s^-1 T^-1 2.40000000e+00 CODATA2022
rg_h_shield_2pi shielded helion gyromag. ratio over 2 pi 3.24340997e+01 MHz T^-1 4.30000000e-07 CODATA2022
muH_shield shielded helion mag. mom. -1.07455309e-26 J T^-1 1.30000000e-34 CODATA2022
muH_shield_Bhor shielded helion mag. mom. to Bohr magneton ratio -1.15867147e-03 1.40000000e-11 CODATA2022
muH_shield_Nuc shielded helion mag. mom. to nuclear magneton rati -2.12749772e+00 2.50000000e-08 CODATA2022
muH_shield_p shielded helion to proton mag. mom. ratio -7.61766562e-01 8.90000000e-09 CODATA2022
muH_shield_p_shield shielded helion to shielded proton mag. mom. ratio -7.61786131e-01 3.30000000e-09 CODATA2022
rg_p_shield shielded proton gyromag. ratio 2.67515315e+08 s^-1 T^-1 2.90000000e+00 CODATA2022
rg_p_shield_2pi shielded proton gyromag. ratio over 2 pi 4.25763851e+01 MHz T^-1 5.30000000e-07 CODATA2022
muP_shield shielded proton mag. mom. 1.41057056e-26 J T^-1 1.50000000e-34 CODATA2022
muP_shield_Bhor shielded proton mag. mom. to Bohr magneton ratio 1.52099313e-03 1.70000000e-11 CODATA2022
muP_shield_Nuc shielded proton mag. mom. to nuclear magneton rati 2.79277560e+00 3.00000000e-08 CODATA2022
c speed of light in vacuum 2.99792458e+10 cm / s 0.00000000e+00 CODATA2022
g standard acceleration of gravity 9.80665000e+02 cm / s2 0.00000000e+00 CODATA2022
atm standard atmosphere 1.01325000e+06 P / s 0.00000000e+00 CODATA2022
sigma Stefan-Boltzmann constant 5.67037442e-05 g / (s3 K4) 0.00000000e+00 CODATA2022
lambda_compt_tau tau Compton wavelength 6.97771000e-14 cm 4.70000000e-18 CODATA2022
lambda_compt_tau_2pi tau Compton wavelength over 2 pi 1.11056000e-14 cm 1.00000000e-18 CODATA2022
mTau_e tau-electron mass ratio 3.47723000e+03 2.30000000e-01 CODATA2022
mTau tau mass 3.16754000e-24 g 2.10000000e-28 CODATA2022
mTau_E tau mass energy equivalent 2.84684000e-03 erg 1.90000000e-07 CODATA2022
mTau_E_MeV tau mass energy equivalent in MeV 2.84677949e-03 erg 2.56348261e-07 CODATA2022
mTau_u tau mass in u 3.16754469e-24 g 2.15870079e-28 CODATA2022
MTau tau molar mass 1.90754000e+00 g / mol 1.30000000e-04 CODATA2022
mTau_mu tau-muon mass ratio 1.68170000e+01 1.10000000e-03 CODATA2022
mTau_n tau-neutron mass ratio 1.89115000e+00 1.30000000e-04 CODATA2022
mTau_p tau-proton mass ratio 1.89376000e+00 1.30000000e-04 CODATA2022
sigma_T Thomson cross section 6.65245873e-25 cm2 6.00000000e-34 CODATA2022
muPsi_e triton-electron mag. mom. ratio -1.62051442e-03 2.10000000e-11 CODATA2022
mPsi_e triton-electron mass ratio 5.49692154e+03 2.70000000e-07 CODATA2022
g_psi triton g factor 5.95792493e+00 1.20000000e-08 CODATA2022
muPsi triton mag. mom. 1.50460952e-26 J T^-1 3.00000000e-35 CODATA2022
muPsi_Bhor triton mag. mom. to Bohr magneton ratio 1.62239367e-03 3.20000000e-12 CODATA2022
muPsi_Nuc triton mag. mom. to nuclear magneton ratio 2.97896247e+00 5.90000000e-09 CODATA2022
mPsi triton mass 5.00735674e-24 g 1.50000000e-33 CODATA2022
mPsi_E triton mass energy equivalent 4.50038781e-03 erg 1.40000000e-12 CODATA2022
mPsi_E_MeV triton mass energy equivalent in MeV 4.50038781e-03 erg 1.36185014e-12 CODATA2022
mPsi_u triton mass in u 5.00735674e-24 g 1.99264688e-34 CODATA2022
MPsi triton molar mass 3.01550072e+00 g / mol 9.20000000e-10 CODATA2022
muPsi_n triton-neutron mag. mom. ratio -1.55718553e+00 3.70000000e-07 CODATA2022
muPsi_p triton-proton mag. mom. ratio 1.06663991e+00 1.00000000e-08 CODATA2022
mPsi_p triton-proton mass ratio 2.99371703e+00 1.50000000e-10 CODATA2022
u unified atomic mass unit 1.66053907e-24 g 5.00000000e-34 CODATA2022
R_K von Klitzing constant 2.58128075e+04 ohm 0.00000000e+00 CODATA2022
theta_W weak mixing angle 2.22900000e-01 3.00000000e-04 CODATA2022
b_freq Wien frequency displacement law constant 5.87892576e+10 1 / (K s) 0.00000000e+00 CODATA2022
b_lambda Wien wavelength displacement law constant 2.89777196e-01 K cm 0.00000000e+00 CODATA2022
auMom_um atomic unit of mom.um 1.99285188e-19 dyn s 2.40000000e-27 CODATA2022
mE_h electron-helion mass ratio 1.81954307e-04 7.90000000e-15 CODATA2022
mE_psi electron-triton mass ratio 1.81920006e-04 9.00000000e-15 CODATA2022
g_h helion g factor -4.25525061e+00 5.00000000e-08 CODATA2022
muH helion mag. mom. -1.07461753e-26 J T^-1 1.30000000e-34 CODATA2022
muH_Bhor helion mag. mom. to Bohr magneton ratio -1.15874096e-03 1.40000000e-11 CODATA2022
muH_Nuc helion mag. mom. to nuclear magneton ratio -2.12762531e+00 2.50000000e-08 CODATA2022
n0 Loschmidt constant (273.15 K, 100 kPa) 2.65164580e+19 1 / cm3 0.00000000e+00 CODATA2022
p_um natural unit of mom.um 2.73092449e-17 dyn s 3.40000000e-25 CODATA2022
p_um_MeV_c natural unit of mom.um in MeV/c 5.10998946e-01 MeV/c 3.10000000e-09 CODATA2022
mN-mP neutron-proton mass difference 2.30557435e-27 g 8.20000000e-34 CODATA2022
mN-mP_E neutron-proton mass difference energy equivalent 2.07214689e-06 erg 7.40000000e-13 CODATA2022
mN-mP_E_MeV neutron-proton mass difference energy equivalent i 2.07214689e-06 erg 7.37001252e-13 CODATA2022
mN-mP_u neutron-proton mass difference in u 2.30557435e-27 g 8.13664143e-34 CODATA2022
stp standard-state pressure 1.00000000e+06 P / s 0.00000000e+00 CODATA2022
mAlpha alpha particle relative atomic mass 4.00150618e+00 6.30000000e-11 CODATA2022
muB_invm_T Bohr magneton in inverse meter per tesla 4.66864478e+01 m^-1 T^-1 1.40000000e-08 CODATA2022
kB_invm Boltzmann constant in inverse meter per kelvin 6.95034800e-01 1 / (K cm) 0.00000000e+00 CODATA2022
ampere-90 conventional value of ampere-90 1.00000009e+00 A 0.00000000e+00 CODATA2022
coulomb-90 conventional value of coulomb-90 1.00000009e+00 C 0.00000000e+00 CODATA2022
farad-90 conventional value of farad-90 9.99999982e-01 F 0.00000000e+00 CODATA2022
henry-90 conventional value of henry-90 1.00000002e+00 H 0.00000000e+00 CODATA2022
ohm-90 conventional value of ohm-90 1.00000002e+00 ohm 0.00000000e+00 CODATA2022
volt-90 conventional value of volt-90 1.00000011e+00 V 0.00000000e+00 CODATA2022
watt-90 conventional value of watt-90 1.00000020e+07 erg / s 0.00000000e+00 CODATA2022
mD_amu_rel deuteron relative atomic mass 2.01355321e+00 4.00000000e-11 CODATA2022
rg_e_MHz_T electron gyromag. ratio in MHz/T 2.80249514e+04 MHz T^-1 8.50000000e-06 CODATA2022
mE_amu_rel electron relative atomic mass 5.48579909e-04 1.60000000e-14 CODATA2022
e_hbar elementary charge over h-bar 1.51926745e+15 A J^-1 0.00000000e+00 CODATA2022
mH_amu_rel helion relative atomic mass 3.01493225e+00 9.70000000e-11 CODATA2022
h_shield_shift helion shielding shift 5.99674300e-05 1.00000000e-10 CODATA2022
F_hyperfine_Cs-133 hyperfine transition frequency of Cs-133 9.19263177e+09 1 / s 0.00000000e+00 CODATA2022
aSi_220_ideal lattice spacing of ideal Si (220) 1.92015572e-08 cm 3.20000000e-16 CODATA2022
eta luminous efficacy 6.83000000e-05 s3 rad2 cd / (g cm2) 0.00000000e+00 CODATA2022
rg_n_MHz_T neutron gyromag. ratio in MHz/T 2.91646931e+01 MHz T^-1 6.90000000e-06 CODATA2022
mN_amu_rel neutron relative atomic mass 1.00866492e+00 4.90000000e-10 CODATA2022
mu_N_invm nuclear magneton in inverse meter per tesla 2.54262341e-02 m^-1 T^-1 7.80000000e-12 CODATA2022
h_eV_Hz Planck constant in eV/Hz 6.62607015e-27 erg s 0.00000000e+00 CODATA2022
rg_p_MHz_T proton gyromag. ratio in MHz/T 4.25774785e+01 MHz T^-1 1.80000000e-08 CODATA2022
mP_amu_rel proton relative atomic mass 1.00727647e+00 5.30000000e-11 CODATA2022
lambda_compt_bar reduced Compton wavelength 3.86159268e-11 cm 1.20000000e-20 CODATA2022
lambda_compt_mu_bar reduced muon Compton wavelength 1.86759431e-13 cm 4.20000000e-21 CODATA2022
lambda_compt_n_bar reduced neutron Compton wavelength 2.10019416e-14 cm 1.20000000e-23 CODATA2022
hbar reduced Planck constant 1.05457182e-27 erg s 0.00000000e+00 CODATA2022
hbar_eV_s reduced Planck constant in eV s 1.05457182e-27 erg s 0.00000000e+00 CODATA2022
chbar_MeV reduced Planck constant times c in MeV fm 3.16152677e-17 cm erg 0.00000000e+00 CODATA2022
lambda_compt_p_bar reduced proton Compton wavelength 2.10308910e-14 cm 6.40000000e-24 CODATA2022
lambda_compt_tau_bar reduced tau Compton wavelength 1.11053800e-14 cm 7.50000000e-19 CODATA2022
rg_h_shield_MHz_T shielded helion gyromag. ratio in MHz/T 3.24340994e+01 MHz T^-1 3.80000000e-07 CODATA2022
rg_p_shield_MHz_T shielded proton gyromag. ratio in MHz/T 4.25763847e+01 MHz T^-1 4.60000000e-07 CODATA2022
d_shield-p_shield_HD shielding difference of d and p in HD 2.02000000e-08 2.00000000e-11 CODATA2022
t_shield-p_shield_HT shielding difference of t and p in HT 2.41400000e-08 2.00000000e-11 CODATA2022
tau_E tau energy equivalent 2.84684357e-03 erg 1.92261196e-07 CODATA2022
psi_amu_rel triton relative atomic mass 3.01550072e+00 1.20000000e-10 CODATA2022
muPsi_p triton to proton mag. mom. ratio 1.06663992e+00 2.10000000e-09 CODATA2022
epsilon0 vacuum electric permittivity 8.85418781e-12 F m^-1 1.30000000e-21 CODATA2022
mu0 vacuum mag. permeability 1.25663706e-06 N A^-2 1.90000000e-16 CODATA2022
mWZ W to Z mass ratio 8.81530000e-01 1.70000000e-04 CODATA2022
au Astronomical Unit 1.49597871e+13 cm 0.00000000e+00 IAU 2012 Resolution B2
pc Parsec 3.08567758e+18 cm 0.00000000e+00 Derived from au + IAU 2015 Resolution B 2 note [4]
kpc Kiloparsec 3.08567758e+21 cm 0.00000000e+00 Derived from au + IAU 2015 Resolution B 2 note [4]
L_bol0 Luminosity for absolute bolometric magnitude 0 3.01280000e+35 erg / s 0.00000000e+00 IAU 2015 Resolution B 2
L_sun Nominal solar luminosity 3.82800000e+33 erg / s 0.00000000e+00 IAU 2015 Resolution B 3
GM_sun Nominal solar mass parameter 1.32712440e+26 cm3 / s2 0.00000000e+00 IAU 2015 Resolution B 3
M_sun Solar mass 1.98840987e+33 g 4.46880543e+28 IAU 2015 Resolution B 3 + CODATA 2018
R_sun Nominal solar radius 6.95700000e+10 cm 0.00000000e+00 IAU 2015 Resolution B 3
GM_jup Nominal Jupiter mass parameter 1.26686530e+23 cm3 / s2 0.00000000e+00 IAU 2015 Resolution B 3
M_jup Jupiter mass 1.89812460e+30 g 4.26589589e+25 IAU 2015 Resolution B 3 + CODATA 2018
R_jup Nominal Jupiter equatorial radius 7.14920000e+09 cm 0.00000000e+00 IAU 2015 Resolution B 3
GM_earth Nominal Earth mass parameter 3.98600400e+20 cm3 / s2 0.00000000e+00 IAU 2015 Resolution B 3
M_earth Earth mass 5.97216787e+27 g 1.34220095e+23 IAU 2015 Resolution B 3 + CODATA 2018
R_earth Nominal Earth equatorial radius 6.37810000e+08 cm 0.00000000e+00 IAU 2015 Resolution B 3

View File

@@ -0,0 +1,4 @@
eos:
helm: "eos/helm_table.dat"
mesh:
sphere: "mesh/sphere.msh"

View File

@@ -0,0 +1 @@
Use the utility `utils/atomic/convertWeightsToHeader.py` to generate atomicWeights.h

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
species_weight_dep = declare_dependency(
include_directories: include_directories('include'),
)

View File

@@ -0,0 +1,2 @@
subdir('const')
subdir('atomic')

226
build-config/boost/install.sh Executable file
View File

@@ -0,0 +1,226 @@
#!/usr/bin/env bash
#
# install.sh - Interactive installation script for Boost.
#
# This script checks if Boost is installed (by looking for boost/version.hpp in common locations).
# If not found, it prompts the user to install Boost using the native package manager for:
# - FreeBSD, Ubuntu, Debian, Fedora, Arch, Mint, Manjaro, macOS, OpenSuse, and Nix.
#
# All output is colorized for clarity and logged to meson-log.txt.
set -e
# ANSI color codes.
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
BLUE="\033[0;34m"
NC="\033[0m" # No Color
# Log file.
LOGFILE="4DSSE-install-log.txt"
touch "$LOGFILE"
# Log function: prints to stdout and appends to logfile.
log() {
local message="$1"
# Print the colored message to stdout.
echo -e "$message"
# Strip ANSI escape sequences and append the cleaned message to the log file.
echo -e "$message" | sed -r 's/\x1B\[[0-9;]*[mK]//g' >> "$LOGFILE"
}
check_boost_installed() {
log "${BLUE}[Info] Checking for Boost::numeric and Boost::phoenix using Meson...${NC}"
local tmpDir
if [[ -d mesonTest ]]; then
rm -rf mesonTest
fi
tmpDir=$(mkdir mesonTest)
local sourceFile="mesonTest/test.cpp"
local mesonFile="mesonTest/meson.build"
# Write test.cpp
cat > "$sourceFile" <<EOF
#include <boost/numeric/ublas/vector.hpp>
#include <boost/phoenix/phoenix.hpp>
int main() {
boost::numeric::ublas::vector<double> v(3);
v[0] = 1.0;
return v[0];
}
EOF
# Write meson.build
cat > "$mesonFile" <<EOF
project('boost-check', 'cpp', default_options: ['cpp_std=c++17'])
boost_dep = dependency('boost', required: true)
executable('boostAvaliTest', 'test.cpp', dependencies: [boost_dep])
EOF
# Try configuring and compiling
if meson setup "mesonTest/build" "mesonTest" && \
meson compile -C "mesonTest/build"; then
log "${GREEN}[Success] Boost::numeric and Boost::phoenix are available.${NC}"
rm -rf "mesonTest"
return 0
else
log "${RED}[Error] Boost could not be found or required components are missing.${NC}"
rm -rf "mesonTest"
return 1
fi
}
# Prompt the user for a yes/no answer.
prompt_yes_no() {
local promptMsg="$1"
read -p "$(echo -e ${YELLOW}$promptMsg${NC}) " answer
if [[ "$answer" =~ ^[Yy]$ ]]; then
return 0
else
return 1
fi
}
# Detect OS.
OS=$(uname -s)
DISTRO="unknown"
if [ -f /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
DISTRO=$ID
fi
if [[ "$OS" == "Darwin" ]]; then
OS="macOS"
fi
if [[ $OS == "macOS" ]]; then
log "${BLUE}[Info] Detected OS: ${OS}${NC}"
else
log "${BLUE}[Info] Detected OS: ${OS} Distribution: ${DISTRO}${NC}"
fi
# Check if Boost is already installed.
if check_boost_installed; then
log "${GREEN}[Success] Boost is already installed on your system.${NC}"
log "${GREEN}[Success] 4DSSE installation can now continue.${NC}"
exit 0
else
log "${YELLOW}[Info] Boost was not detected on your system.${NC}"
if prompt_yes_no "[Query] Would you like to install Boost now? (y/n): "; then
case "$OS" in
"macOS")
# On macOS, check if Homebrew is available.
if ! command -v brew &> /dev/null; then
log "${YELLOW}[Warning] Homebrew is not installed. It is recommended for installing Boost on macOS.${NC}"
if prompt_yes_no "[Query] Would you like to install Homebrew now? (y/n): "; then
log "${BLUE}[Info] Installing Homebrew...${NC}"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" | tee -a "$LOGFILE"
else
log "${RED}[Error] Homebrew is required for an easy Boost installation on macOS. Aborting.${NC}"
exit 1
fi
fi
log "${BLUE}[Info] Running: brew install boost${NC}"
brew install boost | tee -a "$LOGFILE"
;;
"Linux")
case "$DISTRO" in
"ubuntu"|"debian"|"linuxmint")
log "${BLUE}[Info] Running: sudo apt-get update && sudo apt-get install -y libboost-all-dev${NC}"
sudo apt-get update | tee -a "$LOGFILE"
sudo apt-get install -y libboost-all-dev | tee -a "$LOGFILE"
;;
"fedora")
log "${BLUE}[Info] Running: sudo dnf install boost-devel${NC}"
sudo dnf install -y boost-devel | tee -a "$LOGFILE"
;;
"arch"|"manjaro")
log "${BLUE}[Info] Running: sudo pacman -S boost${NC}"
sudo pacman -S --noconfirm boost | tee -a "$LOGFILE"
;;
"opensuse")
log "${BLUE}[Info] Running: sudo zypper install libboost-devel${NC}"
sudo zypper install -y libboost-devel | tee -a "$LOGFILE"
;;
"nixos"|"nix")
log "${BLUE}[Info] Running: nix-env -iA nixpkgs.boost${NC}"
nix-env -iA nixpkgs.boost | tee -a "$LOGFILE"
;;
*)
log "${RED}[Error] Your Linux distribution is not recognized. Please install Boost manually.${NC}"
exit 1
;;
esac
;;
"FreeBSD")
log "${BLUE}[Info] Running: sudo pkg install boost-all${NC}"
sudo pkg install -y boost-all | tee -a "$LOGFILE"
;;
*)
log "${RED}[Error] Automatic Boost installation is not supported on OS: ${OS}. Please install Boost manually.${NC}"
exit 1
;;
esac
# Verify Boost installation.
if check_boost_installed; then
log "${GREEN}[Success] Boost installation succeeded.${NC}"
else
log "${RED}[Error] Boost installation appears to have failed. Please install Boost manually.${NC}"
exit 1
fi
else
log "${RED}[Error] Boost is required. Please install it using the appropriate command for your system:${NC}"
case "$OS" in
"macOS")
log "${RED}[INFO] brew install boost (Install Homebrew from https://brew.sh if not present)${NC}"
;;
"Linux")
case "$DISTRO" in
"ubuntu"|"debian"|"linuxmint")
log "${RED}[INFO] sudo apt-get install libboost-all-dev${NC}"
;;
"fedora")
log "${RED}[INFO] sudo dnf install boost-devel${NC}"
;;
"arch"|"manjaro")
log "${RED}[INFO] sudo pacman -S boost${NC}"
;;
"opensuse")
log "${RED}[INFO] sudo zypper install libboost-devel${NC}"
;;
"nixos"|"nix")
log "${RED}[INFO] nix-env -iA nixpkgs.boost${NC}"
;;
*)
log "${RED}[INFO] Please consult your distribution's documentation for installing Boost.${NC}"
;;
esac
;;
"FreeBSD")
log "${RED}[INFO] sudo pkg install boost-all${NC}"
;;
*)
log "${RED}[INFO] Please consult your operating system's documentation for installing Boost.${NC}"
;;
esac
exit 1
fi
fi
check_boost_installed
log "${GREEN}[Success] Boost installed successfully!${NC}"
log "${GREEN}[Success] 4DSSE installation can now continue.${NC}"

View File

@@ -0,0 +1 @@
boost_dep = dependency('boost', version: '>=1.8.0')

View File

@@ -2,4 +2,6 @@ cmake = import('cmake')
subdir('mfem')
subdir('yaml-cpp')
subdir('quill')
subdir('quill')
subdir('boost')
subdir('opatIO')

View File

@@ -0,0 +1,3 @@
opatio_dep = dependency('opatio', fallback: ['opat-core', 'opatio_dep'])
picosha2_dep = dependency('picosha2', fallback: ['opat-core', 'picosha2_dep'])

View File

@@ -22,14 +22,26 @@ project('4DSSE', 'cpp', version: '0.0.1a', default_options: ['cpp_std=c++23'], m
# Add default visibility for all C++ targets
add_project_arguments('-fvisibility=default', language: 'cpp')
if get_option('buildtype') == 'debug'
add_project_arguments('-Wno-unused-variable', '-Wno-unused-parameter', '-Wno-unused-function', '-Wno-unused-private-field', '-Wno-unused-lambda-capture', language : 'cpp')
# Determine the mode
mode = 1
if get_option('user_mode')
mode = 0
endif
# Define DATA_DIR based on mode
if mode == 1
data_dir = meson.project_source_root() + '/assets/dynamic'
else
data_dir = get_option('prefix') + '/' + get_option('datadir') + '/4DSSE'
endif
# Pass the DATA_DIR definition to the compiler
add_project_arguments('-DDATA_DIR=' + data_dir, language : 'cpp')
# Build external dependencies first so that all the embedded resources are available to the other targets
subdir('build-config')
subdir('subprojects/PicoSHA2')
subdir('assets/static')
# Build the main project
subdir('src')

View File

@@ -1 +1,2 @@
option('build_tests', type: 'boolean', value: true, description: 'Build tests')
option('user_mode', type: 'boolean', value: false, description: 'Enable user mode (set mode = 0)')

428
mk
View File

@@ -1,23 +1,421 @@
#!/bin/bash
#!/usr/bin/env bash
# Check for the --noTest flag
if [[ "$1" == "--noTest" ]]; then
meson setup build -Dbuild_tests=false --buildtype=release
set -e
# --- Defaults ---
userFlag=0
testsFlag=0
runTestsFlag=0
buildDir="build"
installDir="$HOME/.local/4DSSE"
# --- Help Menu ---
show_help() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS]
Options:
--user Build and Install as a release for. Intended for end users.
--noBuildTest Do not build tests.
--runTest Run tests.
--buildDir Specify the build directory. Default is "${buildDir}".
--installDir Specify the install directory. Default is "${installDir}".
-h, --help Show this help message and exit
You can use these flags in any order. Flags not passed will get default values.
Examples:
For an end user who wants a seemless experience 4DSSE:
./mk --user
For developers who want to modify the source:
./mk
For developers who want to run tests:
./mk --tests
EOF
}
# --- Parse Arguments ---
while [[ $# -gt 0 ]]; do
case "$1" in
--user)
userFlag=1
shift
;;
--noTest)
testsFlag=1
shift
;;
--runTest)
runTestsFlag=1
shift
;;
--buildDir)
buildDir=1
shift
;;
--installDir)
installDir=1
shift
;;
-h|--help)
show_help
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use --help for usage information."
exit 1
;;
esac
done
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
BLUE="\033[0;34m"
MAGENTA="\033[0;35m"
NC="\033[0m" # No Color
# Log file.
LOGDIR="4DSSE_logs"
if [[ ! -d "$LOGDIR" ]]; then
echo -e "${BLUE}[Info] Creating log directory...${NC}"
mkdir "$LOGDIR"
else
meson setup build -Dbuild_tests=true --buildtype=debug
echo -e "${MAGENTA}[Succsess] Log directory already exists. Skipping...${NC}"
fi
LOGFILE="${LOGDIR}/4DSSE-install-log.txt"
# Log function: prints to stdout and appends to logfile.
log() {
local message="$1"
# Print the colored message to stdout.
echo -e "$message"
# Strip ANSI escape sequences and append the cleaned message to the log file.
echo -e "$message" | sed -r 's/\x1B\[[0-9;]*[mK]//g' >> "$LOGFILE"
}
if [[ -f "$LOGFILE" ]]; then
# Get the calendar datetime of the log file creation.
# convert UNIX timestamp to human-readable date
rm "$LOGFILE"
log "${BLUE}[Info] Old log file removed.${NC}"
fi
touch "$LOGFILE"
# --- Check if Clang or GCC is installed ---
log "${BLUE}[Info] Checking if Clang or GCC is installed...${NC}"
if ! command -v clang &> /dev/null && ! command -v gcc &> /dev/null; then
log "${RED}[Error] Clang or GCC is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install Clang or GCC and try again.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] Clang or GCC is installed. Continuing...${NC}"
fi
# Compile the project
meson compile -C build
# --- Check if MESON is installed ---
log "${BLUE}[Info] Checking if Meson is installed...${NC}"
if ! command -v meson &> /dev/null; then
log "${RED}[Error] Meson is not installed. Exiting...${NC}"
# Check if the user would like to try to install meson by getting input
installMeson=0
while true; do
echo -ne "${YELLOW}[Query] Would you like to try to install Meson? [y/n]: ${NC}"
read -p "" yn
case $yn in
[Yy]* ) installMeson=1; break;;
[Nn]* ) break;;
* ) echo "Please answer yes or no.";;
esac
done
if [[ $installMeson -eq 1 ]]; then
# check if pip is installed
if ! command -v pip &> /dev/null; then
log "${RED}[Error] pip is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install pip and try again.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] pip is installed. Continuing...${NC}"
fi
# If tests are built, run them
if [[ "$1" != "--noTest" ]]; then
meson test -C build
# check if python3 is installed
if ! command -v python3 &> /dev/null; then
log "${RED}[Error] python3 is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install python3 and try again.${NC}"
log "${YELLOW}[INFO] If you have python3 installed, please add it to your PATH.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] python3 is installed. Continuing...${NC}"
fi
# Check if the venv ~/.4DSSE_env exists
if [[ ! -d "$HOME/.4DSSE_env" ]]; then
log "${BLUE}[Info] Creating virtual environment...${NC}"
python3 -m venv "$HOME/.4DSSE_env"
source "$HOME/.4DSSE_env/bin/activate"
log "${GREEN}[Succsess] Virtual environment created.${NC}"
else
log "${MAGENTA}[Succsess] Virtual environment already exists. Skipping...${NC}"
fi
# install meson
log "${BLUE}[Info] Installing Meson...${NC}"
pip install meson
# confirm meson is installed
if ! command -v meson &> /dev/null; then
log "${RED}[Error] Meson did not install properly. Exiting...${NC}"
log "${YELLOW}[Info] Please manually install Meson and try again.${NC}"
exit 1
else
log "${GREEN}[Succsess] Meson installed.${NC}"
fi
else
log "${YELLOW}[Info] Please install Meson and try again.${NC}"
exit 1
fi
else
log "${MAGENTA}[Succsess] Meson is installed. Continuing...${NC}"
fi
# Check if --docs are to be built
if [[ "$*" == *"--docs"* ]]; then
echo "Generating documentation..."
doxygen
cd docs/latex && make
# --- Check if NINJA is installed ---
log "${BLUE}[Info] Checking if Ninja is installed...${NC}"
if ! command -v ninja &> /dev/null; then
log "${RED}[Error] Ninja is not installed. Exiting...${NC}"
# Check if the user would like to try to install ninja by getting input
installNinja=0
while true; do
echo -ne "${YELLOW}[Query] Would you like to try to install Ninja? [y/n]: ${NC}"
read -p "" yn
case $yn in
[Yy]* ) installNinja=1; break;;
[Nn]* ) break;;
* ) echo "Please answer yes or no.";;
esac
done
if [[ $installNinja -eq 1 ]]; then
# check if pip is installed
if ! command -v pip &> /dev/null; then
log "${RED}[Error] pip is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install pip and try again.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] pip is installed. Continuing...${NC}"
fi
# check if python3 is installed
if ! command -v python3 &> /dev/null; then
log "${RED}[Error] python3 is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install python3 and try again.${NC}"
log "${YELLOW}[INFO] If you have python3 installed, please add it to your PATH.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] python3 is installed. Continuing...${NC}"
fi
# Check if the venv ~/.4DSSE_env exists
if [[ ! -d "$HOME/.4DSSE_env" ]]; then
log "${BLUE}[Info] Creating virtual environment...${NC}"
python3 -m venv "$HOME/.4DSSE_env"
source "$HOME/.4DSSE_env/bin/activate"
log "${GREEN}[Succsess] Virtual environment created.${NC}"
else
log "${MAGENTA}[Succsess] Virtual environment already exists. Skipping...${NC}"
fi
# install ninja
log "${BLUE}[Info] Installing Ninja...${NC}"
pip install ninja
# confirm ninja is installed
if ! command -v ninja &> /dev/null; then
log "${RED}[Error] Ninja did not install properly. Exiting...${NC}"
log "${YELLOW}[Info] Please manually install Ninja and try again.${NC}"
exit 1
else
log "${GREEN}[Succsess] Ninja installed.${NC}"
fi
else
log "${YELLOW}[Info] Please install Ninja and try again.${NC}"
exit 1
fi
else
log "${MAGENTA}[Succsess] Ninja is installed. Continuing...${NC}"
fi
# --- Check if CMake is installed ---
log "${BLUE}[Info] Checking if CMake is installed...${NC}"
if ! command -v cmake &> /dev/null; then
log "${RED}[Error] CMake is not installed....${NC}"
# Check if the user would like to try to install cmake by getting input
installCMake=0
while true; do
echo -ne "${YELLOW}[Query] Would you like to try to install CMake? [y/n]: ${NC}"
read -p "" yn
case $yn in
[Yy]* ) installCMake=1; break;;
[Nn]* ) break;;
* ) echo "Please answer yes or no.";;
esac
done
if [[ $installCMake -eq 1 ]]; then
# check if pip is installed
if ! command -v pip &> /dev/null; then
log "${RED}[Error] pip is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install pip and try again.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] pip is installed. Continuing...${NC}"
fi
# check if python3 is installed
if ! command -v python3 &> /dev/null; then
log "${RED}[Error] python3 is not installed. Exiting...${NC}"
log "${YELLOW}[Info] Please install python3 and try again.${NC}"
log "${YELLOW}[INFO] If you have python3 installed, please add it to your PATH.${NC}"
exit 1
else
log "${MAGENTA}[Succsess] python3 is installed. Continuing...${NC}"
fi
# Check if the venv ~/.4DSSE_env exists
if [[ ! -d "$HOME/.4DSSE_env" ]]; then
log "${BLUE}[Info] Creating virtual environment...${NC}"
python3 -m venv "$HOME/.4DSSE_env"
source "$HOME/.4DSSE_env/bin/activate"
log "${GREEN}[Succsess] Virtual environment created.${NC}"
else
log "${MAGENTA}[Succsess] Virtual environment already exists. Skipping...${NC}"
fi
# install cmake
log "${BLUE}[Info] Installing CMake...${NC}"
pip install cmake
# confirm cmake is installed
if ! command -v cmake &> /dev/null; then
log "${RED}[Error] CMake did not install properly. Exiting...${NC}"
log "${YELLOW}[Info] Please manually install CMake and try again.${NC}"
exit 1
else
log "${GREEN}[Succsess] CMake installed.${NC}"
fi
fi
else
log "${MAGENTA}[Succsess] CMake is installed. Continuing...${NC}"
fi
# --- Build 4DSSE ---
log "${BLUE}[Info] Building 4DSSE...${NC}"
if [[ $userFlag -eq 1 ]]; then
log "${BLUE}[Info] Installing 4DSSE in user mode...${NC}"
else
log "${BLUE}[Info] Installing 4DSSE for developers...${NC}"
fi
if [[ $testsFlag -eq 0 ]]; then
log "${BLUE}[Info] Building with tests...${NC}"
else
log "${BLUE}[Info] Building without tests...${NC}"
fi
# --- First check Boost status ---
log "${BLUE}[Info] Checking Boost status...${NC}"
# if the following script exists with anything other than a 0 status the script will exit
if [[ -f ./build-config/boost/.boost_installed ]]; then
log "${MAGENTA}[Succsess] Boost already installed. Skipping...${NC}"
else
log "${BLUE}[Info] Installing Boost...${NC}"
if ! ./build-config/boost/install.sh; then
log "${RED}[Error] Boost check failed. Exiting...${NC}"
exit 1
else
touch ./build-config/boost/.boost_installed
log "${GREEN}[Succsess] Boost check passed.${NC}"
fi
fi
#check if the last build flags are the same as the current build flags
# if the flags are the same skip the configuration step
# if they are different then reconfigure the build directory
# do not use grep -oP as it is not POSIX compliant
doReconfigure=1
log "${BLUE}[Info] Checking last build flags...${NC}"
if [[ -f $buildDir/.last_build_flags ]]; then
lastUserFlag=$(grep -Eo 'userFlag=[0-9]+' $buildDir/.last_build_flags | cut -d'=' -f2)
lastTestsFlag=$(grep -Eo 'testsFlag=[0-9]+' $buildDir/.last_build_flags | cut -d'=' -f2)
if [[ $lastUserFlag -eq $userFlag && $lastTestsFlag -eq $testsFlag ]]; then
log "${MAGENTA}[Succsess] Last build flags match current build flags. Skipping configuration...${NC}"
doReconfigure=0
else
log "${YELLOW}[Info] Last build flags do not match current build flags. Reconfiguring...${NC}"
rm -rf $buildDir
fi
else
log "${BLUE}[Info] Last build flags not found. Reconfiguring...${NC}"
fi
# --- Check if the build dir has been configured with the correct flags ---
if [[ $doReconfigure -eq 1 ]]; then
log "${BLUE}[Info] Configuring build directory...${NC}"
if [ -f "$buildDir/build.ninja" ]; then
log "${MAGENTA}[Succsess] Build directory already configured. Skipping...${NC}"
else
if [[ $userFlag -eq 1 ]]; then
meson setup "$buildDir" -Duser_mode=true --buildtype=release
else
if [[ $testsFlag -eq 0 ]]; then
meson setup "$buildDir" --buildtype=debug
else
meson setup "$buildDir" --buildtype=debug -Dbuild_tests=false
fi
fi
log "${GREEN}[Succsess] Build directory configured successfully.${NC}"
fi
log "${BLUE}[Info] Caching last build flags...${NC}"
# --- Cache the last build flags ---
if [[ $userFlag -eq 1 ]]; then
echo "userFlag=1" > $buildDir/.last_build_flags
else
echo "userFlag=0" > $buildDir/.last_build_flags
fi
if [[ $testsFlag -eq 1 ]]; then
echo "testsFlag=1" >> $buildDir/.last_build_flags
else
echo "testsFlag=0" >> $buildDir/.last_build_flags
fi
log "${GREEN}[Succsess] Last build flags cached.${NC}"
fi
log "${BLUE}[Info] Building 4DSSE...${NC}"
meson compile -C "$buildDir"
# --- Install 4DSSE ---
if [[ $userFlag -eq 1 ]]; then
log "${BLUE}[Info] Installing 4DSSE in user mode...${NC}"
meson install -C "$buildDir"
fi
if [[ $runTestsFlag -eq 1 ]]; then
log "${BLUE}[Info] Running tests...${NC}"
meson test -C "$buildDir"
fi
if [[ $userFlag -eq 1 ]]; then
log "${GREEN}[Succsess] 4DSSE built and installed successfully.${NC}"
else
log "${GREEN}[Succsess] 4DSSE built successfully.${NC}"
fi
log "${GREEN}[Succsess] 4DSSE mk script complete.${NC}"

View File

@@ -0,0 +1,33 @@
# Define the library
composition_sources = files(
'private/composition.cpp',
)
composition_headers = files(
'public/composition.h'
)
dependencies = [
probe_dep,
config_dep,
quill_dep,
species_weight_dep
]
# Define the libcomposition library so it can be linked against by other parts of the build system
libcomposition = static_library('composition',
composition_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
dependencies: dependencies,
install : true)
composition_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libcomposition,
dependencies: dependencies,
sources: composition_sources,
)
# Make headers accessible
install_headers(composition_headers, subdir : '4DSSE/composition')

View File

@@ -0,0 +1,536 @@
#include "composition.h"
#include "quill/LogMacros.h"
#include <stdexcept>
#include <unordered_map>
#include <vector>
#include <array>
#include <utility>
#include "atomicSpecies.h"
using namespace composition;
CompositionEntry::CompositionEntry() : m_symbol("H-1"), m_isotope(chemSpecies::species.at("H-1")), m_initialized(false) {}
CompositionEntry::CompositionEntry(const std::string& symbol, bool massFracMode) : m_symbol(symbol), m_isotope(chemSpecies::species.at(symbol)), m_massFracMode(massFracMode) {
setSpecies(symbol);
}
CompositionEntry::CompositionEntry(const CompositionEntry& entry) :
m_symbol(entry.m_symbol),
m_isotope(entry.m_isotope),
m_massFracMode(entry.m_massFracMode),
m_massFraction(entry.m_massFraction),
m_numberFraction(entry.m_numberFraction),
m_relAbundance(entry.m_relAbundance),
m_initialized(entry.m_initialized) {}
void CompositionEntry::setSpecies(const std::string& symbol) {
if (m_initialized) {
throw std::runtime_error("Composition entry is already initialized.");
}
if (chemSpecies::species.count(symbol) == 0) {
throw std::runtime_error("Invalid symbol.");
}
m_symbol = symbol;
m_isotope = chemSpecies::species.at(symbol);
m_initialized = true;
}
std::string CompositionEntry::symbol() const {
return m_symbol;
}
double CompositionEntry::mass_fraction() const {
if (!m_massFracMode) {
throw std::runtime_error("Composition entry is in number fraction mode.");
}
return m_massFraction;
}
double CompositionEntry::mass_fraction(double meanMolarMass) const {
if (m_massFracMode) {
return m_massFraction;
}
return m_relAbundance / meanMolarMass;
}
double CompositionEntry::number_fraction() const {
if (m_massFracMode) {
throw std::runtime_error("Composition entry is in mass fraction mode.");
}
return m_numberFraction;
}
double CompositionEntry::number_fraction(double totalMoles) const {
if (m_massFracMode) {
return m_relAbundance / totalMoles;
}
return m_numberFraction;
}
double CompositionEntry::rel_abundance() const {
return m_relAbundance;
}
chemSpecies::Species CompositionEntry::isotope() const {
return m_isotope;
}
void CompositionEntry::setMassFraction(double mass_fraction) {
if (!m_massFracMode) {
throw std::runtime_error("Composition entry is in number fraction mode.");
}
m_massFraction = mass_fraction;
m_relAbundance = m_massFraction / m_isotope.mass();
}
void CompositionEntry::setNumberFraction(double number_fraction) {
if (m_massFracMode) {
throw std::runtime_error("Composition entry is in mass fraction mode.");
}
m_numberFraction = number_fraction;
m_relAbundance = m_numberFraction * m_isotope.mass();
}
bool CompositionEntry::setMassFracMode(double meanParticleMass) {
if (m_massFracMode) {
return false;
}
m_massFracMode = true;
m_massFraction = m_relAbundance / meanParticleMass;
return true;
}
bool CompositionEntry::setNumberFracMode(double specificNumberDensity) {
if (!m_massFracMode) {
return false;
}
m_massFracMode = false;
m_numberFraction = m_relAbundance / specificNumberDensity;
return true;
}
bool CompositionEntry::getMassFracMode() const {
return m_massFracMode;
}
Composition::Composition(const std::vector<std::string>& symbols) {
for (const auto& symbol : symbols) {
registerSymbol(symbol);
}
}
Composition::Composition(const std::set<std::string>& symbols) {
for (const auto& symbol : symbols) {
registerSymbol(symbol);
}
}
Composition::Composition(const std::vector<std::string>& symbols, const std::vector<double>& fractions, bool massFracMode) : m_massFracMode(massFracMode) {
if (symbols.size() != fractions.size()) {
LOG_ERROR(m_logger, "The number of symbols and fractions must be equal.");
throw std::runtime_error("The number of symbols and fractions must be equal.");
}
validateComposition(fractions);
for (const auto &symbol : symbols) {
registerSymbol(symbol);
}
for (size_t i = 0; i < symbols.size(); ++i) {
if (m_massFracMode) {
setMassFraction(symbols[i], fractions[i]);
} else {
setNumberFraction(symbols[i], fractions[i]);
}
}
finalize();
}
void Composition::registerSymbol(const std::string& symbol, bool massFracMode) {
if (!isValidSymbol(symbol)) {
LOG_ERROR(m_logger, "Invalid symbol: {}", symbol);
throw std::runtime_error("Invalid symbol.");
}
// If no symbols have been registered allow mode to be set
if (m_registeredSymbols.size() == 0) {
m_massFracMode = massFracMode;
} else {
if (m_massFracMode != massFracMode) {
LOG_ERROR(m_logger, "Composition is in mass fraction mode. Cannot register symbol in number fraction mode.");
throw std::runtime_error("Composition is in mass fraction mode. Cannot register symbol in number fraction mode.");
}
}
if (m_registeredSymbols.find(symbol) != m_registeredSymbols.end()) {
LOG_WARNING(m_logger, "Symbol {} is already registered.", symbol);
return;
}
m_registeredSymbols.insert(symbol);
CompositionEntry entry(symbol, m_massFracMode);
m_compositions[symbol] = entry;
LOG_INFO(m_logger, "Registered symbol: {}", symbol);
}
void Composition::registerSymbol(const std::vector<std::string>& symbols, bool massFracMode) {
for (const auto& symbol : symbols) {
registerSymbol(symbol, massFracMode);
}
}
std::set<std::string> Composition::getRegisteredSymbols() const {
return m_registeredSymbols;
}
void Composition::validateComposition(const std::vector<double>& fractions) const {
if (!isValidComposition(fractions)) {
LOG_ERROR(m_logger, "Invalid composition.");
throw std::runtime_error("Invalid composition.");
}
}
bool Composition::isValidComposition(const std::vector<double>& fractions) const {
double sum = 0.0;
for (const auto& fraction : fractions) {
sum += fraction;
}
if (sum < 0.999999 || sum > 1.000001) {
LOG_ERROR(m_logger, "The sum of fractions must be equal to 1.");
return false;
}
return true;
}
bool Composition::isValidSymbol(const std::string& symbol) const {
return chemSpecies::species.count(symbol) > 0;
}
double Composition::setMassFraction(const std::string& symbol, const double& mass_fraction) {
if (m_registeredSymbols.find(symbol) == m_registeredSymbols.end()) {
LOG_ERROR(m_logger, "Symbol {} is not registered.", symbol);
throw std::runtime_error("Symbol is not registered.");
}
if (!m_massFracMode) {
LOG_ERROR(m_logger, "Composition is in number fraction mode.");
throw std::runtime_error("Composition is in number fraction mode.");
}
if (mass_fraction < 0.0 || mass_fraction > 1.0) {
LOG_ERROR(m_logger, "Mass fraction must be between 0 and 1 for symbol {}. Currently it is {}.", symbol, mass_fraction);
throw std::runtime_error("Mass fraction must be between 0 and 1.");
}
m_finalized = false;
double old_mass_fraction = m_compositions.at(symbol).mass_fraction();
m_compositions.at(symbol).setMassFraction(mass_fraction);
return old_mass_fraction;
}
std::vector<double> Composition::setMassFraction(const std::vector<std::string>& symbols, const std::vector<double>& mass_fractions) {
if (symbols.size() != mass_fractions.size()) {
LOG_ERROR(m_logger, "The number of symbols and mass fractions must be equal.");
throw std::runtime_error("The number of symbols and mass fractions must be equal.");
}
std::vector<double> old_mass_fractions;
old_mass_fractions.reserve(symbols.size());
for (size_t i = 0; i < symbols.size(); ++i) {
old_mass_fractions.push_back(setMassFraction(symbols[i], mass_fractions[i]));
}
return old_mass_fractions;
}
double Composition::setNumberFraction(const std::string& symbol, const double& number_fraction) {
if (m_registeredSymbols.find(symbol) == m_registeredSymbols.end()) {
LOG_ERROR(m_logger, "Symbol {} is not registered.", symbol);
throw std::runtime_error("Symbol is not registered.");
}
if (m_massFracMode) {
LOG_ERROR(m_logger, "Composition is in mass fraction mode.");
throw std::runtime_error("Composition is in mass fraction mode.");
}
if (number_fraction < 0.0 || number_fraction > 1.0) {
LOG_ERROR(m_logger, "Number fraction must be between 0 and 1 for symbol {}. Currently it is {}.", symbol, number_fraction);
throw std::runtime_error("Number fraction must be between 0 and 1.");
}
m_finalized = false;
double old_number_fraction = m_compositions.at(symbol).number_fraction();
m_compositions.at(symbol).setNumberFraction(number_fraction);
return old_number_fraction;
}
std::vector<double> Composition::setNumberFraction(const std::vector<std::string>& symbols, const std::vector<double>& number_fractions) {
if (symbols.size() != number_fractions.size()) {
LOG_ERROR(m_logger, "The number of symbols and number fractions must be equal.");
throw std::runtime_error("The number of symbols and number fractions must be equal.");
}
std::vector<double> old_number_fractions;
old_number_fractions.reserve(symbols.size());
for (size_t i = 0; i < symbols.size(); ++i) {
old_number_fractions.push_back(setNumberFraction(symbols[i], number_fractions[i]));
}
return old_number_fractions;
}
bool Composition::finalize(bool norm) {
bool finalized = false;
if (m_massFracMode) {
finalized = finalizeMassFracMode(norm);
} else {
finalized = finalizeNumberFracMode(norm);
}
if (finalized) {
m_finalized = true;
}
return finalized;
}
bool Composition::finalizeMassFracMode(bool norm) {
std::vector<double> mass_fractions;
mass_fractions.reserve(m_compositions.size());
for (const auto& [_, entry] : m_compositions) {
mass_fractions.push_back(entry.mass_fraction());
}
if (norm) {
double sum = 0.0;
for (const auto& mass_fraction : mass_fractions) {
sum += mass_fraction;
}
for (int i = 0; i < mass_fractions.size(); ++i) {
mass_fractions[i] /= sum;
}
for (auto& [symbol, entry] : m_compositions) {
setMassFraction(symbol, entry.mass_fraction() / sum);
}
}
try {
validateComposition(mass_fractions);
} catch (const std::runtime_error& e) {
double massSum = 0.0;
for (const auto& [_, entry] : m_compositions) {
massSum += entry.mass_fraction();
}
LOG_ERROR(m_logger, "Composition is invalid (Total mass {}).", massSum);
m_finalized = false;
return false;
}
for (const auto& [_, entry] : m_compositions) {
m_specificNumberDensity += entry.rel_abundance();
}
m_meanParticleMass = 1.0/m_specificNumberDensity;
return true;
}
bool Composition::finalizeNumberFracMode(bool norm) {
std::vector<double> number_fractions;
number_fractions.reserve(m_compositions.size());
for (const auto& [_, entry] : m_compositions) {
number_fractions.push_back(entry.number_fraction());
}
if (norm) {
double sum = 0.0;
for (const auto& number_fraction : number_fractions) {
sum += number_fraction;
}
for (auto& [symbol, entry] : m_compositions) {
setNumberFraction(symbol, entry.number_fraction() / sum);
}
}
try {
validateComposition(number_fractions);
} catch (const std::runtime_error& e) {
double numberSum = 0.0;
for (const auto& [_, entry] : m_compositions) {
numberSum += entry.number_fraction();
}
LOG_ERROR(m_logger, "Composition is invalid (Total number {}).", numberSum);
m_finalized = false;
return false;
}
for (const auto& [_, entry] : m_compositions) {
m_meanParticleMass += entry.rel_abundance();
}
m_specificNumberDensity = 1.0/m_meanParticleMass;
return true;
}
Composition Composition::mix(const Composition& other, double fraction) const {
if (!m_finalized || !other.m_finalized) {
LOG_ERROR(m_logger, "Compositions have not both been finalized.");
throw std::runtime_error("Compositions have not been finalized (Consider running .finalize()).");
}
if (fraction < 0.0 || fraction > 1.0) {
LOG_ERROR(m_logger, "Fraction must be between 0 and 1.");
throw std::runtime_error("Fraction must be between 0 and 1.");
}
std::set<std::string> mixedSymbols = other.getRegisteredSymbols();
// Get the union of the two sets
mixedSymbols.insert(m_registeredSymbols.begin(), m_registeredSymbols.end());
Composition mixedComposition(mixedSymbols);
for (const auto& symbol : mixedSymbols) {
double thisMassFrac, otherMassFrac = 0.0;
thisMassFrac = hasSymbol(symbol) ? getMassFraction(symbol) : 0.0;
otherMassFrac = other.hasSymbol(symbol) ? other.getMassFraction(symbol) : 0.0;
double massFraction = fraction * thisMassFrac + otherMassFrac * (1-fraction);
mixedComposition.setMassFraction(symbol, massFraction);
}
mixedComposition.finalize();
return mixedComposition;
}
double Composition::getMassFraction(const std::string& symbol) const {
if (!m_finalized) {
LOG_ERROR(m_logger, "Composition has not been finalized.");
throw std::runtime_error("Composition has not been finalized (Consider running .finalize()).");
}
if (m_compositions.count(symbol) == 0) {
LOG_ERROR(m_logger, "Symbol {} is not in the composition.", symbol);
throw std::runtime_error("Symbol is not in the composition.");
}
if (m_massFracMode) {
return m_compositions.at(symbol).mass_fraction();
} else {
return m_compositions.at(symbol).mass_fraction(m_meanParticleMass);
}
}
std::unordered_map<std::string, double> Composition::getMassFraction() const {
std::unordered_map<std::string, double> mass_fractions;
for (const auto& [symbol, entry] : m_compositions) {
mass_fractions[symbol] = getMassFraction(symbol);
}
return mass_fractions;
}
double Composition::getNumberFraction(const std::string& symbol) const {
if (!m_finalized) {
LOG_ERROR(m_logger, "Composition has not been finalized.");
throw std::runtime_error("Composition has not been finalized (Consider running .finalize()).");
}
if (m_compositions.count(symbol) == 0) {
LOG_ERROR(m_logger, "Symbol {} is not in the composition.", symbol);
throw std::runtime_error("Symbol is not in the composition.");
}
if (!m_massFracMode) {
return m_compositions.at(symbol).number_fraction();
} else {
return m_compositions.at(symbol).number_fraction(m_specificNumberDensity);
}
}
std::unordered_map<std::string, double> Composition::getNumberFraction() const {
std::unordered_map<std::string, double> number_fractions;
for (const auto& [symbol, entry] : m_compositions) {
number_fractions[symbol] = getNumberFraction(symbol);
}
return number_fractions;
}
std::pair<CompositionEntry, GlobalComposition> Composition::getComposition(const std::string& symbol) const {
if (!m_finalized) {
LOG_ERROR(m_logger, "Composition has not been finalized.");
throw std::runtime_error("Composition has not been finalized (Consider running .finalize()).");
}
if (m_compositions.count(symbol) == 0) {
LOG_ERROR(m_logger, "Symbol {} is not in the composition.", symbol);
throw std::runtime_error("Symbol is not in the composition.");
}
return {m_compositions.at(symbol), {m_specificNumberDensity, m_meanParticleMass}};
}
std::pair<std::unordered_map<std::string, CompositionEntry>, GlobalComposition> Composition::getComposition() const {
if (!m_finalized) {
LOG_ERROR(m_logger, "Composition has not been finalized.");
throw std::runtime_error("Composition has not been finalized (Consider running .finalize()).");
}
return {m_compositions, {m_specificNumberDensity, m_meanParticleMass}};
}
Composition Composition::subset(const std::vector<std::string>& symbols, std::string method) const {
std::array<std::string, 2> methods = {"norm", "none"};
if (std::find(methods.begin(), methods.end(), method) == methods.end()) {
std::string errorMessage = "Invalid method: " + method + ". Valid methods are 'norm' and 'none'.";
LOG_ERROR(m_logger, "Invalid method: {}. Valid methods are norm and none.", method);
throw std::runtime_error(errorMessage);
}
Composition subsetComposition;
for (const auto& symbol : symbols) {
if (m_compositions.count(symbol) == 0) {
LOG_ERROR(m_logger, "Symbol {} is not in the composition.", symbol);
throw std::runtime_error("Symbol is not in the composition.");
} else {
subsetComposition.registerSymbol(symbol);
}
subsetComposition.setMassFraction(symbol, m_compositions.at(symbol).mass_fraction());
}
if (method == "norm") {
bool isNorm = subsetComposition.finalize(true);
if (!isNorm) {
LOG_ERROR(m_logger, "Subset composition is invalid.");
throw std::runtime_error("Subset composition is invalid.");
}
}
return subsetComposition;
}
void Composition::setCompositionMode(bool massFracMode) {
if (!m_finalized) {
LOG_ERROR(m_logger, "Composition has not been finalized. Mode cannot be set unless composition is finalized.");
throw std::runtime_error("Composition has not been finalized (Consider running .finalize()). The mode cannot be set unless the composition is finalized.");
}
bool okay = true;
for (auto& [_, entry] : m_compositions) {
if (massFracMode) {
okay = entry.setMassFracMode(m_meanParticleMass);
} else {
okay = entry.setNumberFracMode(m_specificNumberDensity);
}
if (!okay) {
LOG_ERROR(m_logger, "Composition mode could not be set.");
throw std::runtime_error("Composition mode could not be set due to an unknown error.");
}
}
m_massFracMode = massFracMode;
}
bool Composition::hasSymbol(const std::string& symbol) const {
return m_compositions.count(symbol) > 0;
}
/// OVERLOADS
Composition Composition::operator+(const Composition& other) const {
return mix(other, 0.5);
}
std::ostream& composition::operator<<(std::ostream& os, const Composition& composition) {
os << "Composition: \n";
for (const auto& [symbol, entry] : composition.m_compositions) {
os << entry << "\n";
}
return os;
}

View File

@@ -0,0 +1,456 @@
#ifndef COMPOSITION_H
#define COMPOSITION_H
#include <iostream>
#include <string>
#include <unordered_map>
#include <set>
#include <utility>
#include "probe.h"
#include "config.h"
#include "atomicSpecies.h"
namespace composition{
/**
* @brief Represents the global composition of a system. This tends to be used after finalize and is primarily for internal use.
*/
struct GlobalComposition {
double specificNumberDensity; ///< The specific number density of the composition (\sum_{i} X_i m_i. Where X_i is the number fraction of the ith species and m_i is the mass of the ith species).
double meanParticleMass; ///< The mean particle mass of the composition (\sum_{i} \frac{n_i}{m_i}. where n_i is the number fraction of the ith species and m_i is the mass of the ith species).
// Overload the output stream operator for GlobalComposition
friend std::ostream& operator<<(std::ostream& os, const GlobalComposition& comp) {
os << "Global Composition: \n";
os << "\tSpecific Number Density: " << comp.specificNumberDensity << "\n";
os << "\tMean Particle Mass: " << comp.meanParticleMass << "\n";
return os;
}
};
/**
* @brief Represents an entry in the composition with a symbol and mass fraction.
*/
struct CompositionEntry {
std::string m_symbol; ///< The chemical symbol of the species.
chemSpecies::Species m_isotope; ///< The isotope of the species.
bool m_massFracMode = true; ///< The mode of the composition entry. True if mass fraction, false if number fraction.
double m_massFraction = 0.0; ///< The mass fraction of the species.
double m_numberFraction = 0.0; ///< The number fraction of the species.
double m_relAbundance = 0.0; ///< The relative abundance of the species for converting between mass and number fractions.
bool m_initialized = false; ///< True if the composition entry has been initialized.
/**
* @brief Default constructor.
*/
CompositionEntry();
/**
* @brief Constructs a CompositionEntry with the given symbol and mode.
* @param symbol The chemical symbol of the species.
* @param massFracMode True if mass fraction mode, false if number fraction mode.
* @example
* @code
* CompositionEntry entry("H", true);
* @endcode
*/
CompositionEntry(const std::string& symbol, bool massFracMode=true);
/**
* @brief Copy constructor.
* @param entry The CompositionEntry to copy.
*/
CompositionEntry(const CompositionEntry& entry);
/**
* @brief Sets the species for the composition entry.
* @param symbol The chemical symbol of the species.
*/
void setSpecies(const std::string& symbol);
/**
* @brief Gets the chemical symbol of the species.
* @return The chemical symbol of the species.
*/
std::string symbol() const;
/**
* @brief Gets the mass fraction of the species.
* @return The mass fraction of the species.
*/
double mass_fraction() const;
/**
* @brief Gets the mass fraction of the species given the mean molar mass.
* @param meanMolarMass The mean molar mass.
* @return The mass fraction of the species.
*/
double mass_fraction(double meanMolarMass) const;
/**
* @brief Gets the number fraction of the species.
* @return The number fraction of the species.
*/
double number_fraction() const;
/**
* @brief Gets the number fraction of the species given the total moles.
* @param totalMoles The total moles.
* @return The number fraction of the species.
*/
double number_fraction(double totalMoles) const;
/**
* @brief Gets the relative abundance of the species.
* @return The relative abundance of the species.
*/
double rel_abundance() const;
/**
* @brief Gets the isotope of the species.
* @return The isotope of the species.
*/
chemSpecies::Species isotope() const;
/**
* @brief Gets the mode of the composition entry.
* @return True if mass fraction mode, false if number fraction mode.
*/
bool getMassFracMode() const;
/**
* @brief Sets the mass fraction of the species.
* @param mass_fraction The mass fraction to set.
*/
void setMassFraction(double mass_fraction);
/**
* @brief Sets the number fraction of the species.
* @param number_fraction The number fraction to set.
*/
void setNumberFraction(double number_fraction);
/**
* @brief Sets the mode to mass fraction mode.
* @param meanMolarMass The mean molar mass.
* @return True if the mode was successfully set, false otherwise.
*/
bool setMassFracMode(double meanMolarMass);
/**
* @brief Sets the mode to number fraction mode.
* @param totalMoles The total moles.
* @return True if the mode was successfully set, false otherwise.
*/
bool setNumberFracMode(double totalMoles);
/**
* @brief Overloaded output stream operator for CompositionEntry.
* @param os The output stream.
* @param entry The CompositionEntry to output.
* @return The output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const CompositionEntry& entry) {
os << "<" << entry.m_symbol << " : m_frac = " << entry.mass_fraction() << ">";
return os;
}
};
/**
* @brief Manages the composition of elements.
* @details The composition is a collection of elements with their respective mass fractions.
* The general purpose of this class is to provide a standardized interface for managing the composition of
* any part of 4DSSE. There are a few rules when using this class.
* - Only species in the atomicSpecies.h database can be used. There are 1000s (All species from AME2020) in there so it should not be a problem.
* - Before a mass fraction can be set with a particular instance of Composition, the symbol must be registered. (i.e. register He-3 before setting its mass fraction)
* - Before any composition information can be retrived (e.g. getComposition), the composition must be finalized (call to .finalize()). This checks if the total mass fraction sums to approximatly 1 (within 1 part in 10^8)
* - Any changes made to the composition after finalization will "unfinalize" the composition. This means that the composition must be finalized again before any information can be retrived.
* - The mass fraction of any individual species must be no more than 1 and no less than 0.
* - The only exception to the finalize rule is if the compositon was constructed with symbols and mass fractions at instantiation time. In this case, the composition is automatically finalized.
* however, this means that the composition passed to the constructor must be valid.
*
* @example Constructing a finalized composition with symbols and mass fractions:
* @code
* std::vector<std::string> symbols = {"H", "He"};
* std::vector<double> mass_fractions = {0.7, 0.3};
* Composition comp(symbols, mass_fractions);
* @endcode
* @example Constructing a composition with symbols and finalizing it later:
* @code
* std::vector<std::string> symbols = {"H", "He"};
* Composition comp(symbols);
* comp.setComposition("H", 0.7);
* comp.setComposition("He", 0.3);
* comp.finalize();
* @endcode
*/
class Composition {
private:
Config& m_config = Config::getInstance();
Probe::LogManager& m_logManager = Probe::LogManager::getInstance();
quill::Logger* m_logger = m_logManager.getLogger("log");
bool m_finalized = false; ///< True if the composition is finalized.
double m_specificNumberDensity = 0.0; ///< The specific number density of the composition (\sum_{i} X_i m_i. Where X_i is the number fraction of the ith species and m_i is the mass of the ith species).
double m_meanParticleMass = 0.0; ///< The mean particle mass of the composition (\sum_{i} \frac{n_i}{m_i}. where n_i is the number fraction of the ith species and m_i is the mass of the ith species).
bool m_massFracMode = true; ///< True if mass fraction mode, false if number fraction mode.
std::set<std::string> m_registeredSymbols; ///< The registered symbols.
std::unordered_map<std::string, CompositionEntry> m_compositions; ///< The compositions.
/**
* @brief Checks if the given symbol is valid.
* @details A symbol is valid if it is in the atomic species database (species in atomicSpecies.h). These include all the isotopes from AME2020.
* @param symbol The symbol to check.
* @return True if the symbol is valid, false otherwise.
*/
bool isValidSymbol(const std::string& symbol) const;
/**
* @brief Checks if the given mass fractions are valid.
* @param mass_fractions The mass fractions to check.
* @return True if the mass fractions are valid, false otherwise.
*/
bool isValidComposition(const std::vector<double>& fractions) const;
/**
* @brief Validates the given mass fractions.
* @param mass_fractions The mass fractions to validate.
* @throws std::invalid_argument if the mass fractions are invalid.
*/
void validateComposition(const std::vector<double>& fractions) const;
/**
* @brief Finalizes the composition in mass fraction mode.
* @param norm If true, the composition will be normalized to sum to 1.
* @return True if the composition is successfully finalized, false otherwise.
*/
bool finalizeMassFracMode(bool norm);
/**
* @brief Finalizes the composition in number fraction mode.
* @param norm If true, the composition will be normalized to sum to 1.
* @return True if the composition is successfully finalized, false otherwise.
*/
bool finalizeNumberFracMode(bool norm);
public:
/**
* @brief Default constructor.
*/
Composition() = default;
/**
* @brief Default destructor.
*/
~Composition() = default;
/**
* @brief Finalizes the composition.
* @param norm If true, the composition will be normalized to sum to 1 [Default False]
* @return True if the composition is successfully finalized, false otherwise.
*/
bool finalize(bool norm=false);
/**
* @brief Constructs a Composition with the given symbols.
* @param symbols The symbols to initialize the composition with.
* @example
* @code
* std::vector<std::string> symbols = {"H", "O"};
* Composition comp(symbols);
* @endcode
*/
Composition(const std::vector<std::string>& symbols);
/**
* @brief Constructs a Composition with the given symbols as a set.
* @param symbols The symbols to initialize the composition with.
* @example
* @code
* std::set<std::string> symbols = {"H", "O"};
* Composition comp(symbols);
* @endcode
*/
Composition(const std::set<std::string>& symbols);
/**
* @brief Constructs a Composition with the given symbols and mass fractions.
* @param symbols The symbols to initialize the composition with.
* @param mass_fractions The mass fractions corresponding to the symbols.
* @param massFracMode True if mass fraction mode, false if number fraction mode.
* @example
* @code
* std::vector<std::string> symbols = {"H", "O"};
* std::vector<double> mass_fractions = {0.1, 0.9};
* Composition comp(symbols, mass_fractions);
* @endcode
*/
Composition(const std::vector<std::string>& symbols, const std::vector<double>& mass_fractions, bool massFracMode=true);
/**
* @brief Registers a new symbol.
* @param symbol The symbol to register.
* @param massFracMode True if mass fraction mode, false if number fraction mode.
* @example
* @code
* Composition comp;
* comp.registerSymbol("H");
* @endcode
*/
void registerSymbol(const std::string& symbol, bool massFracMode=true);
/**
* @brief Registers multiple new symbols.
* @param symbols The symbols to register.
* @param massFracMode True if mass fraction mode, false if number fraction mode.
* @example
* @code
* std::vector<std::string> symbols = {"H", "O"};
* Composition comp;
* comp.registerSymbol(symbols);
* @endcode
*/
void registerSymbol(const std::vector<std::string>& symbols, bool massFracMode=true);
/**
* @brief Gets the registered symbols.
* @return A set of registered symbols.
*/
std::set<std::string> getRegisteredSymbols() const;
/**
* @brief Sets the mass fraction for a given symbol.
* @param symbol The symbol to set the mass fraction for.
* @param mass_fraction The mass fraction to set.
* @return The mass fraction that was set.
* @example
* @code
* Composition comp;
* comp.setMassFraction("H", 0.1);
* @endcode
*/
double setMassFraction(const std::string& symbol, const double& mass_fraction);
/**
* @brief Sets the mass fraction for multiple symbols.
* @param symbols The symbols to set the mass fraction for.
* @param mass_fractions The mass fractions corresponding to the symbols.
* @return A vector of mass fractions that were set.
* @example
* @code
* std::vector<std::string> symbols = {"H", "O"};
* std::vector<double> mass_fractions = {0.1, 0.9};
* Composition comp;
* comp.setMassFraction(symbols, mass_fractions);
* @endcode
*/
std::vector<double> setMassFraction(const std::vector<std::string>& symbols, const std::vector<double>& mass_fractions);
/**
* @brief Sets the number fraction for a given symbol.
* @param symbol The symbol to set the number fraction for.
* @param number_fraction The number fraction to set.
* @return The number fraction that was set.
*/
double setNumberFraction(const std::string& symbol, const double& number_fraction);
/**
* @brief Sets the number fraction for multiple symbols.
* @param symbols The symbols to set the number fraction for.
* @param number_fractions The number fractions corresponding to the symbols.
* @return A vector of number fractions that were set.
*/
std::vector<double> setNumberFraction(const std::vector<std::string>& symbols, const std::vector<double>& number_fractions);
/**
* @brief Mix two compositions together with a given fraction.
* @param other The other composition to mix with.
* @param fraction The fraction of the other composition to mix with. This is the fraction of the other composition wrt. to the current. i.e. fraction=1 would mean that 50% of the new composition is from the other and 50% from the current).
*/
Composition mix(const Composition& other, double fraction) const;
/**
* @brief Gets the mass fractions of all compositions.
* @return An unordered map of compositions with their mass fractions.
*/
std::unordered_map<std::string, double> getMassFraction() const;
/**
* @brief Gets the mass fraction for a given symbol.
* @param symbol The symbol to get the mass fraction for.
* @return The mass fraction for the given symbol.
*/
double getMassFraction(const std::string& symbol) const;
/**
* @brief Gets the number fraction for a given symbol.
* @param symbol The symbol to get the number fraction for.
* @return The number fraction for the given symbol.
*/
double getNumberFraction(const std::string& symbol) const;
/**
* @brief Gets the number fractions of all compositions.
* @return An unordered map of compositions with their number fractions.
*/
std::unordered_map<std::string, double> getNumberFraction() const;
/**
* @brief Gets the composition entry and global composition for a given symbol.
* @param symbol The symbol to get the composition for.
* @return A pair containing the CompositionEntry and GlobalComposition for the given symbol.
*/
std::pair<CompositionEntry, GlobalComposition> getComposition(const std::string& symbol) const;
/**
* @brief Gets all composition entries and the global composition.
* @return A pair containing an unordered map of CompositionEntries and the GlobalComposition.
*/
std::pair<std::unordered_map<std::string, CompositionEntry>, GlobalComposition> getComposition() const;
/**
* @brief Gets a subset of the composition.
* @param symbols The symbols to include in the subset.
* @param method The method to use for the subset (default is "norm").
* @return A Composition object containing the subset.
*/
Composition subset(const std::vector<std::string>& symbols, std::string method="norm") const;
/**
* @brief Check if a symbol is registered.
* @param symbol The symbol to check.
* @return True if the symbol is registered, false otherwise.
*/
bool hasSymbol(const std::string& symbol) const;
/**
* @brief Sets the composition mode.
* @param massFracMode True if mass fraction mode, false if number fraction mode.
*/
void setCompositionMode(bool massFracMode);
/**
* @brief Overloaded output stream operator for Composition.
* @param os The output stream.
* @param composition The Composition to output.
* @return The output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const Composition& composition);
// Overload the + operator to call mix with a fraction of 0.5
/**
* @brief Overloads the + operator to mix two compositions together with a fraction of 0.5.
* @param other The other composition to mix with.
* @return The mixed composition.
*/
Composition operator+(const Composition& other) const;
};
};
#endif // COMPOSITION_H

View File

@@ -46,7 +46,7 @@ bool Config::loadConfig(const std::string& configFile) {
std::cerr << "Error: " << e.what() << std::endl;
return false;
}
loaded = true;
m_loaded = true;
return true;
}
@@ -61,3 +61,45 @@ void Config::addToCache(const std::string &key, const YAML::Node &node) {
void Config::registerUnknownKey(const std::string &key) {
unknownKeys.push_back(key);
}
bool Config::has(const std::string &key) {
if (!m_loaded) {
throw std::runtime_error("Error! Config file not loaded");
}
if (isKeyInCache(key)) { return true; }
YAML::Node node = YAML::Clone(yamlRoot);
std::istringstream keyStream(key);
std::string subKey;
while (std::getline(keyStream, subKey, ':')) {
if (!node[subKey]) {
registerUnknownKey(key);
return false;
}
node = node[subKey]; // go deeper
}
// Key exists and is of the requested type
addToCache(key, node);
return true;
}
void recurse_keys(const YAML::Node& node, std::vector<std::string>& keyList, const std::string& path = "") {
if (node.IsMap()) {
for (const auto& it : node) {
std::string key = it.first.as<std::string>();
std::string new_path = path.empty() ? key : path + ":" + key;
recurse_keys(it.second, keyList, new_path);
}
} else {
keyList.push_back(path);
}
}
std::vector<std::string> Config::keys() const {
std::vector<std::string> keyList;
YAML::Node node = YAML::Clone(yamlRoot);
recurse_keys(node, keyList);
return keyList;
}

View File

@@ -23,15 +23,19 @@
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <stdexcept>
#include <stdexcept>
// Required for YAML parsing
#include "yaml-cpp/yaml.h"
// -- Forward Def of Resource manager to let it act as a friend of Config --
class ResourceManager;
/**
* @class Config
* @brief Singleton class to manage configuration settings loaded from a YAML file.
@@ -96,6 +100,21 @@ private:
*/
void registerUnknownKey(const std::string &key);
bool m_loaded = false;
// Only friends can access get without a default value
template <typename T>
T get(const std::string &key) {
if (!m_loaded) {
throw std::runtime_error("Error! Config file not loaded");
}
if (has(key)) {
return getFromCache<T>(key, T());
} else {
throw std::runtime_error("Error! Key not found in config file");
}
}
public:
/**
* @brief Get the singleton instance of the Config class.
@@ -138,7 +157,7 @@ public:
*/
template <typename T>
T get(const std::string &key, T defaultValue) {
if (!loaded) {
if (!m_loaded) {
throw std::runtime_error("Configuration file not loaded! This should be done at the very start of whatever main function you are using (and only done once!)");
}
// --- Check if the key has already been checked for existence
@@ -176,6 +195,19 @@ public:
}
}
/**
* @brief Check if the key exists in the given config file
* @param key Key to check;
* @return boolean true or false
*/
bool has(const std::string &key);
/**
* @brief Get all keys defined in the configuration file.
* @return Vector of all keys in the configuration file.
*/
std::vector<std::string> keys() const;
/**
* @brief Print the configuration file path and the YAML root node.
* @param os Output stream.
@@ -183,6 +215,10 @@ public:
* @return Output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const Config& config) {
if (!config.m_loaded) {
os << "Config file not loaded" << std::endl;
return os;
}
if (!config.debug) {
os << "Config file: " << config.configFilePath << std::endl;
} else{
@@ -195,6 +231,8 @@ public:
// Setup gTest class as a friend
friend class configTestPrivateAccessor;
// -- Resource Manager is a friend of config so it can create a seperate instance
friend class ResourceManager;
};
#endif

View File

@@ -1,23 +1,34 @@
# Define the library
eos_sources = files(
'private/helm.cpp',
'private/eosIO.cpp'
)
eos_headers = files(
'public/helm.h'
'public/helm.h',
'public/eosIO.h'
)
dependencies = [
const_dep,
quill_dep,
probe_dep,
config_dep,
mfem_dep,
macros_dep,
]
# Define the libconst library so it can be linked against by other parts of the build system
libeos = static_library('eos',
eos_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
dependencies: [const_dep, quill_dep, probe_dep, config_dep, mfem_dep],
dependencies: dependencies,
install : true)
eos_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libeos,
dependencies: dependencies
)
# Make headers accessible
install_headers(eos_headers, subdir : '4DSSE/eos')

36
src/eos/private/eosIO.cpp Normal file
View File

@@ -0,0 +1,36 @@
#include <string>
#include "eosIO.h"
#include "helm.h"
#include "debug.h"
EosIO::EosIO(const std::string filename) : m_filename(filename) {
load();
}
std::string EosIO::getFormat() const {
return m_format;
}
EOSTable& EosIO::getTable() {
return m_table;
}
void EosIO::load() {
// Load the EOS table from the file
// For now, just set the format to HELM
m_format = "helm";
if (m_format == "helm") {
loadHelm();
}
}
void EosIO::loadHelm() {
// Load the HELM table from the file
auto helmTabptr = helmholtz::read_helm_table(m_filename);
m_table = std::move(helmTabptr);
m_loaded = true;
}

View File

@@ -24,6 +24,7 @@
#include <iostream>
#include <fstream>
#include <memory>
#include <sstream>
#include <cmath>
#include <string>
@@ -121,21 +122,22 @@ namespace helmholtz {
}
// this function reads in the HELM table and stores in the above arrays
HELMTable read_helm_table(const std::string filename) {
std::unique_ptr<HELMTable> read_helm_table(const std::string filename) {
Config& config = Config::getInstance();
std::string logFile = config.get<std::string>("EOS:Helm:LogFile", "log");
Probe::LogManager& logManager = Probe::LogManager::getInstance();
quill::Logger* logger = logManager.getLogger(logFile);
LOG_INFO(logger, "read_helm_table : Reading HELM table from file {}", filename);
HELMTable table;
// Make a unique pointer to the HELMTable
std::unique_ptr<HELMTable> table = std::make_unique<HELMTable>();
string data;
int i, j;
//set T and Rho (d) arrays
for (j=0; j<table.jmax; j++) { table.t[j] = pow(10, tlo + tstp*j); }
for (j=0; j<table->jmax; j++) { table->t[j] = pow(10, tlo + tstp*j); }
for (i=0; i<table.imax; i++) { table.d[i] = pow(10, dlo + dstp*i); }
for (i=0; i<table->imax; i++) { table->d[i] = pow(10, dlo + dstp*i); }
ifstream helm_table(filename);
if (!helm_table) {
@@ -144,83 +146,83 @@ namespace helmholtz {
throw std::runtime_error("Error (" + std::to_string(errorCode) + ") opening file " + filename);
}
//read the Helmholtz free energy and its derivatives
for (j=0; j<table.jmax; j++) {
for (i=0; i<table.imax; i++){
for (j=0; j<table->jmax; j++) {
for (i=0; i<table->imax; i++){
getline(helm_table, data);
stringstream id(data);
id >> table.f[i][j];
id >> table.fd[i][j];
id >> table.ft[i][j];
id >> table.fdd[i][j];
id >> table.ftt[i][j];
id >> table.fdt[i][j];
id >> table.fddt[i][j];
id >> table.fdtt[i][j];
id >> table.fddtt[i][j];
id >> table->f[i][j];
id >> table->fd[i][j];
id >> table->ft[i][j];
id >> table->fdd[i][j];
id >> table->ftt[i][j];
id >> table->fdt[i][j];
id >> table->fddt[i][j];
id >> table->fdtt[i][j];
id >> table->fddtt[i][j];
}
}
//read the pressure derivative with density
for (j=0; j<table.jmax; j++) {
for (i=0; i<table.imax; i++){
for (j=0; j<table->jmax; j++) {
for (i=0; i<table->imax; i++){
getline(helm_table, data);
stringstream id(data);
id >> table.dpdf[i][j];
id >> table.dpdfd[i][j];
id >> table.dpdft[i][j];
id >> table.dpdfdt[i][j];
id >> table->dpdf[i][j];
id >> table->dpdfd[i][j];
id >> table->dpdft[i][j];
id >> table->dpdfdt[i][j];
}
}
//read the electron chemical potential
for (j=0; j<table.jmax; j++) {
for (i=0; i<table.imax; i++){
for (j=0; j<table->jmax; j++) {
for (i=0; i<table->imax; i++){
getline(helm_table, data);
stringstream id(data);
id >> table.ef[i][j];
id >> table.efd[i][j];
id >> table.eft[i][j];
id >> table.efdt[i][j];
id >> table->ef[i][j];
id >> table->efd[i][j];
id >> table->eft[i][j];
id >> table->efdt[i][j];
}
}
//read the number density
for (j=0; j<table.jmax; j++) {
for (i=0; i<table.imax; i++){
for (j=0; j<table->jmax; j++) {
for (i=0; i<table->imax; i++){
getline(helm_table, data);
stringstream id(data);
id >> table.xf[i][j];
id >> table.xfd[i][j];
id >> table.xft[i][j];
id >> table.xfdt[i][j];
id >> table->xf[i][j];
id >> table->xfd[i][j];
id >> table->xft[i][j];
id >> table->xfdt[i][j];
}
}
helm_table.close(); //done reading
// construct the temperature and density deltas and their inverses
for (j=0; j<table.jmax; j++) {
double dth = table.t[j+1] - table.t[j];
for (j=0; j<table->jmax; j++) {
double dth = table->t[j+1] - table->t[j];
double dt2 = dth * dth;
double dti = 1.0/dth;
double dt2i = 1.0/dt2;
table.dt_sav[j] = dth;
table.dt2_sav[j] = dt2;
table.dti_sav[j] = dti;
table.dt2i_sav[j] = dt2i;
table->dt_sav[j] = dth;
table->dt2_sav[j] = dt2;
table->dti_sav[j] = dti;
table->dt2i_sav[j] = dt2i;
}
for (i=0; i<table.imax; i++) {
double dd = table.d[i+1] - table.d[i];
for (i=0; i<table->imax; i++) {
double dd = table->d[i+1] - table->d[i];
double dd2 = dd * dd;
double ddi = 1.0/dd;
table.dd_sav[i] = dd;
table.dd2_sav[i] = dd2;
table.ddi_sav[i] = ddi;
table->dd_sav[i] = dd;
table->dd2_sav[i] = dd2;
table->ddi_sav[i] = ddi;
}
table.loaded = true;
table->loaded = true;
return table;
}

70
src/eos/public/eosIO.h Normal file
View File

@@ -0,0 +1,70 @@
#ifndef EOSIO_H
#define EOSIO_H
#include <string>
#include <variant>
#include <memory>
// EOS table format includes
#include "helm.h"
using EOSTable = std::variant<
std::unique_ptr<helmholtz::HELMTable>
>;
/**
* @class EosIO
* @brief Handles the input/output operations for EOS tables.
*
* The EosIO class is responsible for loading and managing EOS tables from files.
* It supports different formats, currently only HELM format.
*
* Example usage:
* @code
* EosIO eosIO("path/to/file");
* std::string format = eosIO.getFormat();
* EOSTable& table = eosIO.getTable();
* @endcode
*/
class EosIO {
private:
std::string m_filename; ///< The filename of the EOS table.
bool m_loaded = false; ///< Flag indicating if the table is loaded.
std::string m_format; ///< The format of the EOS table.
EOSTable m_table; ///< The EOS table data.
/**
* @brief Loads the EOS table from the file.
*/
void load();
/**
* @brief Loads the HELM format EOS table.
*/
void loadHelm();
public:
/**
* @brief Constructs an EosIO object with the given filename.
* @param filename The filename of the EOS table.
*/
EosIO(const std::string filename);
/**
* @brief Default destructor.
*/
~EosIO() = default;
/**
* @brief Gets the format of the EOS table.
* @return The format of the EOS table as a string.
*/
std::string getFormat() const;
/**
* @brief Gets the EOS table.
* @return A reference to the EOS table.
*/
EOSTable& getTable();
};
#endif // EOSIO_H

View File

@@ -35,6 +35,8 @@
#include <string>
#include <format>
#include "debug.h"
/**
* @brief 2D array template alias.
* @tparam T Type of the array elements.
@@ -139,6 +141,118 @@ namespace helmholtz
heap_deallocate_contiguous_2D_memory(xfdt);
}
// // Delete copy constructor and copy assignment operator to prevent accidental shallow copies
// HELMTable(const HELMTable&) = delete;
// HELMTable& operator=(const HELMTable&) = delete;
// // Move constructor
// HELMTable(HELMTable&& other) noexcept
// : loaded(other.loaded),
// f(other.f), fd(other.fd), ft(other.ft), fdd(other.fdd), ftt(other.ftt), fdt(other.fdt),
// fddt(other.fddt), fdtt(other.fdtt), fddtt(other.fddtt),
// dpdf(other.dpdf), dpdfd(other.dpdfd), dpdft(other.dpdft), dpdfdt(other.dpdfdt),
// ef(other.ef), efd(other.efd), eft(other.eft), efdt(other.efdt),
// xf(other.xf), xfd(other.xfd), xft(other.xft), xfdt(other.xfdt)
// {
// other.f = nullptr;
// other.fd = nullptr;
// other.ft = nullptr;
// other.fdd = nullptr;
// other.ftt = nullptr;
// other.fdt = nullptr;
// other.fddt = nullptr;
// other.fdtt = nullptr;
// other.fddtt = nullptr;
// other.dpdf = nullptr;
// other.dpdfd = nullptr;
// other.dpdft = nullptr;
// other.dpdfdt = nullptr;
// other.ef = nullptr;
// other.efd = nullptr;
// other.eft = nullptr;
// other.efdt = nullptr;
// other.xf = nullptr;
// other.xfd = nullptr;
// other.xft = nullptr;
// other.xfdt = nullptr;
// }
// // Move assignment operator
// HELMTable& operator=(HELMTable&& other) noexcept {
// if (this != &other) {
// // Deallocate current memory
// heap_deallocate_contiguous_2D_memory(f);
// heap_deallocate_contiguous_2D_memory(fd);
// heap_deallocate_contiguous_2D_memory(ft);
// heap_deallocate_contiguous_2D_memory(fdd);
// heap_deallocate_contiguous_2D_memory(ftt);
// heap_deallocate_contiguous_2D_memory(fdt);
// heap_deallocate_contiguous_2D_memory(fddt);
// heap_deallocate_contiguous_2D_memory(fdtt);
// heap_deallocate_contiguous_2D_memory(fddtt);
// heap_deallocate_contiguous_2D_memory(dpdf);
// heap_deallocate_contiguous_2D_memory(dpdfd);
// heap_deallocate_contiguous_2D_memory(dpdft);
// heap_deallocate_contiguous_2D_memory(dpdfdt);
// heap_deallocate_contiguous_2D_memory(ef);
// heap_deallocate_contiguous_2D_memory(efd);
// heap_deallocate_contiguous_2D_memory(eft);
// heap_deallocate_contiguous_2D_memory(efdt);
// heap_deallocate_contiguous_2D_memory(xf);
// heap_deallocate_contiguous_2D_memory(xfd);
// heap_deallocate_contiguous_2D_memory(xft);
// heap_deallocate_contiguous_2D_memory(xfdt);
// // Transfer ownership of resources
// loaded = other.loaded;
// f = other.f;
// fd = other.fd;
// ft = other.ft;
// fdd = other.fdd;
// ftt = other.ftt;
// fdt = other.fdt;
// fddt = other.fddt;
// fdtt = other.fdtt;
// fddtt = other.fddtt;
// dpdf = other.dpdf;
// dpdfd = other.dpdfd;
// dpdft = other.dpdft;
// dpdfdt = other.dpdfdt;
// ef = other.ef;
// efd = other.efd;
// eft = other.eft;
// efdt = other.efdt;
// xf = other.xf;
// xfd = other.xfd;
// xft = other.xft;
// xfdt = other.xfdt;
// // Null out the other object's pointers
// other.f = nullptr;
// other.fd = nullptr;
// other.ft = nullptr;
// other.fdd = nullptr;
// other.ftt = nullptr;
// other.fdt = nullptr;
// other.fddt = nullptr;
// other.fdtt = nullptr;
// other.fddtt = nullptr;
// other.dpdf = nullptr;
// other.dpdfd = nullptr;
// other.dpdft = nullptr;
// other.dpdfdt = nullptr;
// other.ef = nullptr;
// other.efd = nullptr;
// other.eft = nullptr;
// other.efdt = nullptr;
// other.xf = nullptr;
// other.xfd = nullptr;
// other.xft = nullptr;
// other.xfdt = nullptr;
// }
// return *this;
// }
friend std::ostream& operator<<(std::ostream& os, const helmholtz::HELMTable& table) {
if (!table.loaded) {
os << "HELMTable not loaded\n";
@@ -371,7 +485,7 @@ namespace helmholtz
* @param filename Path to the file containing the table.
* @return HELMTable structure containing the table data.
*/
HELMTable read_helm_table(const std::string filename);
std::unique_ptr<HELMTable> read_helm_table(const std::string filename);
/**
* @brief Calculate the Helmholtz EOS components.

View File

@@ -6,18 +6,22 @@ meshIO_sources = files(
meshIO_headers = files(
'public/meshIO.h'
)
dependencies = [
mfem_dep
]
# Define the libmeshIO library so it can be linked against by other parts of the build system
libmeshIO = static_library('meshIO',
meshIO_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
dependencies: [mfem_dep],
dependencies: dependencies,
install : true)
meshio_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libmeshIO,
sources: meshIO_sources,
dependencies: [mfem_dep]
)
dependencies: dependencies
)
# Make headers accessible
install_headers(meshIO_headers, subdir : '4DSSE/meshIO')

View File

@@ -1,12 +1,24 @@
# Build resources first so that all the embedded resources are available to the other targets
subdir('resources')
# Build the main source code in the correct order
# Unless you know what you are doing, do not change the order of the subdirectories
# as there are dependencies which exist between them.
# Build the main source code
# Utility Libraries
subdir('misc')
subdir('config')
subdir('dobj')
subdir('const')
subdir('opatIO')
subdir('meshIO')
subdir('probe')
subdir('dobj')
# Physically Informed Libraries
subdir('const')
subdir('composition')
# Asset Libraries
subdir('eos')
subdir('meshIO')
# Resouce Manager Libraries
subdir('resource')
# Physics Libraries
subdir('network')
subdir('poly')

36
src/misc/macros/debug.h Normal file
View File

@@ -0,0 +1,36 @@
/**
* @file debug.h
* @brief Defines a macro for triggering a breakpoint in different compilers and platforms.
*
* This file provides a macro `BREAKPOINT()` that triggers a breakpoint
* in the debugger, depending on the compiler and platform being used.
*
* Usage:
* @code
* BREAKPOINT(); // Triggers a breakpoint in the debugger
* @endcode
*/
#ifdef __GNUC__ // GCC and Clang
/**
* @brief Triggers a breakpoint in GCC and Clang.
*/
#define BREAKPOINT() __builtin_debugtrap()
#elif defined(_MSC_VER) // MSVC
/**
* @brief Triggers a breakpoint in MSVC.
*/
#define BREAKPOINT() __debugbreak()
#elif defined(__APPLE__) && defined(__MACH__) // macOS with Clang and LLDB
#include <signal.h>
/**
* @brief Triggers a breakpoint in macOS with Clang and LLDB.
*/
#define BREAKPOINT() raise(SIGTRAP)
#else
#include <csignal>
/**
* @brief Triggers a breakpoint in other platforms.
*/
#define BREAKPOINT() std::raise(SIGTRAP)
#endif

View File

@@ -0,0 +1,21 @@
# ***********************************************************************
#
# Copyright (C) 2025 -- The 4D-STAR Collaboration
# File Author: Emily Boudreaux
# Last Modified: March 19, 2025
#
# 4DSSE is free software; you can use it and/or modify
# it under the terms and restrictions the GNU General Library Public
# License version 3 (GPLv3) as published by the Free Software Foundation.
#
# 4DSSE 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 Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this software; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# *********************************************************************** #
macros_dep = declare_dependency(include_directories: include_directories('.'))

View File

@@ -0,0 +1,16 @@
#ifndef WARNING_CONTROL_H
#define WARNING_CONTROL_H
#if defined(__GNUC__) || defined(__clang__)
#define DEPRECATION_WARNING_OFF _Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
#define DEPRECATION_WARNING_ON _Pragma("GCC diagnostic pop")
#elif defined(_MSC_VER)
#define DEPRECATION_WARNING_OFF __pragma(warning(push)) __pragma(warning(disable: 4996))
#define DEPRECATION_WARNING_ON __pragma(warning(pop))
#else
#define DEPRECATION_WARNING_OFF
#define DEPRECATION_WARNING_ON
#endif
#endif // WARNING_CONTROL_H

2
src/misc/meson.build Normal file
View File

@@ -0,0 +1,2 @@
# IMPORTANT: DO NOT MAKE MISC DEPEND ON ANY OTHER MODULE AS IT IS THE FIRST MODULE TO BE BUILT
subdir('macros')

36
src/network/meson.build Normal file
View File

@@ -0,0 +1,36 @@
# Define the library
network_sources = files(
'private/network.cpp',
'private/approx8.cpp'
)
network_headers = files(
'public/network.h',
'public/approx8.h'
)
dependencies = [
boost_dep,
const_dep,
quill_dep,
mfem_dep,
config_dep,
probe_dep
]
# Define the libnetwork library so it can be linked against by other parts of the build system
libnetwork = static_library('network',
network_sources,
include_directories: include_directories('public'),
dependencies: dependencies,
install : true)
network_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libnetwork,
sources: network_sources,
dependencies: dependencies,
)
# Make headers accessible
install_headers(network_headers, subdir : '4DSSE/network')

View File

@@ -0,0 +1,523 @@
#include <cmath>
#include <stdexcept>
#include <array>
#include <boost/numeric/odeint.hpp>
#include "const.h"
#include "config.h"
#include "quill/LogMacros.h"
#include "approx8.h"
#include "network.h"
/* Nuclear reaction network in cgs units based on Frank Timmes' "aprox8".
At this time it does neither screening nor neutrino losses. It includes
the following 8 isotopes:
h1
he3
he4
c12
n14
o16
ne20
mg24
and the following nuclear reactions:
---pp chain---
p(p,e+)d
d(p,g)he3
he3(he3,2p)he4
---CNO cycle---
c12(p,g)n13 - n13 -> c13 + p -> n14
n14(p,g)o15 - o15 + p -> c12 + he4
n14(a,g)f18 - proceeds to ne20
n15(p,a)c12 - / these two n15 reactions are \ CNO I
n15(p,g)o16 - \ used to calculate a fraction / CNO II
o16(p,g)f17 - f17 + e -> o17 and then o17 + p -> n14 + he4
---alpha captures---
c12(a,g)o16
triple alpha
o16(a,g)ne20
ne20(a,g)mg24
c12(c12,a)ne20
c12(o16,a)mg24
At present the rates are all evaluated using a fitting function.
The coefficients to the fit are from reaclib.jinaweb.org .
*/
namespace nnApprox8{
// using namespace std;
using namespace boost::numeric::odeint;
//helper functions
// a function to multilpy two arrays and then sum the resulting elements: sum(a*b)
double sum_product( const vec7 &a, const vec7 &b){
if (a.size() != b.size()) {
throw std::runtime_error("Error: array size mismatch in sum_product");
}
double sum=0;
for (size_t i=0; i < a.size(); i++) {
sum += a[i] * b[i];
}
return sum;
}
// the fit to the nuclear reaction rates is of the form:
// exp( a0 + a1/T9 + a2/T9^(1/3) + a3*T9^(1/3) + a4*T9 + a5*T9^(5/3) + log(T9) )
// this function returns an array of the T9 terms in that order, where T9 is the temperatures in GigaKelvin
vec7 get_T9_array(const double &T) {
vec7 arr;
double T9=1e-9*T;
double T913=pow(T9,1./3.);
arr[0]=1;
arr[1]=1/T9;
arr[2]=1/T913;
arr[3]=T913;
arr[4]=T9;
arr[5]=pow(T9,5./3.);
arr[6]=log(T9);
return arr;
}
// this function uses the two preceding functions to evaluate the rate given the T9 array and the coefficients
double rate_fit(const vec7 &T9, const vec7 &coef){
return exp(sum_product(T9,coef));
}
// p + p -> d; this, like some of the other rates, this is a composite of multiple fits
double pp_rate(const vec7 &T9) {
vec7 a1 = {-34.78630, 0,-3.511930, 3.100860, -0.1983140, 1.262510e-2, -1.025170};
vec7 a2 = { -4.364990e+1,-2.460640e-3,-2.750700,-4.248770e-1,1.598700e-2,-6.908750e-4,-2.076250e-1};
return rate_fit(T9,a1) + rate_fit(T9,a2);
}
// p + d -> he3
double dp_rate(const vec7 &T9) {
vec7 a1 = {7.528980, 0, -3.720800, 0.8717820, 0, 0,-0.6666670};
vec7 a2 = {8.935250, 0, -3.720800, 0.1986540, 0, 0, 0.3333330};
return rate_fit(T9,a1) + rate_fit(T9,a2);
}
// he3 + he3 -> he4 + 2p
double he3he3_rate(const vec7 &T9){
vec7 a = {2.477880e+01,0,-12.27700,-0.1036990,-6.499670e-02,1.681910e-02,-6.666670e-01};
return rate_fit(T9,a);
}
// he3(he3,2p)he4
double he3he4_rate(const vec7 &T9){
vec7 a1 = {1.560990e+01,0.000000e+00,-1.282710e+01,-3.082250e-02,-6.546850e-01,8.963310e-02,-6.666670e-01};
vec7 a2 = {1.770750e+01,0.000000e+00,-1.282710e+01,-3.812600e+00,9.422850e-02,-3.010180e-03,1.333330e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2);
}
// he4 + he4 + he4 -> c12
double triple_alpha_rate(const vec7 &T9){
vec7 a1 = {-9.710520e-01,0.000000e+00,-3.706000e+01,2.934930e+01,-1.155070e+02,-1.000000e+01,-1.333330e+00};
vec7 a2 = {-1.178840e+01,-1.024460e+00,-2.357000e+01,2.048860e+01,-1.298820e+01,-2.000000e+01,-2.166670e+00};
vec7 a3 = {-2.435050e+01,-4.126560e+00,-1.349000e+01,2.142590e+01,-1.347690e+00,8.798160e-02,-1.316530e+01};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3);
}
// c12 + p -> n13
double c12p_rate(const vec7 &T9){
vec7 a1={1.714820e+01,0.000000e+00,-1.369200e+01,-2.308810e-01,4.443620e+00,-3.158980e+00,-6.666670e-01};
vec7 a2={1.754280e+01,-3.778490e+00,-5.107350e+00,-2.241110e+00,1.488830e-01,0.000000e+00,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2);
}
// c12 + he4 -> o16
double c12a_rate(const vec7 &T9){
vec7 a1={6.965260e+01,-1.392540e+00,5.891280e+01,-1.482730e+02,9.083240e+00,-5.410410e-01,7.035540e+01};
vec7 a2={2.546340e+02,-1.840970e+00,1.034110e+02,-4.205670e+02,6.408740e+01,-1.246240e+01,1.373030e+02};
return rate_fit(T9,a1) + rate_fit(T9,a2);
}
// n14(p,g)o15 - o15 + p -> c12 + he4
double n14p_rate(const vec7 &T9){
vec7 a1={1.701000e+01,0.000000e+00,-1.519300e+01,-1.619540e-01,-7.521230e+00,-9.875650e-01,-6.666670e-01};
vec7 a2={2.011690e+01,0.000000e+00,-1.519300e+01,-4.639750e+00,9.734580e+00,-9.550510e+00,3.333330e-01};
vec7 a3={7.654440e+00,-2.998000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a4={6.735780e+00,-4.891000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,6.820000e-02};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3) + rate_fit(T9,a4);
}
// n14(a,g)f18 assumed to go on to ne20
double n14a_rate(const vec7 &T9){
vec7 a1={2.153390e+01,0.000000e+00,-3.625040e+01,0.000000e+00,0.000000e+00,-5.000000e+00,-6.666670e-01};
vec7 a2={1.968380e-01,-5.160340e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a3={1.389950e+01,-1.096560e+01,-5.622700e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3);
}
// n15(p,a)c12 (CNO I)
double n15pa_rate(const vec7 &T9){
vec7 a1 = {2.747640e+01,0.000000e+00,-1.525300e+01,1.593180e+00,2.447900e+00,-2.197080e+00,-6.666670e-01};
vec7 a2 = {-4.873470e+00,-2.021170e+00,0.000000e+00,3.084970e+01,-8.504330e+00,-1.544260e+00,-1.500000e+00};
vec7 a3 = {2.089720e+01,-7.406000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a4 = {-6.575220e+00,-1.163800e+00,0.000000e+00,2.271050e+01,-2.907070e+00,2.057540e-01,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3) + rate_fit(T9,a4);
}
// n15(p,g)o16 (CNO II)
double n15pg_rate(const vec7 &T9){
vec7 a1 = {2.001760e+01,0.000000e+00,-1.524000e+01,3.349260e-01,4.590880e+00,-4.784680e+00,-6.666670e-01};
vec7 a2 = {6.590560e+00,-2.923150e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a3 = {1.454440e+01,-1.022950e+01,0.000000e+00,0.000000e+00,4.590370e-02,0.000000e+00,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3);
}
double n15pg_frac(const vec7 &T9){
double f1=n15pg_rate(T9);
double f2=n15pa_rate(T9);
return f1/(f1+f2);
}
// o16(p,g)f17 then f17 -> o17(p,a)n14
double o16p_rate(const vec7 &T9){
vec7 a={1.909040e+01,0.000000e+00,-1.669600e+01,-1.162520e+00,2.677030e-01,-3.384110e-02,-6.666670e-01};
return rate_fit(T9,a);
}
// o16(a,g)ne20
double o16a_rate(const vec7 &T9){
vec7 a1={2.390300e+01,0.000000e+00,-3.972620e+01,-2.107990e-01,4.428790e-01,-7.977530e-02,-6.666670e-01};
vec7 a2={3.885710e+00,-1.035850e+01,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a3={9.508480e+00,-1.276430e+01,0.000000e+00,-3.659250e+00,7.142240e-01,-1.075080e-03,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3);
}
// ne20(a,g)mg24
double ne20a_rate(const vec7 &T9){
vec7 a1={2.450580e+01,0.000000e+00,-4.625250e+01,5.589010e+00,7.618430e+00,-3.683000e+00,-6.666670e-01};
vec7 a2={-3.870550e+01,-2.506050e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a3={1.983070e+00,-9.220260e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,-1.500000e+00};
vec7 a4={-8.798270e+00,-1.278090e+01,0.000000e+00,1.692290e+01,-2.573250e+00,2.089970e-01,-1.500000e+00};
return rate_fit(T9,a1) + rate_fit(T9,a2) + rate_fit(T9,a3) + rate_fit(T9,a4);
}
// c12(c12,a)ne20
double c12c12_rate(const vec7 &T9){
vec7 a={6.128630e+01,0.000000e+00,-8.416500e+01,-1.566270e+00,-7.360840e-02,-7.279700e-02,-6.666670e-01};
return rate_fit(T9,a);
}
// c12(o16,a)mg24
double c12o16_rate(const vec7 &T9){
vec7 a={4.853410e+01,3.720400e-01,-1.334130e+02,5.015720e+01,-3.159870e+00,1.782510e-02,-2.370270e+01};
return rate_fit(T9,a);
}
// for Boost ODE solvers either a struct or a class is required
// a Jacobian matrix for implicit solvers
void Jacobian::operator() ( const vector_type &y, matrix_type &J, double /* t */, vector_type &dfdt ) {
Constants& constants = Constants::getInstance();
const double avo = constants.get("N_a").value;
const double clight = constants.get("c").value;
// EOS
vec7 T9=get_T9_array(y[Net::itemp]);
// evaluate rates once per call
double rpp=pp_rate(T9);
double r33=he3he3_rate(T9);
double r34=he3he4_rate(T9);
double r3a=triple_alpha_rate(T9);
double rc12p=c12p_rate(T9);
double rc12a=c12a_rate(T9);
double rn14p=n14p_rate(T9);
double rn14a=n14a_rate(T9);
double ro16p=o16p_rate(T9);
double ro16a=o16a_rate(T9);
double rne20a=ne20a_rate(T9);
double r1212=c12c12_rate(T9);
double r1216=c12o16_rate(T9);
double pfrac=n15pg_frac(T9);
double afrac=1-pfrac;
double yh1 = y[Net::ih1];
double yhe3 = y[Net::ihe3];
double yhe4 = y[Net::ihe4];
double yc12 = y[Net::ic12];
double yn14 = y[Net::in14];
double yo16 = y[Net::io16];
double yne20 = y[Net::ine20];
// zero all elements to begin
for (int i=0; i < Net::nvar; i++) {
for (int j=0; j < Net::nvar; j++) {
J(i,j)=0.0;
}
}
// h1 jacobian elements
J(Net::ih1,Net::ih1) = -3*yh1*rpp - 2*yc12*rc12p -2*yn14*rn14p -2*yo16*ro16p;
J(Net::ih1,Net::ihe3) = 2*yhe3*r33 - yhe4*r34;
J(Net::ih1,Net::ihe4) = -yhe3*r34;
J(Net::ih1,Net::ic12) = -2*yh1*rc12p;
J(Net::ih1,Net::in14) = -2*yh1*rn14p;
J(Net::ih1,Net::io16) = -2*yh1*ro16p;
// he3 jacobian elements
J(Net::ihe3,Net::ih1) = yh1*rpp;
J(Net::ihe3,Net::ihe3) = -2*yhe3*r33 - yhe4*r34;
J(Net::ihe3,Net::ihe4) = -yhe3*r34;
// he4 jacobian elements
J(Net::ihe4,Net::ih1) = yn14*afrac*rn14p + yo16*ro16p;
J(Net::ihe4,Net::ihe3) = yhe3*r33 - yhe4*r34;
J(Net::ihe4,Net::ihe4) = yhe3*r34 - 1.5*yhe4*yhe4*r3a - yc12*rc12a - 1.5*yn14*rn14a - yo16*ro16a - yne20*rne20a;
J(Net::ihe4,Net::ic12) = -yhe4*rc12a + yc12*r1212 + yo16*r1216;
J(Net::ihe4,Net::in14) = yh1*afrac*rn14p - 1.5*yhe4*rn14a;
J(Net::ihe4,Net::io16) = yh1*ro16p - yhe4*ro16a + yc12*r1216;
J(Net::ihe4,Net::ine20) = -yhe4*rne20a;
// c12 jacobian elements
J(Net::ic12,Net::ih1) = -yc12*rc12p + yn14*afrac*rn14p;
J(Net::ic12,Net::ihe4) = 0.5*yhe4*yhe4*r3a - yhe4*rc12a;
J(Net::ic12,Net::ic12) = -yh1*rc12p - yhe4*rc12a - yo16*r1216 - 2*yc12*r1212;
J(Net::ic12,Net::in14) = yh1*yn14*afrac*rn14p;
J(Net::ic12,Net::io16) = -yc12*r1216;
// n14 jacobian elements
J(Net::in14,Net::ih1) = yc12*rc12p - yn14*rn14p + yo16*ro16p;
J(Net::in14,Net::ihe4) = -yn14*rn14a;
J(Net::in14,Net::ic12) = yh1*rc12p;
J(Net::in14,Net::in14) = -yh1*rn14p - yhe4*rn14a;
J(Net::in14,Net::io16) = yo16*ro16p;
// o16 jacobian elements
J(Net::io16,Net::ih1) = yn14*pfrac*rn14p - yo16*ro16p;
J(Net::io16,Net::ihe4) = yc12*rc12a - yo16*ro16a;
J(Net::io16,Net::ic12) = yhe4*rc12a - yo16*r1216;
J(Net::io16,Net::in14) = yh1*pfrac*rn14p;
J(Net::io16,Net::io16) = yh1*ro16p - yc12*r1216 -yhe4*ro16a;
// ne20 jacobian elements
J(Net::ine20,Net::ihe4) = yn14*rn14a + yo16*ro16a - yne20*rne20a;
J(Net::ine20,Net::ic12) = yc12*r1212;
J(Net::ine20,Net::in14) = yhe4*rn14a;
J(Net::ine20,Net::io16) = yo16*ro16a;
J(Net::ine20,Net::ine20) = -yhe4*rne20a;
// mg24 jacobian elements
J(Net::img24,Net::ihe4) = yne20*rne20a;
J(Net::img24,Net::ic12) = yo16*r1216;
J(Net::img24,Net::io16) = yc12*r1216;
J(Net::img24,Net::ine20) = yhe4*rne20a;
// energy accountings
for (int j=0; j<Net::niso; j++) {
for (int i=0; i<Net::niso; i++) {
J(Net::iener,j) += J(i,j)*Net::mion[i];
}
J(Net::iener,j) *= -avo*clight*clight;
}
}
void ODE::operator() ( const vector_type &y, vector_type &dydt, double /* t */) {
Constants& constants = Constants::getInstance();
const double avo = constants.get("N_a").value;
const double clight = constants.get("c").value;
// EOS
double T=y[Net::itemp];
double den=y[Net::iden];
vec7 T9=get_T9_array(T);
// rates
double rpp=den*pp_rate(T9);
double r33=den*he3he3_rate(T9);
double r34=den*he3he4_rate(T9);
double r3a=den*den*triple_alpha_rate(T9);
double rc12p=den*c12p_rate(T9);
double rc12a=den*c12a_rate(T9);
double rn14p=den*n14p_rate(T9);
double rn14a=n14a_rate(T9);
double ro16p=den*o16p_rate(T9);
double ro16a=den*o16a_rate(T9);
double rne20a=den*ne20a_rate(T9);
double r1212=den*c12c12_rate(T9);
double r1216=den*c12o16_rate(T9);
double pfrac=n15pg_frac(T9);
double afrac=1-pfrac;
double yh1 = y[Net:: ih1];
double yhe3 = y[Net:: ihe3];
double yhe4 = y[Net:: ihe4];
double yc12 = y[Net:: ic12];
double yn14 = y[Net:: in14];
double yo16 = y[Net:: io16];
double yne20 = y[Net::ine20];
dydt[Net::ih1] = -1.5*yh1*yh1*rpp;
dydt[Net::ih1] += yhe3*yhe3*r33;
dydt[Net::ih1] += -yhe3*yhe4*r34;
dydt[Net::ih1] += -2*yh1*yc12*rc12p;
dydt[Net::ih1] += -2*yh1*yn14*rn14p;
dydt[Net::ih1] += -2*yh1*yo16*ro16p;
dydt[Net::ihe3] = 0.5*yh1*yh1*rpp;
dydt[Net::ihe3] += -yhe3*yhe3*r33;
dydt[Net::ihe3] += -yhe3*yhe4*r34;
dydt[Net::ihe4] = 0.5*yhe3*yhe3*r33;
dydt[Net::ihe4] += yhe3*yhe4*r34;
dydt[Net::ihe4] += -yhe4*yc12*rc12a;
dydt[Net::ihe4] += yh1*yn14*afrac*rn14p;
dydt[Net::ihe4] += yh1*yo16*ro16p;
dydt[Net::ihe4] += -0.5*yhe4*yhe4*yhe4*r3a;
dydt[Net::ihe4] += -yhe4*yo16*ro16a;
dydt[Net::ihe4] += 0.5*yc12*yc12*r1212;
dydt[Net::ihe4] += yc12*yo16*r1216;
dydt[Net::ihe4] += -yhe4*yne20*rne20a;
dydt[Net::ic12] = (1./6.)*yhe4*yhe4*yhe4*r3a;
dydt[Net::ic12] += -yhe4*yc12*rc12a;
dydt[Net::ic12] += -yh1*yc12*rc12p;
dydt[Net::ic12] += yh1*yn14*afrac*rn14p;
dydt[Net::ic12] += -yc12*yc12*r1212;
dydt[Net::ic12] += -yc12*yo16*r1216;
dydt[Net::in14] = yh1*yc12*rc12p;
dydt[Net::in14] += -yh1*yn14*rn14p;
dydt[Net::in14] += yh1*yo16*ro16p;
dydt[Net::in14] += -yhe4*yn14*rn14a;
dydt[Net::io16] = yhe4*yc12*rc12a;
dydt[Net::io16] += yh1*yn14*pfrac*rn14p;
dydt[Net::io16] += -yh1*yo16*ro16p;
dydt[Net::io16] += -yc12*yo16*r1216;
dydt[Net::io16] += -yhe4*yo16*ro16a;
dydt[Net::ine20] = 0.5*yc12*yc12*r1212;
dydt[Net::ine20] += yhe4*yn14*rn14a;
dydt[Net::ine20] += yhe4*yo16*ro16a;
dydt[Net::ine20] += -yhe4*yne20*rne20a;
dydt[Net::img24] = yc12*yo16*r1216;
dydt[Net::img24] += yhe4*yne20*rne20a;
dydt[Net::itemp] = 0.;
dydt[Net::iden] = 0.;
// energy accounting
double enuc = 0.;
for (int i=0; i<Net::niso; i++) {
enuc += Net::mion[i]*dydt[i];
}
dydt[Net::iener] = -enuc*avo*clight*clight;
}
nuclearNetwork::NetOut Approx8Network::evaluate(const nuclearNetwork::NetIn &netIn) {
m_y = convert_netIn(netIn);
m_tmax = netIn.tmax;
m_dt0 = netIn.dt0;
const double stiff_abs_tol = m_config.get<double>("Network:Approx8:Stiff:AbsTol", 1.0e-6);
const double stiff_rel_tol = m_config.get<double>("Network:Approx8:Stiff:RelTol", 1.0e-6);
const double nonstiff_abs_tol = m_config.get<double>("Network:Approx8:NonStiff:AbsTol", 1.0e-6);
const double nonstiff_rel_tol = m_config.get<double>("Network:Approx8:NonStiff:RelTol", 1.0e-6);
int num_steps = -1;
if (m_stiff) {
LOG_DEBUG(m_logger, "Using stiff solver for Approx8Network");
num_steps = integrate_const(
make_dense_output<rosenbrock4<double>>(stiff_abs_tol, stiff_rel_tol),
std::make_pair(ODE(), Jacobian()),
m_y,
0.0,
m_tmax,
m_dt0
);
} else {
LOG_DEBUG(m_logger, "Using non stiff solver for Approx8Network");
num_steps = integrate_const (
make_dense_output<runge_kutta_dopri5<vector_type>>(nonstiff_abs_tol, nonstiff_rel_tol),
ODE(),
m_y,
0.0,
m_tmax,
m_dt0
);
}
double ysum = 0.0;
for (int i = 0; i < Net::niso; i++) {
m_y[i] *= Net::aion[i];
ysum += m_y[i];
}
for (int i = 0; i < Net::niso; i++) {
m_y[i] /= ysum;
}
nuclearNetwork::NetOut netOut;
std::vector<double> outComposition;
outComposition.reserve(Net::nvar);
for (int i = 0; i < Net::niso; i++) {
outComposition.push_back(m_y[i]);
}
netOut.energy = m_y[Net::iener];
netOut.composition = outComposition;
netOut.num_steps = num_steps;
return netOut;
}
void Approx8Network::setStiff(bool stiff) {
m_stiff = stiff;
}
vector_type Approx8Network::convert_netIn(const nuclearNetwork::NetIn &netIn) {
if (netIn.composition.size() != Net::niso) {
LOG_ERROR(m_logger, "Error: composition size mismatch in convert_netIn");
throw std::runtime_error("Error: composition size mismatch in convert_netIn");
}
vector_type y(Net::nvar, 0.0);
y[Net::ih1] = netIn.composition[0];
y[Net::ihe3] = netIn.composition[1];
y[Net::ihe4] = netIn.composition[2];
y[Net::ic12] = netIn.composition[3];
y[Net::in14] = netIn.composition[4];
y[Net::io16] = netIn.composition[5];
y[Net::ine20] = netIn.composition[6];
y[Net::img24] = netIn.composition[7];
y[Net::itemp] = netIn.temperature;
y[Net::iden] = netIn.density;
y[Net::iener] = netIn.energy;
double ysum = 0.0;
for (int i = 0; i < Net::niso; i++) {
y[i] /= Net::aion[i];
ysum += y[i];
}
for (int i = 0; i < Net::niso; i++) {
y[i] /= ysum;
}
return y;
}
};
// main program

View File

@@ -0,0 +1,16 @@
#include "network.h"
#include "probe.h"
#include "quill/LogMacros.h"
namespace nuclearNetwork {
Network::Network() :
m_config(Config::getInstance()),
m_logManager(Probe::LogManager::getInstance()),
m_logger(m_logManager.getLogger("log")) {
}
nuclearNetwork::NetOut nuclearNetwork::Network::evaluate(const NetIn &netIn) {
// You can throw an exception here or log a warning if it should never be used.
LOG_ERROR(m_logger, "nuclearNetwork::Network::evaluate() is not implemented");
throw std::runtime_error("nuclearNetwork::Network::evaluate() is not implemented");
}
}

View File

@@ -0,0 +1,314 @@
#ifndef APPROX8_H
#define APPROX8_H
#include <array>
#include <boost/numeric/odeint.hpp>
#include "network.h"
/**
* @file approx8.h
* @brief Header file for the Approx8 nuclear reaction network.
*
* This file contains the definitions and declarations for the Approx8 nuclear reaction network.
* The network is based on Frank Timmes' "aprox8" and includes 8 isotopes and various nuclear reactions.
* The rates are evaluated using a fitting function with coefficients from reaclib.jinaweb.org.
*/
/**
* @typedef vector_type
* @brief Alias for a vector of doubles using Boost uBLAS.
*/
typedef boost::numeric::ublas::vector< double > vector_type;
/**
* @typedef matrix_type
* @brief Alias for a matrix of doubles using Boost uBLAS.
*/
typedef boost::numeric::ublas::matrix< double > matrix_type;
/**
* @typedef vec7
* @brief Alias for a std::array of 7 doubles.
*/
typedef std::array<double,7> vec7;
namespace nnApprox8{
using namespace boost::numeric::odeint;
/**
* @struct Net
* @brief Contains constants and arrays related to the nuclear network.
*/
struct Net{
const static int ih1=0;
const static int ihe3=1;
const static int ihe4=2;
const static int ic12=3;
const static int in14=4;
const static int io16=5;
const static int ine20=6;
const static int img24=7;
const static int itemp=img24+1;
const static int iden =itemp+1;
const static int iener=iden+1;
const static int niso=img24+1; // number of isotopes
const static int nvar=iener+1; // number of variables
static constexpr std::array<int,niso> aion = {
1,
3,
4,
12,
14,
16,
20,
24
};
static constexpr std::array<double,niso> mion = {
1.67262164e-24,
5.00641157e-24,
6.64465545e-24,
1.99209977e-23,
2.32462686e-23,
2.65528858e-23,
3.31891077e-23,
3.98171594e-23
};
};
/**
* @brief Multiplies two arrays and sums the resulting elements.
* @param a First array.
* @param b Second array.
* @return Sum of the product of the arrays.
* @example
* @code
* vec7 a = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0};
* vec7 b = {0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
* double result = sum_product(a, b);
* @endcode
*/
double sum_product( const vec7 &a, const vec7 &b);
/**
* @brief Returns an array of T9 terms for the nuclear reaction rate fit.
* @param T Temperature in GigaKelvin.
* @return Array of T9 terms.
* @example
* @code
* double T = 1.5;
* vec7 T9_array = get_T9_array(T);
* @endcode
*/
vec7 get_T9_array(const double &T);
/**
* @brief Evaluates the nuclear reaction rate given the T9 array and coefficients.
* @param T9 Array of T9 terms.
* @param coef Array of coefficients.
* @return Evaluated rate.
* @example
* @code
* vec7 T9 = get_T9_array(1.5);
* vec7 coef = {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001};
* double rate = rate_fit(T9, coef);
* @endcode
*/
double rate_fit(const vec7 &T9, const vec7 &coef);
/**
* @brief Calculates the rate for the reaction p + p -> d.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double pp_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction p + d -> he3.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double dp_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction he3 + he3 -> he4 + 2p.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double he3he3_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction he3(he3,2p)he4.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double he3he4_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction he4 + he4 + he4 -> c12.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double triple_alpha_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction c12 + p -> n13.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double c12p_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction c12 + he4 -> o16.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double c12a_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction n14(p,g)o15 - o15 + p -> c12 + he4.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double n14p_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction n14(a,g)f18 assumed to go on to ne20.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double n14a_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction n15(p,a)c12 (CNO I).
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double n15pa_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction n15(p,g)o16 (CNO II).
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double n15pg_rate(const vec7 &T9);
/**
* @brief Calculates the fraction for the reaction n15(p,g)o16.
* @param T9 Array of T9 terms.
* @return Fraction of the reaction.
*/
double n15pg_frac(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction o16(p,g)f17 then f17 -> o17(p,a)n14.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double o16p_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction o16(a,g)ne20.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double o16a_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction ne20(a,g)mg24.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double ne20a_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction c12(c12,a)ne20.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double c12c12_rate(const vec7 &T9);
/**
* @brief Calculates the rate for the reaction c12(o16,a)mg24.
* @param T9 Array of T9 terms.
* @return Rate of the reaction.
*/
double c12o16_rate(const vec7 &T9);
/**
* @struct Jacobian
* @brief Functor to calculate the Jacobian matrix for implicit solvers.
*/
struct Jacobian {
/**
* @brief Calculates the Jacobian matrix.
* @param y State vector.
* @param J Jacobian matrix.
* @param t Time.
* @param dfdt Derivative of the state vector.
*/
void operator() ( const vector_type &y, matrix_type &J, double /* t */, vector_type &dfdt );
};
/**
* @struct ODE
* @brief Functor to calculate the derivatives for the ODE solver.
*/
struct ODE {
/**
* @brief Calculates the derivatives of the state vector.
* @param y State vector.
* @param dydt Derivative of the state vector.
* @param t Time.
*/
void operator() ( const vector_type &y, vector_type &dydt, double /* t */);
};
/**
* @class Approx8Network
* @brief Class for the Approx8 nuclear reaction network.
*/
class Approx8Network : public nuclearNetwork::Network {
public:
/**
* @brief Evaluates the nuclear network.
* @param netIn Input parameters for the network.
* @return Output results from the network.
*/
virtual nuclearNetwork::NetOut evaluate(const nuclearNetwork::NetIn &netIn);
/**
* @brief Sets whether the solver should use a stiff method.
* @param stiff Boolean indicating if a stiff method should be used.
*/
void setStiff(bool stiff);
/**
* @brief Checks if the solver is using a stiff method.
* @return Boolean indicating if a stiff method is being used.
*/
bool isStiff() { return m_stiff; }
private:
vector_type m_y;
double m_tmax;
double m_dt0;
bool m_stiff = false;
/**
* @brief Converts the input parameters to the internal state vector.
* @param netIn Input parameters for the network.
* @return Internal state vector.
*/
vector_type convert_netIn(const nuclearNetwork::NetIn &netIn);
};
} // namespace nnApprox8
#endif

View File

@@ -0,0 +1,93 @@
#ifndef NETWORK_H
#define NETWORK_H
#include <vector>
#include "probe.h"
#include "config.h"
#include "quill/Logger.h"
namespace nuclearNetwork {
/**
* @struct NetIn
* @brief Input structure for the network evaluation.
*
* This structure holds the input parameters required for the network evaluation.
*
* Example usage:
* @code
* nuclearNetwork::NetIn netIn;
* netIn.composition = {1.0, 0.0, 0.0};
* netIn.tmax = 1.0e6;
* netIn.dt0 = 1.0e-3;
* netIn.temperature = 1.0e8;
* netIn.density = 1.0e5;
* netIn.energy = 1.0e12;
* @endcode
*/
struct NetIn {
std::vector<double> composition; ///< Composition of the network
double tmax; ///< Maximum time
double dt0; ///< Initial time step
double temperature; ///< Temperature in Kelvin
double density; ///< Density in g/cm^3
double energy; ///< Energy in ergs
};
/**
* @struct NetOut
* @brief Output structure for the network evaluation.
*
* This structure holds the output results from the network evaluation.
*
* Example usage:
* @code
* nuclearNetwork::NetOut netOut = network.evaluate(netIn);
* std::vector<double> composition = netOut.composition;
* int steps = netOut.num_steps;
* double energy = netOut.energy;
* @endcode
*/
struct NetOut {
std::vector<double> composition; ///< Composition of the network after evaluation
int num_steps; ///< Number of steps taken in the evaluation
double energy; ///< Energy in ergs after evaluation
};
/**
* @class Network
* @brief Class for network evaluation.
*
* This class provides methods to evaluate the network based on the input parameters.
*
* Example usage:
* @code
* nuclearNetwork::Network network;
* nuclearNetwork::NetIn netIn;
* // Set netIn parameters...
* nuclearNetwork::NetOut netOut = network.evaluate(netIn);
* @endcode
*/
class Network {
public:
Network();
virtual ~Network() = default;
/**
* @brief Evaluate the network based on the input parameters.
*
* @param netIn Input parameters for the network evaluation.
* @return NetOut Output results from the network evaluation.
*/
virtual NetOut evaluate(const NetIn &netIn);
protected:
Config& m_config; ///< Configuration instance
Probe::LogManager& m_logManager; ///< Log manager instance
quill::Logger* m_logger; ///< Logger instance
};
} // namespace nuclearNetwork
#endif // NETWORK_H

View File

@@ -1,20 +0,0 @@
# Define the library
opatIO_sources = files(
'private/opatIO.cpp',
)
opatIO_headers = files(
'public/opatIO.h'
)
# Define the libopatIO library so it can be linked against by other parts of the build system
libopatIO = library('opatIO',
opatIO_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
dependencies: [picosha2_dep],
install : true,
)
# Make headers accessible
install_headers(opatIO_headers, subdir : '4DSSE/opatIO')

View File

@@ -1,520 +0,0 @@
/* ***********************************************************************
//
// Copyright (C) 2025 -- The 4D-STAR Collaboration
// File Author: Emily Boudreaux
// Last Modified: March 07, 2025
//
// 4DSSE is free software; you can use it and/or modify
// it under the terms and restrictions the GNU General Library Public
// License version 3 (GPLv3) as published by the Free Software Foundation.
//
// 4DSSE 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 Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with this software; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// *********************************************************************** */
#include "opatIO.h"
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <map>
#include <utility>
#include <cmath>
#include <limits>
#include <deque>
#include <cstdint>
#include "picosha2.h"
// Function to check system endianness
bool is_big_endian() {
uint16_t test = 0x1;
return reinterpret_cast<uint8_t*>(&test)[0] == 0;
}
// Generic function to swap bytes for any type
template <typename T>
T swap_bytes(T value) {
static_assert(std::is_trivially_copyable<T>::value, "swap_bytes only supports trivial types.");
T result;
uint8_t* src = reinterpret_cast<uint8_t*>(&value);
uint8_t* dest = reinterpret_cast<uint8_t*>(&result);
for (size_t i = 0; i < sizeof(T); i++) {
dest[i] = src[sizeof(T) - 1 - i];
}
return result;
}
// Constructor
OpatIO::OpatIO() {}
OpatIO::OpatIO(std::string filename) : filename(filename) {
load();
}
// Destructor
OpatIO::~OpatIO() {
unload();
}
// Load the OPAT file
void OpatIO::load() {
if (loaded) return;
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Could not open file: " + filename);
}
readHeader(file);
readTableIndex(file);
loaded = true;
file.close();
}
// // Unload the OPAT file
void OpatIO::unload() {
if (!loaded) return;
tableIndex.clear();
while (!tableQueue.empty()) {
tableQueue.pop_front();
}
loaded = false;
}
// Read the header from the file
void OpatIO::readHeader(std::ifstream &file) {
file.read(reinterpret_cast<char*>(&header), sizeof(Header));
if (file.gcount() != sizeof(Header)) {
throw std::runtime_error("Error reading header from file");
}
if (is_big_endian()) {
header.version = swap_bytes(header.version);
header.numTables = swap_bytes(header.numTables);
header.indexOffset = swap_bytes(header.indexOffset);
header.numIndex = swap_bytes(header.numIndex);
}
}
// Read the table index from the file
void OpatIO::readTableIndex(std::ifstream &file) {
file.seekg(header.indexOffset, std::ios::beg);
tableIndex.resize(header.numTables);
long unsigned int indexReadBytes;
for (uint32_t i = 0; i < header.numTables; i++) {
indexReadBytes = 0;
// Read the index vector in based on numIndex
tableIndex.at(i).index.resize(header.numIndex);
file.read(reinterpret_cast<char*>(tableIndex.at(i).index.data()), header.numIndex * sizeof(double));
indexReadBytes += static_cast<int>(file.gcount());
// Read the start and end position of the table in
file.read(reinterpret_cast<char*>(&tableIndex.at(i).byteStart), sizeof(uint64_t));
indexReadBytes += static_cast<int>(file.gcount());
file.read(reinterpret_cast<char*>(&tableIndex.at(i).byteEnd), sizeof(uint64_t));
indexReadBytes += static_cast<int>(file.gcount());
// Read the checksum in
file.read(tableIndex.at(i).sha256, 32);
indexReadBytes += static_cast<int>(file.gcount());
// validate that the size of read data is correct
if (indexReadBytes != header.numIndex * sizeof(double) + 32 + 2 * sizeof(uint64_t)) {
throw std::runtime_error("Error reading table index from file");
}
}
buildTableIDToIndex();
}
void OpatIO::buildTableIDToIndex(){
tableIDToIndex.clear();
int tableID = 0;
std::vector<double> ind;
ind.resize(header.numIndex);
for (const auto &table : tableIndex) {
ind.clear();
for (const auto &index : table.index) {
ind.push_back(index);
}
tableIDToIndex.emplace(tableID, ind);
tableID++;
}
LookupEpsilon();
}
void OpatIO::LookupEpsilon() {
/*
Get 10% of the minimum spacing between index values
in the tableIDToIndex map. This can be used
to set the comparison distance when doing a reverse
lookup (index -> tableID)
*/
indexEpsilon.resize(header.numIndex);
double epsilon;
for (int i = 0; i < static_cast<int>(header.numIndex); i++) {
epsilon = std::numeric_limits<double>::max();
for (int j = 1; j < static_cast<int>(header.numTables); j++) {
epsilon = std::min(epsilon, std::fabs(tableIDToIndex.at(j).at(i) - tableIDToIndex.at(j-1).at(i)));
}
indexEpsilon.at(i) = epsilon * 0.1;
}
}
int OpatIO::lookupTableID(std::vector<double> index) {
std::vector<bool> IndexOkay;
IndexOkay.resize(header.numIndex);
int tableID = 0;
for (const auto &tableMap : tableIDToIndex){
// Loop through all index values and check if they are within epsilon for that index
std::fill(IndexOkay.begin(), IndexOkay.end(), false);
for (long unsigned int i = 0; i < index.size(); i++) {
IndexOkay.at(i) = std::fabs(tableMap.second.at(i) - index.at(i)) < indexEpsilon.at(i);
}
// If all index values are within epsilon, return the table ID
if (std::all_of(IndexOkay.begin(), IndexOkay.end(), [](bool i){return i;})) {
return tableID;
}
tableID++;
}
// If no table is found, return -1 (sentinal value)
return -1;
}
// Get a table from the queue
OPATTable OpatIO::getTableFromQueue(int tableID) {
for (const auto &table : tableQueue) {
if (table.first == tableID) {
return table.second;
}
}
throw std::out_of_range("Table not found!");
}
// Add a table to the queue
void OpatIO::addTableToQueue(int tableID, OPATTable table) {
if (static_cast<int>(tableQueue.size()) >= maxQDepth) {
removeTableFromQueue();
}
std::pair<int, OPATTable> IDTablePair = {tableID, table};
tableQueue.push_back(IDTablePair);
}
// Remove a table from the queue
void OpatIO::removeTableFromQueue() {
if (!tableQueue.empty()) {
tableQueue.pop_front();
}
}
// Flush the queue
void OpatIO::flushQueue() {
while (!tableQueue.empty()) {
tableQueue.pop_back();
tableQueue.pop_front();
}
}
// Get the OPAT version
uint16_t OpatIO::getOPATVersion() {
return header.version;
}
// Get a table for given X and Z
OPATTable OpatIO::getTable(std::vector<double> index) {
int tableID = lookupTableID(index);
if (tableID == -1) {
throw std::out_of_range("Index Not found!");
}
try {
return getTableFromQueue(tableID);
}
catch(const std::out_of_range &e) {
return getTable(tableID);
}
}
OPATTable OpatIO::getTable(int tableID) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Could not open file: " + filename);
}
uint64_t byteStart = tableIndex[tableID].byteStart;
file.seekg(byteStart, std::ios::beg);
OPATTable table;
// Step 1: Read N_R and N_T
file.read(reinterpret_cast<char*>(&table.N_R), sizeof(uint32_t));
file.read(reinterpret_cast<char*>(&table.N_T), sizeof(uint32_t));
// Resize vectors to hold the correct number of elements
table.logR.resize(table.N_R);
table.logT.resize(table.N_T);
table.logKappa.resize(table.N_R, std::vector<double>(table.N_T));
// Step 2: Read logR values
file.read(reinterpret_cast<char*>(table.logR.data()), table.N_R * sizeof(double));
// Step 3: Read logT values
file.read(reinterpret_cast<char*>(table.logT.data()), table.N_T * sizeof(double));
// Step 4: Read logKappa values (flattened row-major order)
for (size_t i = 0; i < table.N_R; ++i) {
file.read(reinterpret_cast<char*>(table.logKappa[i].data()), table.N_T * sizeof(double));
}
if (!file) {
throw std::runtime_error("Error reading table from file: " + filename);
}
addTableToQueue(tableID, table);
file.close();
return table;
}
// Set the maximum queue depth
void OpatIO::setMaxQDepth(int depth) {
maxQDepth = depth;
}
int OpatIO::getMaxQDepth() {
return maxQDepth;
}
// Set the filename
void OpatIO::setFilename(std::string filename) {
if (loaded) {
throw std::runtime_error("Cannot set filename while file is loaded");
}
this->filename = filename;
}
// Check if the file is loaded
bool OpatIO::isLoaded() {
return loaded;
}
// Print the header
void OpatIO::printHeader() {
std::cout << "Version: " << header.version << std::endl;
std::cout << "Number of Tables: " << header.numTables << std::endl;
std::cout << "Header Size: " << header.headerSize << std::endl;
std::cout << "Index Offset: " << header.indexOffset << std::endl;
std::cout << "Creation Date: " << header.creationDate << std::endl;
std::cout << "Source Info: " << header.sourceInfo << std::endl;
std::cout << "Comment: " << header.comment << std::endl;
std::cout << "Number of Indices: " << header.numIndex << std::endl;
}
// Print the table index
void OpatIO::printTableIndex() {
if (tableIndex.empty()) {
std::cout << "No table indexes found." << std::endl;
return;
}
// Print table header
std::cout << std::left << std::setw(10);
for (int i = 0; i < header.numIndex; i++) {
std::cout << "Index " << i << std::setw(10);
}
std::cout << std::setw(15) << "Byte Start"
<< std::setw(15) << "Byte End"
<< "Checksum (SHA-256)" << std::endl;
std::cout << std::string(80, '=') << std::endl; // Separator line
// Print each entry in the table
for (const auto &index : tableIndex) {
std::cout << std::fixed << std::setprecision(4) << std::setw(10);
for (int i = 0; i < header.numIndex; i++) {
std::cout << index.index[i] << std::setw(10);
}
std::cout << std::setw(5) << index.byteStart
<< std::setw(15) << index.byteEnd
<< std::hex; // Switch to hex mode for checksum
for (int i = 0; i < 8; ++i) { // Print first 8 bytes of SHA-256 for brevity
std::cout << std::setw(2) << std::setfill('0') << (int)index.sha256[i];
}
std::cout << "..." << std::dec << std::setfill(' ') << std::endl; // Reset formatting
}
}
void OpatIO::printTable(OPATTable table, uint32_t truncateDigits) {
int printTo;
bool truncate = false;
if (table.N_R > truncateDigits) {
printTo = truncateDigits;
truncate = true;
} else {
printTo = table.N_R-1;
}
std::cout << "LogR (size: " << table.logR.size() << "): [";
for (int i = 0; i < printTo; ++i) {
std::cout << table.logR.at(i) << ", ";
}
if (truncate) {
std::cout << "..., ";
for (int i = truncateDigits; i > 1; --i) {
std::cout << table.logR.at(table.logR.size() - i) << ", ";
}
}
std::cout << table.logR.back() << "]" << std::endl;
if (table.N_T > truncateDigits) {
printTo = truncateDigits;
truncate = true;
} else {
printTo = table.N_T-1;
}
std::cout << "LogT (size: " << table.logT.size() << "): [";
for (int i = 0; i < printTo; ++i) {
std::cout << table.logT.at(i) << ", ";
}
if (truncate) {
std::cout << "..., ";
for (int i = truncateDigits; i > 1; --i) {
std::cout << table.logT.at(table.logT.size() - i) << ", ";
}
}
std::cout << table.logT.back() << "]" << std::endl;
bool truncateRow = false;
bool truncateCol = false;
int printToRow, printToCol;
if (table.N_T > truncateDigits) {
printToRow = truncateDigits;
truncateRow = true;
} else {
printToRow = table.N_T-1;
}
if (table.N_R > truncateDigits) {
printToCol = truncateDigits;
truncateCol = true;
} else {
printToCol = table.N_R-1;
}
std::cout << "LogKappa (size: " << table.N_R << " x " << table.N_T << "): \n[";
for (int rowIndex = 0; rowIndex < printToRow; rowIndex++) {
std::cout << "[";
for (int colIndex = 0; colIndex < printToCol; colIndex++) {
std::cout << table.logKappa.at(rowIndex).at(colIndex) << ", ";
}
if (truncateRow) {
std::cout << "..., ";
for (int i = truncateDigits; i > 1; i--) {
std::cout << table.logKappa.at(rowIndex).at(table.logKappa.at(rowIndex).size() - i) << ", ";
}
}
std::cout << table.logKappa.at(rowIndex).back() << "],\n";
}
if (truncateCol) {
std::cout << ".\n.\n.\n";
for (int rowIndex = truncateDigits; rowIndex > 1; rowIndex--) {
std::cout << "[";
for (int colIndex = 0; colIndex < printToCol; colIndex++) {
std::cout << table.logKappa.at(rowIndex).at(colIndex) << ", ";
}
if (truncateRow) {
std::cout << "..., ";
for (int i = truncateDigits; i > 1; i--) {
std::cout << table.logKappa.at(rowIndex).at(table.logKappa.at(rowIndex).size() - i) << ", ";
}
}
std::cout << table.logKappa.at(rowIndex).back() << "],\n";
}
std::cout << "[";
for (int colIndex = 0; colIndex < printToCol; colIndex++) {
std::cout << table.logKappa.back().at(colIndex) << ", ";
}
if (truncateRow) {
std::cout << "..., ";
for (int i = truncateDigits; i > 1; i--) {
std::cout << table.logKappa.back().at(table.logKappa.back().size() - i) << ", ";
}
}
std::cout << table.logKappa.back().back() << "]";
}
std::cout << "]" << std::endl;
}
void OpatIO::printTable(std::vector<double> index, uint32_t truncateDigits) {
int tableID = lookupTableID(index);
OPATTable table = getTable(tableID);
printTable(table, truncateDigits);
}
// Get the table index
std::vector<TableIndex> OpatIO::getTableIndex() {
return tableIndex;
}
// Get the header
Header OpatIO::getHeader() {
return header;
}
// Get the size of the index vector used
uint16_t OpatIO::getNumIndex() {
return header.numIndex;
}
TableIndex OpatIO::getTableIndex(std::vector<double> index) {
int tableID = lookupTableID(index);
return tableIndex.at(tableID);
}
std::vector<unsigned char> OpatIO::computeChecksum(int tableID) {
OPATTable table = getTable(tableID);
std::vector<std::vector<double>> logKappa = table.logKappa;
std::vector<double> flatData(logKappa.size() * logKappa.size());
size_t offset = 0;
for (const auto& row : logKappa) {
for (const auto& val : row) {
flatData[offset++] = val;
}
}
std::vector<unsigned char> flatDataBytes(flatData.size() * sizeof(double));
std::memcpy(flatDataBytes.data(), flatData.data(), flatDataBytes.size());
std::vector<unsigned char> hash(picosha2::k_digest_size);
picosha2::hash256(flatDataBytes.begin(), flatDataBytes.end(), hash.begin(), hash.end());
return hash;
}
std::vector<unsigned char> OpatIO::computeChecksum(std::vector<double> index) {
int tableID = lookupTableID(index);
return computeChecksum(tableID);
}
bool OpatIO::validateAll() {
for (const auto &table : tableIDToIndex) {
std::vector<unsigned char> hash = computeChecksum(table.first);
std::vector<unsigned char> storedHash(tableIndex.at(table.first).sha256, tableIndex.at(table.first).sha256 + 32);
if (hash != storedHash) {
return false;
}
}
return true;
}

View File

@@ -1,290 +0,0 @@
/* ***********************************************************************
//
// Copyright (C) 2025 -- The 4D-STAR Collaboration
// File Author: Emily Boudreaux
// Last Modified: March 07, 2025
//
// 4DSSE is free software; you can use it and/or modify
// it under the terms and restrictions the GNU General Library Public
// License version 3 (GPLv3) as published by the Free Software Foundation.
//
// 4DSSE 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 Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with this software; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// *********************************************************************** */
#ifndef OPATIO_H
#define OPATIO_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <utility>
#include <cstdint>
/**
* @brief Structure to hold the header information of an OPAT file.
*/
#pragma pack(1)
struct Header {
char magic[4]; ///< Magic number to identify the file type
uint16_t version; ///< Version of the OPAT file format
uint32_t numTables; ///< Number of tables in the file
uint32_t headerSize; ///< Size of the header
uint64_t indexOffset; ///< Offset to the index section
char creationDate[16]; ///< Creation date of the file
char sourceInfo[64]; ///< Source information
char comment[128]; ///< Comment section
uint16_t numIndex; ///< Size of index vector per table
char reserved[24]; ///< Reserved for future use
};
#pragma pack()
/**
* @brief Structure to hold the index information of a table in an OPAT file.
*/
struct TableIndex {
std::vector<double> index; ///< Index vector for associated table
uint64_t byteStart; ///< Byte start position of the table
uint64_t byteEnd; ///< Byte end position of the table
char sha256[32]; ///< SHA-256 hash of the table data
};
/**
* @brief Structure to hold the data of an OPAT table.
*/
struct OPATTable {
uint32_t N_R; ///< Number of R values
uint32_t N_T; ///< Number of T values
std::vector<double> logR; ///< Logarithm of R values
std::vector<double> logT; ///< Logarithm of T values
std::vector<std::vector<double>> logKappa; ///< Logarithm of Kappa values
};
class opatIOTest; // Friend for gtest
/**
* @brief Class to manage the input/output operations for OPAT files.
*/
class OpatIO {
private:
Header header; ///< Header information of the OPAT file
std::vector<TableIndex> tableIndex; ///< Index information of the tables
std::deque<std::pair<int, OPATTable>> tableQueue; ///< Queue to manage table caching
std::map<int, std::vector<double>> tableIDToIndex; ///< Map to store table ID to indexing
std::vector<double> indexEpsilon; ///< Epsilon values for each index
int maxQDepth = 20; ///< Maximum depth of the table queue
std::string filename; ///< Filename of the OPAT file
bool loaded = false; ///< Flag to indicate if the file is loaded
/**
* @brief Read the header from the file.
* @param file The input file stream.
*/
void readHeader(std::ifstream &file);
/**
* @brief Read the table index from the file.
* @param file The input file stream.
*/
void readTableIndex(std::ifstream &file);
/**
* @brief Get a table from the queue.
* @param tableID The ID of the table.
* @return The OPAT table.
*/
OPATTable getTableFromQueue(int tableID);
/**
* @brief Add a table to the queue.
* @param tableID The ID of the table.
* @param table The OPAT table.
*/
void addTableToQueue(int tableID, OPATTable table);
/**
* @brief Remove a table from the queue.
*/
void removeTableFromQueue();
/**
* @brief Flush the table queue.
*/
void flushQueue();
/**
* @brief Get a table by its ID.
* @param tableID The ID of the table.
* @return The OPAT table.
*/
OPATTable getTable(int tableID);
/**
* @brief Print a table.
* @param table The OPAT table.
* @param truncateDigits Number of digits to truncate.
*/
void printTable(OPATTable table, uint32_t truncateDigits=5);
/**
* @brief Lookup epsilon values for Index.
*/
void LookupEpsilon();
/**
* @brief Build the table ID to Index mapping.
*/
void buildTableIDToIndex();
public:
/**
* @brief Default constructor.
*/
OpatIO();
/**
* @brief Constructor with filename.
* @param filename The name of the OPAT file.
*/
OpatIO(std::string filename);
/**
* @brief Destructor.
*/
~OpatIO();
/**
* @brief Get a table by index vector
* @param index The index vector associated with the table to retrieve.
* @throw std::out_of_range if the index is not found.
* @return The OPAT table.
*/
OPATTable getTable(std::vector<double> index);
/**
* @brief Set the maximum depth of the table queue.
* @param depth The maximum depth.
*/
void setMaxQDepth(int depth);
/**
* @brief Get the maximum depth of the table queue.
* @return The maximum depth.
*/
int getMaxQDepth();
/**
* @brief Set the filename of the OPAT file.
* @param filename The name of the file.
*/
void setFilename(std::string filename);
/**
* @brief Load the OPAT file.
*/
void load();
/**
* @brief Unload the OPAT file.
*/
void unload();
/**
* @brief Check if the file is loaded.
* @return True if the file is loaded, false otherwise.
*/
bool isLoaded();
/**
* @brief Print the header information.
*/
void printHeader();
/**
* @brief Print the table index.
*/
void printTableIndex();
/**
* @brief Print a table by X and Z values.
* @param index The index vector associated with the table to print.
* @param truncateDigits Number of digits to truncate.
*/
void printTable(std::vector<double> index, uint32_t truncateDigits=5);
/**
* @brief Get the table index.
* @return A vector of TableIndex structures.
*/
std::vector<TableIndex> getTableIndex();
/**
* @brief Get the header information.
* @return The Header structure.
*/
Header getHeader();
/**
* @brief Lookup the table ID by X and Z values.
* @param index The index vector associated with the table to lookup.
* @return The table ID if index is found, otherwise -1.
*/
int lookupTableID(std::vector<double> index);
/**
* @brief Lookup the closest table ID by X and Z values.
* @param index The index vector associated with the table to lookup.
* @return The closest table ID.
*/
int lookupClosestTableID(std::vector<double> index);
/**
* @brief Get the version of the OPAT file format.
* @return The version of the OPAT file format.
*/
uint16_t getOPATVersion();
/**
* @brief Get size of the index vector per table in the OPAT file.
* @return The size of the index vector per table.
*/
uint16_t getNumIndex();
/**
* @brief Get the index vector for a given table ID.
* @param index The index vector associated with the table to retrieve.
* @return The full TableIndex entry for the table
*/
TableIndex getTableIndex(std::vector<double> index);
/**
* @brief Get the checksum (sha256) for a given table ID.
* @param tableID The ID of the table.
* @return The checksum vector for the table.
*/
std::vector<unsigned char> computeChecksum(int tableID);
/**
* @brief Get the checksum (sha256) for a given index vector.
* @param index The index vector associated with the table to retrieve.
* @return The checksum vector for the table.
*/
std::vector<unsigned char> computeChecksum(std::vector<double> index);
/**
* @brief Validate the checksum of all tables.
* @return True if all checksum are valid, false otherwise.
*/
bool validateAll();
};
#endif

View File

@@ -27,16 +27,23 @@ probe_headers = files(
'public/probe.h'
)
dependencies = [
config_dep,
mfem_dep,
quill_dep
]
# Define the liblogger library so it can be linked against by other parts of the build system
libprobe = static_library('probe',
probe_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
install : true,
dependencies: [config_dep, mfem_dep, quill_dep, macros_dep]
dependencies: dependencies
)
probe_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libprobe,
dependencies: dependencies
)

40
src/resource/meson.build Normal file
View File

@@ -0,0 +1,40 @@
# Define the library
resourceManager_sources = files(
'private/resourceManager.cpp',
'private/resourceManagerTypes.cpp'
)
resourceManager_headers = files(
'public/resourceManager.h',
'public/resourceManagerTypes.h'
)
dependencies = [
yaml_cpp_dep,
opatio_dep,
eos_dep,
quill_dep,
config_dep,
probe_dep,
mfem_dep,
macros_dep,
meshio_dep
]
libResourceHeader_dep = declare_dependency(include_directories: include_directories('public'))
# Define the libresourceManager library so it can be linked against by other parts of the build system
libresourceManager = static_library('resourceManager',
resourceManager_sources,
include_directories: include_directories('public'),
cpp_args: ['-fvisibility=default'],
dependencies: dependencies,
install : true)
resourceManager_dep = declare_dependency(
include_directories: include_directories('public'),
link_with: libresourceManager,
dependencies: dependencies
)
# Make headers accessible
install_headers(resourceManager_headers, subdir : '4DSSE/resource')

View File

@@ -0,0 +1,68 @@
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
#include "quill/LogMacros.h"
#include "resourceManager.h"
#include "resourceManagerTypes.h"
#include "debug.h"
#include "config.h"
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
ResourceManager::ResourceManager() {
std::string defaultDataDir = TOSTRING(DATA_DIR);
m_dataDir = m_config.get<std::string>("Data:Dir", defaultDataDir);
// -- Get the index file path using filesytem to make it a system safe path
std::string indexFilePath = m_dataDir + "/index.yaml";
std::filesystem::path indexFile(indexFilePath);
m_resourceConfig.loadConfig(indexFile.string());
std::vector<std::string> assets = m_resourceConfig.keys();
for (auto key : assets ) {
load(key);
}
}
std::vector<std::string> ResourceManager::getAvaliableResources() {
std::vector<std::string> resources;
resources = m_resourceConfig.keys();
return resources;
}
const Resource& ResourceManager::getResource(const std::string &name) const {
auto it = m_resources.find(name);
if (it != m_resources.end()) {
return it->second;
}
throw std::runtime_error("Resource " + name + " not found");
}
bool ResourceManager::loadResource(std::string& name) {
return load(name);
}
bool ResourceManager::load(const std::string& name) {
const std::string resourcePath = m_dataDir + "/" + m_resourceConfig.get<std::string>(name);
std::filesystem::path resourceFile(resourcePath);
if (!std::filesystem::exists(resourceFile)) {
LOG_ERROR(m_logger, "Resource file not found: {}", resourceFile.string());
return false;
}
LOG_INFO(m_logger, "Loading resource: {}", resourceFile.string());
if (m_resources.find(name) != m_resources.end()) {
LOG_INFO(m_logger, "Resource already loaded: {}", name);
return true;
}
Resource resource = createResource(name, resourcePath);
m_resources[name] = std::move(resource);
// -- Check if the resource is already in the map
return true;
}

View File

@@ -0,0 +1,41 @@
#include <string>
#include "resourceManagerTypes.h"
#include "opatIO.h"
#include "meshIO.h"
#include "eosIO.h"
#include "debug.h"
std::string getFirstSegment(const std::string& input) {
size_t pos = input.find(':');
if (pos == std::string::npos) {
// No colon found, return the entire string
return input;
} else {
// Return substring from start to the position of the first colon
return input.substr(0, pos);
}
}
Resource createResource(const std::string& type, const std::string& path) {
static const std::unordered_map<std::string, std::function<Resource(const std::string&)>> factoryMap = {
{"opac", [](const std::string& p) { return Resource(
std::make_unique<OpatIO>(p));
}},
{"mesh", [](const std::string& p) { return Resource(
std::make_unique<MeshIO>(p));
}},
{"eos", [](const std::string& p) { return Resource(
std::make_unique<EosIO>(p));
}}
// Add more mappings as needed
};
auto it = factoryMap.find(getFirstSegment(type));
if (it != factoryMap.end()) {
return it->second(path);
} else {
throw std::invalid_argument("Unknown resource type: " + type);
}
}

View File

@@ -0,0 +1,115 @@
#ifndef RESOURCE_MANAGER_H
#define RESOURCE_MANAGER_H
#include <vector>
#include <string>
#include <stdexcept>
#include <unordered_map>
#include "resourceManagerTypes.h"
#include "config.h"
#include "probe.h"
#include "quill/LogMacros.h"
/**
* @class ResourceManager
* @brief Manages resources within the application.
*
* The ResourceManager class is responsible for loading, storing, and providing access to resources.
* It follows the Singleton design pattern to ensure only one instance of the manager exists.
*/
class ResourceManager {
private:
/**
* @brief Private constructor to prevent instantiation.
*/
ResourceManager();
/**
* @brief Deleted copy constructor to prevent copying.
*/
ResourceManager(const ResourceManager&) = delete;
/**
* @brief Deleted assignment operator to prevent assignment.
*/
ResourceManager& operator=(const ResourceManager&) = delete;
Config& m_config = Config::getInstance();
Probe::LogManager& m_logManager = Probe::LogManager::getInstance();
quill::Logger* m_logger = m_logManager.getLogger("log");
Config m_resourceConfig;
std::string m_dataDir;
std::unordered_map<std::string, Resource> m_resources;
/**
* @brief Loads a resource by name.
* @param name The name of the resource to load.
* @return True if the resource was loaded successfully, false otherwise.
*/
bool load(const std::string& name);
public:
/**
* @brief Gets the singleton instance of the ResourceManager.
* @return The singleton instance of the ResourceManager.
*/
static ResourceManager& getInstance() {
static ResourceManager instance;
return instance;
}
/**
* @brief Gets a list of available resources.
* @return A vector of strings containing the names of available resources.
*
* Example usage:
* @code
* ResourceManager& manager = ResourceManager::getInstance();
* std::vector<std::string> resources = manager.getAvaliableResources();
* @endcode
*/
std::vector<std::string> getAvaliableResources();
/**
* @brief Gets a resource by name.
* @param name The name of the resource to retrieve.
* @return A constant reference to the requested resource.
* @throws std::runtime_error if the resource is not found.
*
* Example usage:
* @code
* ResourceManager& manager = ResourceManager::getInstance();
* const Resource& resource = manager.getResource("exampleResource");
* @endcode
*/
const Resource& getResource(const std::string &name) const;
/**
* @brief Loads a resource by name.
* @param name The name of the resource to load.
* @return True if the resource was loaded successfully, false otherwise.
*
* Example usage:
* @code
* ResourceManager& manager = ResourceManager::getInstance();
* bool success = manager.loadResource("exampleResource");
* @endcode
*/
bool loadResource(std::string& name);
/**
* @brief Loads all resources.
* @return An unordered map with resource names as keys and load success as values.
*
* Example usage:
* @code
* ResourceManager& manager = ResourceManager::getInstance();
* std::unordered_map<std::string, bool> results = manager.loadAllResources();
* @endcode
*/
std::unordered_map<std::string, bool> loadAllResources();
};
#endif // RESOURCE_MANAGER_H

View File

@@ -0,0 +1,71 @@
#ifndef RESOURCE_MANAGER_TYPES_H
#define RESOURCE_MANAGER_TYPES_H
#include <memory>
#include <variant>
#include "opatIO.h"
#include "helm.h"
#include "meshIO.h"
#include "eosIO.h"
/**
* @file resourceManagerTypes.h
* @brief Defines types and functions for managing resources.
*
* This file provides type definitions and functions for handling different
* types of resources in a unified manner.
*/
// -- Valid resource types
/**
* @brief A variant type that can hold different types of resources.
*
* The Resource type is a std::variant that can hold a unique pointer to
* an OpatIO, MeshIO, or EosIO object.
*
* Example usage:
* @code
* Resource resource = std::make_unique<OpatIO>(...);
* @endcode
*/
using Resource = std::variant<
std::unique_ptr<OpatIO>,
std::unique_ptr<MeshIO>,
std::unique_ptr<EosIO>>;
/**
* @brief Extracts the first segment of a given string.
*
* This function takes a string input and returns the first segment
* separated by a delimiter (default is '/').
*
* @param input The input string to be processed.
* @return The first segment of the input string.
*
* Example usage:
* @code
* std::string segment = getFirstSegment("path/to/resource");
* // segment == "path"
* @endcode
*/
std::string getFirstSegment(const std::string& input);
/**
* @brief Creates a resource based on the specified type and path.
*
* This function creates a resource object based on the provided type
* and initializes it using the given path.
*
* @param type The type of the resource to be created (e.g., "OpatIO", "MeshIO", "EosIO").
* @param path The path to initialize the resource with.
* @return A Resource object initialized with the specified type and path.
*
* Example usage:
* @code
* Resource resource = createResource("OpatIO", "path/to/opat");
* @endcode
*/
Resource createResource(const std::string& type, const std::string& path);
#endif // RESOURCE_MANAGER_TYPES_H

Binary file not shown.

View File

@@ -1,21 +0,0 @@
# MIT License
Copyright (c) 2017 okdshin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,138 +0,0 @@
# PicoSHA2 - a C++ SHA256 hash generator
Copyright &copy; 2017 okdshin
## Introduction
PicoSHA2 is a tiny SHA256 hash generator for C++ with following properties:
- header-file only
- no external dependencies (only uses standard C++ libraries)
- STL-friendly
- licensed under MIT License
## Generating SHA256 hash and hash hex string
```c++
// any STL sequantial container (vector, list, dequeue...)
std::string src_str = "The quick brown fox jumps over the lazy dog";
std::vector<unsigned char> hash(picosha2::k_digest_size);
picosha2::hash256(src_str.begin(), src_str.end(), hash.begin(), hash.end());
std::string hex_str = picosha2::bytes_to_hex_string(hash.begin(), hash.end());
```
## Generating SHA256 hash and hash hex string from byte stream
```c++
picosha2::hash256_one_by_one hasher;
...
hasher.process(block.begin(), block.end());
...
hasher.finish();
std::vector<unsigned char> hash(picosha2::k_digest_size);
hasher.get_hash_bytes(hash.begin(), hash.end());
std::string hex_str = picosha2::get_hash_hex_string(hasher);
```
The file `example/interactive_hasher.cpp` has more detailed information.
## Generating SHA256 hash from a binary file
```c++
std::ifstream f("file.txt", std::ios::binary);
std::vector<unsigned char> s(picosha2::k_digest_size);
picosha2::hash256(f, s.begin(), s.end());
```
This `hash256` may use less memory than reading whole of the file.
## Generating SHA256 hash hex string from std::string
```c++
std::string src_str = "The quick brown fox jumps over the lazy dog";
std::string hash_hex_str;
picosha2::hash256_hex_string(src_str, hash_hex_str);
std::cout << hash_hex_str << std::endl;
//this output is "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
```
```c++
std::string src_str = "The quick brown fox jumps over the lazy dog";
std::string hash_hex_str = picosha2::hash256_hex_string(src_str);
std::cout << hash_hex_str << std::endl;
//this output is "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
```
```c++
std::string src_str = "The quick brown fox jumps over the lazy dog.";//add '.'
std::string hash_hex_str = picosha2::hash256_hex_string(src_str.begin(), src_str.end());
std::cout << hash_hex_str << std::endl;
//this output is "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"
```
## Generating SHA256 hash hex string from byte sequence
```c++
std::vector<unsigned char> src_vect(...);
std::string hash_hex_str;
picosha2::hash256_hex_string(src_vect, hash_hex_str);
```
```c++
std::vector<unsigned char> src_vect(...);
std::string hash_hex_str = picosha2::hash256_hex_string(src_vect);
```
```c++
unsigned char src_c_array[picosha2::k_digest_size] = {...};
std::string hash_hex_str;
picosha2::hash256_hex_string(src_c_array, src_c_array+picosha2::k_digest_size, hash_hex_str);
```
```c++
unsigned char src_c_array[picosha2::k_digest_size] = {...};
std::string hash_hex_str = picosha2::hash256_hex_string(src_c_array, src_c_array+picosha2::k_digest_size);
```
## Generating SHA256 hash byte sequence from STL sequential container
```c++
//any STL sequantial container (vector, list, dequeue...)
std::string src_str = "The quick brown fox jumps over the lazy dog";
//any STL sequantial containers (vector, list, dequeue...)
std::vector<unsigned char> hash(picosha2::k_digest_size);
// in: container, out: container
picosha2::hash256(src_str, hash);
```
```c++
//any STL sequantial container (vector, list, dequeue...)
std::string src_str = "The quick brown fox jumps over the lazy dog";
//any STL sequantial containers (vector, list, dequeue...)
std::vector<unsigned char> hash(picosha2::k_digest_size);
// in: iterator pair, out: contaner
picosha2::hash256(src_str.begin(), src_str.end(), hash);
```
```c++
std::string src_str = "The quick brown fox jumps over the lazy dog";
unsigned char hash_byte_c_array[picosha2::k_digest_size];
// in: container, out: iterator(pointer) pair
picosha2::hash256(src_str, hash_byte_c_array, hash_byte_c_array+picosha2::k_digest_size);
```
```c++
std::string src_str = "The quick brown fox jumps over the lazy dog";
std::vector<unsigned char> hash(picosha2::k_digest_size);
// in: iterator pair, out: iterator pair
picosha2::hash256(src_str.begin(), src_str.end(), hash.begin(), hash.end());
```

View File

@@ -1,4 +0,0 @@
picosha2_dep = declare_dependency(
include_directories: include_directories('public')
)

View File

@@ -1,377 +0,0 @@
/*
The MIT License (MIT)
Copyright (C) 2017 okdshin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef PICOSHA2_H
#define PICOSHA2_H
// picosha2:20140213
#ifndef PICOSHA2_BUFFER_SIZE_FOR_INPUT_ITERATOR
#define PICOSHA2_BUFFER_SIZE_FOR_INPUT_ITERATOR \
1048576 //=1024*1024: default is 1MB memory
#endif
#include <algorithm>
#include <cassert>
#include <iterator>
#include <sstream>
#include <vector>
#include <fstream>
namespace picosha2 {
typedef unsigned long word_t;
typedef unsigned char byte_t;
static const size_t k_digest_size = 32;
namespace detail {
inline byte_t mask_8bit(byte_t x) { return x & 0xff; }
inline word_t mask_32bit(word_t x) { return x & 0xffffffff; }
const word_t add_constant[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
const word_t initial_message_digest[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372,
0xa54ff53a, 0x510e527f, 0x9b05688c,
0x1f83d9ab, 0x5be0cd19};
inline word_t ch(word_t x, word_t y, word_t z) { return (x & y) ^ ((~x) & z); }
inline word_t maj(word_t x, word_t y, word_t z) {
return (x & y) ^ (x & z) ^ (y & z);
}
inline word_t rotr(word_t x, std::size_t n) {
assert(n < 32);
return mask_32bit((x >> n) | (x << (32 - n)));
}
inline word_t bsig0(word_t x) { return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22); }
inline word_t bsig1(word_t x) { return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25); }
inline word_t shr(word_t x, std::size_t n) {
assert(n < 32);
return x >> n;
}
inline word_t ssig0(word_t x) { return rotr(x, 7) ^ rotr(x, 18) ^ shr(x, 3); }
inline word_t ssig1(word_t x) { return rotr(x, 17) ^ rotr(x, 19) ^ shr(x, 10); }
template <typename RaIter1, typename RaIter2>
void hash256_block(RaIter1 message_digest, RaIter2 first, RaIter2 last) {
assert(first + 64 == last);
static_cast<void>(last); // for avoiding unused-variable warning
word_t w[64];
std::fill(w, w + 64, word_t(0));
for (std::size_t i = 0; i < 16; ++i) {
w[i] = (static_cast<word_t>(mask_8bit(*(first + i * 4))) << 24) |
(static_cast<word_t>(mask_8bit(*(first + i * 4 + 1))) << 16) |
(static_cast<word_t>(mask_8bit(*(first + i * 4 + 2))) << 8) |
(static_cast<word_t>(mask_8bit(*(first + i * 4 + 3))));
}
for (std::size_t i = 16; i < 64; ++i) {
w[i] = mask_32bit(ssig1(w[i - 2]) + w[i - 7] + ssig0(w[i - 15]) +
w[i - 16]);
}
word_t a = *message_digest;
word_t b = *(message_digest + 1);
word_t c = *(message_digest + 2);
word_t d = *(message_digest + 3);
word_t e = *(message_digest + 4);
word_t f = *(message_digest + 5);
word_t g = *(message_digest + 6);
word_t h = *(message_digest + 7);
for (std::size_t i = 0; i < 64; ++i) {
word_t temp1 = h + bsig1(e) + ch(e, f, g) + add_constant[i] + w[i];
word_t temp2 = bsig0(a) + maj(a, b, c);
h = g;
g = f;
f = e;
e = mask_32bit(d + temp1);
d = c;
c = b;
b = a;
a = mask_32bit(temp1 + temp2);
}
*message_digest += a;
*(message_digest + 1) += b;
*(message_digest + 2) += c;
*(message_digest + 3) += d;
*(message_digest + 4) += e;
*(message_digest + 5) += f;
*(message_digest + 6) += g;
*(message_digest + 7) += h;
for (std::size_t i = 0; i < 8; ++i) {
*(message_digest + i) = mask_32bit(*(message_digest + i));
}
}
} // namespace detail
template <typename InIter>
void output_hex(InIter first, InIter last, std::ostream& os) {
os.setf(std::ios::hex, std::ios::basefield);
while (first != last) {
os.width(2);
os.fill('0');
os << static_cast<unsigned int>(*first);
++first;
}
os.setf(std::ios::dec, std::ios::basefield);
}
template <typename InIter>
void bytes_to_hex_string(InIter first, InIter last, std::string& hex_str) {
std::ostringstream oss;
output_hex(first, last, oss);
hex_str.assign(oss.str());
}
template <typename InContainer>
void bytes_to_hex_string(const InContainer& bytes, std::string& hex_str) {
bytes_to_hex_string(bytes.begin(), bytes.end(), hex_str);
}
template <typename InIter>
std::string bytes_to_hex_string(InIter first, InIter last) {
std::string hex_str;
bytes_to_hex_string(first, last, hex_str);
return hex_str;
}
template <typename InContainer>
std::string bytes_to_hex_string(const InContainer& bytes) {
std::string hex_str;
bytes_to_hex_string(bytes, hex_str);
return hex_str;
}
class hash256_one_by_one {
public:
hash256_one_by_one() { init(); }
void init() {
buffer_.clear();
std::fill(data_length_digits_, data_length_digits_ + 4, word_t(0));
std::copy(detail::initial_message_digest,
detail::initial_message_digest + 8, h_);
}
template <typename RaIter>
void process(RaIter first, RaIter last) {
add_to_data_length(static_cast<word_t>(std::distance(first, last)));
std::copy(first, last, std::back_inserter(buffer_));
std::size_t i = 0;
for (; i + 64 <= buffer_.size(); i += 64) {
detail::hash256_block(h_, buffer_.begin() + i,
buffer_.begin() + i + 64);
}
buffer_.erase(buffer_.begin(), buffer_.begin() + i);
}
void finish() {
byte_t temp[64];
std::fill(temp, temp + 64, byte_t(0));
std::size_t remains = buffer_.size();
std::copy(buffer_.begin(), buffer_.end(), temp);
temp[remains] = 0x80;
if (remains > 55) {
std::fill(temp + remains + 1, temp + 64, byte_t(0));
detail::hash256_block(h_, temp, temp + 64);
std::fill(temp, temp + 64 - 4, byte_t(0));
} else {
std::fill(temp + remains + 1, temp + 64 - 4, byte_t(0));
}
write_data_bit_length(&(temp[56]));
detail::hash256_block(h_, temp, temp + 64);
}
template <typename OutIter>
void get_hash_bytes(OutIter first, OutIter last) const {
for (const word_t* iter = h_; iter != h_ + 8; ++iter) {
for (std::size_t i = 0; i < 4 && first != last; ++i) {
*(first++) = detail::mask_8bit(
static_cast<byte_t>((*iter >> (24 - 8 * i))));
}
}
}
private:
void add_to_data_length(word_t n) {
word_t carry = 0;
data_length_digits_[0] += n;
for (std::size_t i = 0; i < 4; ++i) {
data_length_digits_[i] += carry;
if (data_length_digits_[i] >= 65536u) {
carry = data_length_digits_[i] >> 16;
data_length_digits_[i] &= 65535u;
} else {
break;
}
}
}
void write_data_bit_length(byte_t* begin) {
word_t data_bit_length_digits[4];
std::copy(data_length_digits_, data_length_digits_ + 4,
data_bit_length_digits);
// convert byte length to bit length (multiply 8 or shift 3 times left)
word_t carry = 0;
for (std::size_t i = 0; i < 4; ++i) {
word_t before_val = data_bit_length_digits[i];
data_bit_length_digits[i] <<= 3;
data_bit_length_digits[i] |= carry;
data_bit_length_digits[i] &= 65535u;
carry = (before_val >> (16 - 3)) & 65535u;
}
// write data_bit_length
for (int i = 3; i >= 0; --i) {
(*begin++) = static_cast<byte_t>(data_bit_length_digits[i] >> 8);
(*begin++) = static_cast<byte_t>(data_bit_length_digits[i]);
}
}
std::vector<byte_t> buffer_;
word_t data_length_digits_[4]; // as 64bit integer (16bit x 4 integer)
word_t h_[8];
};
inline void get_hash_hex_string(const hash256_one_by_one& hasher,
std::string& hex_str) {
byte_t hash[k_digest_size];
hasher.get_hash_bytes(hash, hash + k_digest_size);
return bytes_to_hex_string(hash, hash + k_digest_size, hex_str);
}
inline std::string get_hash_hex_string(const hash256_one_by_one& hasher) {
std::string hex_str;
get_hash_hex_string(hasher, hex_str);
return hex_str;
}
namespace impl {
template <typename RaIter, typename OutIter>
void hash256_impl(RaIter first, RaIter last, OutIter first2, OutIter last2, int,
std::random_access_iterator_tag) {
hash256_one_by_one hasher;
// hasher.init();
hasher.process(first, last);
hasher.finish();
hasher.get_hash_bytes(first2, last2);
}
template <typename InputIter, typename OutIter>
void hash256_impl(InputIter first, InputIter last, OutIter first2,
OutIter last2, int buffer_size, std::input_iterator_tag) {
std::vector<byte_t> buffer(buffer_size);
hash256_one_by_one hasher;
// hasher.init();
while (first != last) {
int size = buffer_size;
for (int i = 0; i != buffer_size; ++i, ++first) {
if (first == last) {
size = i;
break;
}
buffer[i] = *first;
}
hasher.process(buffer.begin(), buffer.begin() + size);
}
hasher.finish();
hasher.get_hash_bytes(first2, last2);
}
}
template <typename InIter, typename OutIter>
void hash256(InIter first, InIter last, OutIter first2, OutIter last2,
int buffer_size = PICOSHA2_BUFFER_SIZE_FOR_INPUT_ITERATOR) {
picosha2::impl::hash256_impl(
first, last, first2, last2, buffer_size,
typename std::iterator_traits<InIter>::iterator_category());
}
template <typename InIter, typename OutContainer>
void hash256(InIter first, InIter last, OutContainer& dst) {
hash256(first, last, dst.begin(), dst.end());
}
template <typename InContainer, typename OutIter>
void hash256(const InContainer& src, OutIter first, OutIter last) {
hash256(src.begin(), src.end(), first, last);
}
template <typename InContainer, typename OutContainer>
void hash256(const InContainer& src, OutContainer& dst) {
hash256(src.begin(), src.end(), dst.begin(), dst.end());
}
template <typename InIter>
void hash256_hex_string(InIter first, InIter last, std::string& hex_str) {
byte_t hashed[k_digest_size];
hash256(first, last, hashed, hashed + k_digest_size);
std::ostringstream oss;
output_hex(hashed, hashed + k_digest_size, oss);
hex_str.assign(oss.str());
}
template <typename InIter>
std::string hash256_hex_string(InIter first, InIter last) {
std::string hex_str;
hash256_hex_string(first, last, hex_str);
return hex_str;
}
inline void hash256_hex_string(const std::string& src, std::string& hex_str) {
hash256_hex_string(src.begin(), src.end(), hex_str);
}
template <typename InContainer>
void hash256_hex_string(const InContainer& src, std::string& hex_str) {
hash256_hex_string(src.begin(), src.end(), hex_str);
}
template <typename InContainer>
std::string hash256_hex_string(const InContainer& src) {
return hash256_hex_string(src.begin(), src.end());
}
template<typename OutIter>void hash256(std::ifstream& f, OutIter first, OutIter last){
hash256(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>(), first,last);
}
}// namespace picosha2
#endif // PICOSHA2_H

View File

@@ -1,6 +1,7 @@
[wrap-git]
url = https://github.com/mfem/mfem.git
revision = master
revision = v4.8-rc0
diff_files = mfem/disable_mfem_selfcheck.patch
depth = 1
[cmake]

View File

@@ -0,0 +1,8 @@
[wrap-git]
url = https://github.com/4D-STAR/opat-core
revision = main
depth = 1
[provide]
dependency_names = opatio_dep, picosha2_dep

View File

@@ -0,0 +1,206 @@
#include <gtest/gtest.h>
#include <stdexcept>
#include <string>
#include <algorithm>
#include "atomicSpecies.h"
#include "composition.h"
#include "config.h"
std::string EXAMPLE_FILENAME = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/config/example.yaml";
/**
* @brief Test suite for the composition class.
*/
class compositionTest : public ::testing::Test {};
/**
* @brief Test the constructor of the composition class.
*/
TEST_F(compositionTest, isotopeMasses) {
EXPECT_NO_THROW(chemSpecies::species.at("H-1"));
EXPECT_DOUBLE_EQ(chemSpecies::species.at("H-1").mass(), 1.007825031898);
EXPECT_DOUBLE_EQ(chemSpecies::species.at("He-3").mass(), 3.0160293219700001);
EXPECT_DOUBLE_EQ(chemSpecies::species.at("He-4").mass(),4.0026032541300003);
}
TEST_F(compositionTest, constructor) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
EXPECT_NO_THROW(composition::Composition comp);
}
TEST_F(compositionTest, registerSymbol) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
EXPECT_NO_THROW(comp.registerSymbol("H-1"));
EXPECT_NO_THROW(comp.registerSymbol("He-4"));
EXPECT_THROW(comp.registerSymbol("H-19"), std::runtime_error);
EXPECT_THROW(comp.registerSymbol("He-21"), std::runtime_error);
std::set<std::string> registeredSymbols = comp.getRegisteredSymbols();
EXPECT_TRUE(registeredSymbols.find("H-1") != registeredSymbols.end());
EXPECT_TRUE(registeredSymbols.find("He-4") != registeredSymbols.end());
EXPECT_TRUE(registeredSymbols.find("H-19") == registeredSymbols.end());
EXPECT_TRUE(registeredSymbols.find("He-21") == registeredSymbols.end());
}
TEST_F(compositionTest, setGetComposition) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
EXPECT_DOUBLE_EQ(comp.setMassFraction("H-1", 0.5), 0.0);
EXPECT_DOUBLE_EQ(comp.setMassFraction("He-4", 0.5), 0.0);
EXPECT_DOUBLE_EQ(comp.setMassFraction("H-1", 0.6), 0.5);
EXPECT_DOUBLE_EQ(comp.setMassFraction("He-4", 0.4), 0.5);
EXPECT_NO_THROW(comp.finalize());
EXPECT_DOUBLE_EQ(comp.getMassFraction("H-1"), 0.6);
EXPECT_THROW(comp.setMassFraction("He-3", 0.3), std::runtime_error);
EXPECT_NO_THROW(comp.setMassFraction({"H-1", "He-4"}, {0.5, 0.5}));
EXPECT_THROW(comp.getComposition("H-1"), std::runtime_error);
EXPECT_TRUE(comp.finalize());
EXPECT_DOUBLE_EQ(comp.getComposition("H-1").first.mass_fraction(), 0.5);
EXPECT_NO_THROW(comp.setMassFraction({"H-1", "He-4"}, {0.6, 0.6}));
EXPECT_FALSE(comp.finalize());
EXPECT_THROW(comp.getComposition("H-1"), std::runtime_error);
}
TEST_F(compositionTest, setGetNumberFraction) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1", false);
comp.registerSymbol("He-4", false);
EXPECT_DOUBLE_EQ(comp.setNumberFraction("H-1", 0.5), 0.0);
EXPECT_DOUBLE_EQ(comp.setNumberFraction("He-4", 0.5), 0.0);
EXPECT_DOUBLE_EQ(comp.setNumberFraction("H-1", 0.6), 0.5);
EXPECT_DOUBLE_EQ(comp.setNumberFraction("He-4", 0.4), 0.5);
EXPECT_NO_THROW(comp.finalize());
EXPECT_DOUBLE_EQ(comp.getNumberFraction("H-1"), 0.6);
EXPECT_THROW(comp.setNumberFraction("He-3", 0.3), std::runtime_error);
}
TEST_F(compositionTest, subset) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.6);
comp.setMassFraction("He-4", 0.4);
EXPECT_NO_THROW(comp.finalize());
std::vector<std::string> symbols = {"H-1"};
composition::Composition subsetComp = comp.subset(symbols, "norm");
EXPECT_TRUE(subsetComp.finalize());
EXPECT_DOUBLE_EQ(subsetComp.getMassFraction("H-1"), 1.0);
}
TEST_F(compositionTest, finalizeWithNormalization) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.3);
comp.setMassFraction("He-4", 0.3);
EXPECT_TRUE(comp.finalize(true));
EXPECT_DOUBLE_EQ(comp.getMassFraction("H-1"), 0.5);
EXPECT_DOUBLE_EQ(comp.getMassFraction("He-4"), 0.5);
}
TEST_F(compositionTest, finalizeWithoutNormalization) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.5);
comp.setMassFraction("He-4", 0.5);
EXPECT_TRUE(comp.finalize(false));
EXPECT_DOUBLE_EQ(comp.getMassFraction("H-1"), 0.5);
EXPECT_DOUBLE_EQ(comp.getMassFraction("He-4"), 0.5);
}
TEST_F(compositionTest, getComposition) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.6);
comp.setMassFraction("He-4", 0.4);
EXPECT_NO_THROW(comp.finalize());
auto compositionEntry = comp.getComposition("H-1");
EXPECT_DOUBLE_EQ(compositionEntry.first.mass_fraction(), 0.6);
EXPECT_DOUBLE_EQ(compositionEntry.second.meanParticleMass, 1.4382769310381101);
EXPECT_DOUBLE_EQ(compositionEntry.second.specificNumberDensity, 1.0/1.4382769310381101);
}
TEST_F(compositionTest, setCompositionMode) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.6);
comp.setMassFraction("He-4", 0.4);
EXPECT_NO_THROW(comp.finalize());
EXPECT_DOUBLE_EQ(comp.getMassFraction("H-1"), 0.6);
EXPECT_DOUBLE_EQ(comp.getMassFraction("He-4"), 0.4);
EXPECT_NO_THROW(comp.setCompositionMode(false));
EXPECT_NO_THROW(comp.setNumberFraction("H-1", 0.9));
EXPECT_NO_THROW(comp.setNumberFraction("He-4", 0.1));
EXPECT_THROW(comp.setCompositionMode(true), std::runtime_error);
EXPECT_NO_THROW(comp.finalize());
EXPECT_NO_THROW(comp.setCompositionMode(true));
}
TEST_F(compositionTest, hasSymbol) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp;
comp.registerSymbol("H-1");
comp.registerSymbol("He-4");
comp.setMassFraction("H-1", 0.6);
comp.setMassFraction("He-4", 0.4);
EXPECT_NO_THROW(comp.finalize());
EXPECT_TRUE(comp.hasSymbol("H-1"));
EXPECT_TRUE(comp.hasSymbol("He-4"));
EXPECT_FALSE(comp.hasSymbol("H-2"));
EXPECT_FALSE(comp.hasSymbol("He-3"));
}
TEST_F(compositionTest, mix) {
Config::getInstance().loadConfig(EXAMPLE_FILENAME);
composition::Composition comp1;
comp1.registerSymbol("H-1");
comp1.registerSymbol("He-4");
comp1.setMassFraction("H-1", 0.6);
comp1.setMassFraction("He-4", 0.4);
EXPECT_NO_THROW(comp1.finalize());
composition::Composition comp2;
comp2.registerSymbol("H-1");
comp2.registerSymbol("He-4");
comp2.setMassFraction("H-1", 0.4);
comp2.setMassFraction("He-4", 0.6);
EXPECT_NO_THROW(comp2.finalize());
composition::Composition mixedComp = comp1 + comp2;
EXPECT_TRUE(mixedComp.finalize());
EXPECT_DOUBLE_EQ(mixedComp.getMassFraction("H-1"), 0.5);
EXPECT_DOUBLE_EQ(mixedComp.getMassFraction("He-4"), 0.5);
composition::Composition mixedComp2 = comp1.mix(comp2, 0.25);
EXPECT_TRUE(mixedComp2.finalize());
EXPECT_DOUBLE_EQ(mixedComp2.getMassFraction("H-1"), 0.45);
EXPECT_DOUBLE_EQ(mixedComp2.getMassFraction("He-4"), 0.55);
}

View File

@@ -1,10 +1,8 @@
# Test files for opatIO
# Test files for const
test_sources = [
'opatIOTest.cpp',
'compositionTest.cpp',
]
foreach test_file : test_sources
exe_name = test_file.split('.')[0]
message('Building test: ' + exe_name)
@@ -13,9 +11,7 @@ foreach test_file : test_sources
test_exe = executable(
exe_name,
test_file,
dependencies: [gtest_dep, picosha2_dep, gtest_main],
include_directories: include_directories('../../src/opatIO/public'),
link_with: libopatIO, # Link the dobj library
dependencies: [gtest_dep, species_weight_dep, gtest_main, composition_dep],
install_rpath: '@loader_path/../../src' # Ensure runtime library path resolves correctly
)

View File

@@ -0,0 +1,91 @@
#include "composition.h"
#include "config.h"
#include <string>
int main(int argv, char* argc[]) {
std::string pathToConfigFile;
if (argv == 2) {
pathToConfigFile = argc[1];
} else {
pathToConfigFile = "config.json";
}
Config::getInstance().loadConfig(pathToConfigFile);
composition::Composition comp;
std::vector<std::string> symbols = {"H-1", "He-4"};
comp.registerSymbol(symbols);
comp.setMassFraction("H-1", 0.7);
comp.setMassFraction("He-4", 0.3);
comp.finalize();
std::cout << "=== Mass Fraction Mode ===" << std::endl;
std::cout << "\tH-1 Mass Frac: " << comp.getMassFraction("H-1") << std::endl;
std::cout << "\tH-1 Number Frac: " << comp.getNumberFraction("H-1") << std::endl;
std::cout << "\tHe-4 Mass Frac: " << comp.getMassFraction("He-4") << std::endl;
std::cout << "\tHe-4 Number Frac: " << comp.getNumberFraction("He-4") << std::endl;
std::cout << "\tMass Frac Sum: " << comp.getMassFraction("H-1") + comp.getMassFraction("He-4") << std::endl;
std::cout << "\tNumber Frac Sum: " << comp.getNumberFraction("H-1") + comp.getNumberFraction("He-4") << std::endl;
composition::Composition comp2;
comp2.registerSymbol(symbols, false);
comp2.setNumberFraction("H-1", comp.getNumberFraction("H-1"));
comp2.setNumberFraction("He-4", comp.getNumberFraction("He-4"));
comp2.finalize();
std::cout << "=== Number Fraction Mode ===" << std::endl;
std::cout << "\tH-1 Mass Frac: " << comp2.getMassFraction("H-1") << std::endl;
std::cout << "\tH-1 Number Frac: " << comp2.getNumberFraction("H-1") << std::endl;
std::cout << "\tHe-4 Mass Frac: " << comp2.getMassFraction("He-4") << std::endl;
std::cout << "\tHe-4 Number Frac: " << comp2.getNumberFraction("He-4") << std::endl;
std::cout << "\tMass Frac Sum: " << comp2.getMassFraction("H-1") + comp2.getMassFraction("He-4") << std::endl;
std::cout << "\tNumber Frac Sum: " << comp2.getNumberFraction("H-1") + comp2.getNumberFraction("He-4") << std::endl;
std::vector<std::string> symbols3 = {
"H-1",
"He-3",
"He-4",
"Li-6",
"Li-7",
"O-16",
"C-12",
"Fe-56",
"Ne-20",
"N-14",
"Mg-24",
"Si-28",
"S-32",
"Ca-40",
};
std::vector<double> mass_fractions = {
0.71243,
1e-5,
0.27,
1e-11,
1e-9,
0.009,
0.003,
0.0014,
0.0015,
0.001,
0.0006,
0.0006,
0.0004,
0.00006
};
composition::Composition comp3(symbols3, mass_fractions, true);
std::cout << "=== Mass Fraction Mode ===" << std::endl;
double massFracSum = 0.0;
double numberFracSum = 0.0;
for (const auto& symbol : symbols3) {
std::cout << "\t" << symbol << " Mass Frac: " << comp3.getMassFraction(symbol) << std::endl;
std::cout << "\t" << symbol << " Number Frac: " << comp3.getNumberFraction(symbol) << std::endl;
massFracSum += comp3.getMassFraction(symbol);
numberFracSum += comp3.getNumberFraction(symbol);
}
std::cout << "\tMass Frac Sum: " << massFracSum << std::endl;
std::cout << "\tNumber Frac Sum: " << numberFracSum << std::endl;
return 0;
}

View File

@@ -0,0 +1,2 @@
Composition:
Tracked: "H-1"

View File

@@ -0,0 +1 @@
executable('composition_sandbox', 'comp.cpp', dependencies: [composition_dep, config_dep])

View File

@@ -1,11 +1,12 @@
#include <gtest/gtest.h>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <set>
#include <sstream>
#include "helm.h"
#include "resourceManager.h"
#include "config.h"
/**
* @file constTest.cpp
@@ -17,21 +18,20 @@
*/
class eosTest : public ::testing::Test {};
std::string HELM_FILENAME = std::string(getenv("MESON_SOURCE_ROOT")) + "/assets/eos/helm_table.dat";
std::string TEST_CONFIG = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/testsConfig.yaml";
/**
* @test Verify default constructor initializes correctly.
*/
TEST_F(eosTest, constructor) {
using namespace helmholtz;
EXPECT_NO_THROW(HELMTable table = read_helm_table(HELM_FILENAME));
}
TEST_F(eosTest, read_helm_table) {
using namespace helmholtz;
HELMTable table = read_helm_table(HELM_FILENAME);
// Capture the << operator output as a string
Config::getInstance().loadConfig(TEST_CONFIG);
ResourceManager& rm = ResourceManager::getInstance();
auto& eos = std::get<std::unique_ptr<EosIO>>(rm.getResource("eos:helm"));
auto& table = eos->getTable();
auto& helmTable = *std::get<std::unique_ptr<helmholtz::HELMTable>>(table);
std::stringstream ss;
ss << table;
ss << helmTable;
EXPECT_EQ(ss.str(), "HELMTable Data:\n imax: 541, jmax: 201\n Temperature Range: [1000, 1e+13]\n Density Range: [1e-12, 1e+15]\n");
}
@@ -58,28 +58,31 @@ TEST_F(eosTest, get_helm_EOS) {
eos1.abar = 1.0/asum;
eos1.zbar = eos1.abar*zsum;
HELMTable table = read_helm_table(HELM_FILENAME);
EOS eos = get_helm_EOS(eos1, table);
// std::cout << eos << std::endl;
ResourceManager& rm = ResourceManager::getInstance();
auto& eos = std::get<std::unique_ptr<EosIO>>(rm.getResource("eos:helm"));
auto& table = eos->getTable();
auto& helmTable = *std::get<std::unique_ptr<helmholtz::HELMTable>>(table);
EOS helmEos = get_helm_EOS(eos1, helmTable);
const double absErr = 1e-12;
//Check composition info
EXPECT_DOUBLE_EQ( eos.ye, 8.75e-01);
EXPECT_NEAR( helmEos.ye, 8.75e-01, absErr);
//Check E, P, S and derivatives of each wrt Rho and T
EXPECT_DOUBLE_EQ( eos.etaele, 2.3043348231021554e+01);
EXPECT_DOUBLE_EQ( eos.etot, 1.1586558190936826e+17);
EXPECT_DOUBLE_EQ(eos.denerdd, 6.1893000468285858e+10);
EXPECT_DOUBLE_EQ(eos.denerdt, 1.2129708972542575e+08);
EXPECT_DOUBLE_EQ( eos.ptot, 6.9610135220017030e+22);
EXPECT_DOUBLE_EQ(eos.dpresdd, 1.0296440482849070e+17);
EXPECT_DOUBLE_EQ(eos.dpresdt, 7.7171347517311625e+13);
EXPECT_DOUBLE_EQ( eos.stot, 6.0647461970567346e+08);
EXPECT_DOUBLE_EQ(eos.dentrdd,-7.7171347517311645e+01);
EXPECT_DOUBLE_EQ(eos.dentrdt, 1.2129708972542577e+00);
EXPECT_NEAR( helmEos.etaele, 2.3043348231021554e+01, absErr);
EXPECT_NEAR( helmEos.etot, 1.1586558190936826e+17, 1e3);
EXPECT_NEAR(helmEos.denerdd, 6.1893000468285858e+10, 1e-2);
EXPECT_NEAR(helmEos.denerdt, 1.2129708972542575e+08, 1e-7);
EXPECT_NEAR( helmEos.ptot, 6.9610135220017030e+22, 1e10);
EXPECT_NEAR(helmEos.dpresdd, 1.0296440482849070e+17, 1e3);
EXPECT_NEAR(helmEos.dpresdt, 7.7171347517311625e+13, 1.0);
EXPECT_NEAR( helmEos.stot, 6.0647461970567346e+08, 1e-7);
EXPECT_NEAR(helmEos.dentrdd,-7.7171347517311645e+01, absErr);
EXPECT_NEAR(helmEos.dentrdt, 1.2129708972542577e+00, absErr);
const double abs_err = 1.0e-12;
// Maxwell relations, should always be zero
EXPECT_NEAR( eos.dse, 0, abs_err);
EXPECT_NEAR( eos.dpe, 0, abs_err);
EXPECT_NEAR( eos.dsp, 0, abs_err);
EXPECT_NEAR( helmEos.dse, 0, absErr);
EXPECT_NEAR( helmEos.dpe, 0, absErr);
EXPECT_NEAR( helmEos.dsp, 0, absErr);
}

View File

@@ -11,7 +11,7 @@ foreach test_file : test_sources
test_exe = executable(
exe_name,
test_file,
dependencies: [gtest_dep, eos_dep, gtest_main],
dependencies: [gtest_dep, eos_dep, gtest_main, resourceManager_dep, config_dep],
install_rpath: '@loader_path/../../src' # Ensure runtime library path resolves correctly
)

View File

@@ -1,10 +1,9 @@
#include <gtest/gtest.h>
#include "meshIO.h"
#include <iostream>
#include <string>
#include "mfem.hpp"
std::string EXAMPLE_FILENAME = std::string(getenv("MESON_SOURCE_ROOT")) + "/src/resources/mesh/sphere.msh";
std::string EXAMPLE_FILENAME = std::string(getenv("MESON_SOURCE_ROOT")) + "/assets/dynamic/mesh/sphere.msh";
double ComputeMeshVolume(mfem::Mesh &mesh)
{

View File

@@ -6,13 +6,17 @@ gtest_nomain_dep = dependency('gtest', main: false, required : true)
# Subdirectories for unit and integration tests
subdir('dobj')
subdir('const')
subdir('opatIO')
subdir('meshIO')
subdir('probe')
subdir('config')
subdir('eos')
subdir('resource')
subdir('network')
subdir('composition')
subdir('poly')
# Subdirectories for sandbox tests
subdir('dobj_sandbox')
subdir('opatIO_sandbox')
subdir('composition_sandbox')

View File

@@ -0,0 +1,50 @@
#include <gtest/gtest.h>
#include <string>
#include "approx8.h"
#include "config.h"
#include "network.h"
#include <vector>
std::string TEST_CONFIG = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/testsConfig.yaml";
class approx8Test : public ::testing::Test {};
/**
* @brief Test the constructor of the Config class.
*/
TEST_F(approx8Test, constructor) {
Config& config = Config::getInstance();
config.loadConfig(TEST_CONFIG);
EXPECT_NO_THROW(nnApprox8::Approx8Network());
}
TEST_F(approx8Test, setStiff) {
nnApprox8::Approx8Network network;
EXPECT_NO_THROW(network.setStiff(true));
EXPECT_TRUE(network.isStiff());
EXPECT_NO_THROW(network.setStiff(false));
EXPECT_FALSE(network.isStiff());
}
TEST_F(approx8Test, evaluate) {
nnApprox8::Approx8Network network;
nuclearNetwork::NetIn netIn;
std::vector<double> comp = {0.708, 2.94e-5, 0.276, 0.003, 0.0011, 9.62e-3, 1.62e-3, 5.16e-4};
netIn.composition = comp;
netIn.temperature = 1e7;
netIn.density = 1e2;
netIn.energy = 0.0;
netIn.tmax = 3.15e17;
netIn.dt0 = 1e12;
nuclearNetwork::NetOut netOut;
EXPECT_NO_THROW(netOut = network.evaluate(netIn));
EXPECT_DOUBLE_EQ(netOut.composition[nnApprox8::Net::ih1], 0.50166260916650918);
EXPECT_DOUBLE_EQ(netOut.composition[nnApprox8::Net::ihe4],0.48172270591286032);
EXPECT_DOUBLE_EQ(netOut.energy, 1.6433049870528356e+18);
}

25
tests/network/meson.build Normal file
View File

@@ -0,0 +1,25 @@
# Test files for network
test_sources = [
'approx8Test.cpp',
]
foreach test_file : test_sources
exe_name = test_file.split('.')[0]
message('Building test: ' + exe_name)
# Create an executable target for each test
test_exe = executable(
exe_name,
test_file,
dependencies: [gtest_dep, network_dep, gtest_main],
include_directories: include_directories('../../src/network/public'),
link_with: libnetwork, # Link the dobj library
install_rpath: '@loader_path/../../src' # Ensure runtime library path resolves correctly
)
# Add the executable as a test
test(
exe_name,
test_exe,
env: ['MESON_SOURCE_ROOT=' + meson.project_source_root(), 'MESON_BUILD_ROOT=' + meson.project_build_root()])
endforeach

View File

@@ -1,133 +0,0 @@
#include <gtest/gtest.h>
#include "opatIO.h"
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <sstream>
#include <cstring>
#include "picosha2.h"
std::string EXAMPLE_FILENAME = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/opatIO/synthetic_tables.opat";
/**
* @file opatIOTest.cpp
* @brief Unit tests for the OpatIO class and associated structs.
*/
/**
* @brief Test suite for the const class.
*/
class opatIOTest : public ::testing::Test {};
/**
* @test Verify default constructor initializes correctly.
*/
TEST_F(opatIOTest, DefaultConstructor) {
EXPECT_NO_THROW(OpatIO());
}
/*
* @test Verify constructor initializes correctly with a file.
*/
TEST_F(opatIOTest, Constructor) {
OpatIO opatIO(EXAMPLE_FILENAME);
}
/**
* @test Verify the header is read correctly.
*/
TEST_F(opatIOTest, Header) {
OpatIO opatIO(EXAMPLE_FILENAME);
Header header = opatIO.getHeader();
EXPECT_EQ(header.version, 1);
EXPECT_EQ(header.numTables, 20);
EXPECT_EQ(header.headerSize, 256);
EXPECT_EQ(header.indexOffset, 416416);
EXPECT_EQ(std::string(header.creationDate), "Feb 17, 2025");
EXPECT_EQ(std::string(header.sourceInfo), "utils/opatio/utils/mkTestData.py");
EXPECT_EQ(std::string(header.comment), "Synthetic Opacity Tables");
EXPECT_EQ(header.numIndex, 2);
}
/**
* @test Verify the number of index values is correct. Also check the byte position and index vector
*/
TEST_F(opatIOTest, TableIndex) {
OpatIO opatIO(EXAMPLE_FILENAME);
std::vector<TableIndex> tableIndex = opatIO.getTableIndex();
EXPECT_EQ(tableIndex.size(), 20);
EXPECT_EQ(tableIndex[0].index.at(0), 0.1);
EXPECT_EQ(tableIndex[0].index.at(1), 0.001);
EXPECT_EQ(tableIndex[0].byteStart, 256);
EXPECT_EQ(tableIndex[0].byteEnd, 21064);
}
/**
* @test Verify the maxQDepth (for caching)
*/
TEST_F(opatIOTest, MaxQDepth) {
OpatIO opatIO(EXAMPLE_FILENAME);
EXPECT_EQ(opatIO.getMaxQDepth(), 20);
opatIO.setMaxQDepth(5);
EXPECT_EQ(opatIO.getMaxQDepth(), 5);
}
/**
* @test Verify the Unload function
*/
TEST_F(opatIOTest, Unload){
OpatIO opatIO(EXAMPLE_FILENAME);
EXPECT_NO_THROW(opatIO.unload());
EXPECT_FALSE(opatIO.isLoaded());
}
/**
* @test Verify the lookupTableID function
*/
TEST_F(opatIOTest, LookupTableID) {
OpatIO opatIO(EXAMPLE_FILENAME);
std::vector<double> index = {0.321053, 0.0116842};
EXPECT_EQ(opatIO.lookupTableID(index), 7);
}
/**
* @test Verify the GetTable function by checking the first 2x2 square of the table
*/
TEST_F(opatIOTest, GetTable) {
OpatIO opatIO(EXAMPLE_FILENAME);
std::vector<double> index = {0.1, 0.001};
OPATTable tab = opatIO.getTable(index);
EXPECT_EQ(tab.N_R, 50);
EXPECT_EQ(tab.N_T, 50);
EXPECT_DOUBLE_EQ(tab.logR[0], -8.0);
EXPECT_DOUBLE_EQ(tab.logT[0], 3.0);
EXPECT_DOUBLE_EQ(tab.logKappa[0][0], -0.50183952461055);
EXPECT_DOUBLE_EQ(tab.logKappa[0][1], 1.8028572256396647);
EXPECT_DOUBLE_EQ(tab.logKappa[1][0], 1.8783385110582342);
EXPECT_DOUBLE_EQ(tab.logKappa[1][1], 1.1005312934444582);
}
/**
* @test Verify the GetTable function by computing the checksum of the first table and
* comparing it to the stored checksum
*/
TEST_F(opatIOTest, Checksum) {
OpatIO opatIO(EXAMPLE_FILENAME);
std::vector<double> index = {0.1, 0.001};
TableIndex tableIndex = opatIO.getTableIndex(index);
std::vector<unsigned char> hash = opatIO.computeChecksum(index);
std::string hexRepr = picosha2::bytes_to_hex_string(hash);
std::vector<unsigned char> storedHashVec(tableIndex.sha256, tableIndex.sha256 + 32);
std::string storedHexRepr = picosha2::bytes_to_hex_string(storedHashVec);
EXPECT_EQ(hexRepr, storedHexRepr);
}
TEST_F(opatIOTest, ChecksumAll) {
OpatIO opatIO(EXAMPLE_FILENAME);
opatIO.setMaxQDepth(5);
EXPECT_TRUE(opatIO.validateAll());
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@
executable('tryGS98', 'opacity.cpp', dependencies: [opatio_dep])

View File

@@ -0,0 +1,28 @@
#include <vector>
#include <iostream>
//#include <string>
#include "opatIO.h"
int main() {
std::string FILENAME = "GS98hz.opat";
OpatIO opatIO(FILENAME);
Header header = opatIO.getHeader();
std::cout << header.version << std::endl;
std::cout << header.comment << std::endl;
std::cout << header.numTables << std::endl;
std::vector<TableIndex> tableIndex = opatIO.getTableIndex();
//print out the X,Z pairs in the table
for (size_t i=0; i< tableIndex.size()-1; i++){
std::cout << "Table [" << i << "]: {" << tableIndex[i].index.at(0) << ", "
<< tableIndex[i].index.at(1) << "}" << std::endl;
}
//find the table index corresponding to X=0.1, Z=0.001
std::vector<double> index = {0.1, 0.001};
OPATTable tab = opatIO.getTable(index);
}

View File

@@ -16,5 +16,8 @@ foreach test_file : test_sources
)
# Add the executable as a test
test(exe_name, test_exe)
test(
exe_name,
test_exe,
env: ['MESON_SOURCE_ROOT=' + meson.project_source_root(), 'MESON_BUILD_ROOT=' + meson.project_build_root()])
endforeach

View File

@@ -7,9 +7,12 @@
#include <sstream>
#include <regex>
#include <source_location>
#include "config.h"
#include <chrono>
#include "quill/LogMacros.h"
std::string TEST_CONFIG = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/testsConfig.yaml";
std::string getLastLine(const std::string& filename) {
std::ifstream file(filename);
std::string line, lastLine;
@@ -38,6 +41,7 @@ std::string stripTimestamps(const std::string& logLine) {
class probeTest : public ::testing::Test {};
TEST_F(probeTest, DefaultConstructorTest) {
Config::getInstance().loadConfig(TEST_CONFIG);
EXPECT_NO_THROW(Probe::LogManager::getInstance());
}
@@ -50,20 +54,23 @@ TEST_F(probeTest, waitTest) {
}
TEST_F(probeTest, getLoggerTest) {
Config::getInstance().loadConfig(TEST_CONFIG);
Probe::LogManager& logManager = Probe::LogManager::getInstance();
std::string loggerName = "log";
quill::Logger* logger = logManager.getLogger(loggerName);
const std::string loggerName = "testLog";
const std::string filename = "test.log";
quill::Logger* logger = logManager.newFileLogger(filename, loggerName);
EXPECT_NE(logger, nullptr);
LOG_INFO(logger, "This is a test message");
// Wait for the log to be written by calling getLastLine until it is non empty
std::string lastLine;
while (lastLine.empty()) {
lastLine = getLastLine("4DSSE.log");
lastLine = getLastLine("test.log");
}
EXPECT_EQ(stripTimestamps(lastLine), "This is a test message");
}
TEST_F(probeTest, newFileLoggerTest) {
Config::getInstance().loadConfig(TEST_CONFIG);
Probe::LogManager& logManager = Probe::LogManager::getInstance();
const std::string loggerName = "newLog";
const std::string filename = "newLog.log";
@@ -79,10 +86,12 @@ TEST_F(probeTest, newFileLoggerTest) {
}
TEST_F(probeTest, getLoggerNames) {
Config::getInstance().loadConfig(TEST_CONFIG);
Probe::LogManager& logManager = Probe::LogManager::getInstance();
std::vector<std::string> loggerNames = logManager.getLoggerNames();
EXPECT_EQ(loggerNames.size(), 3);
EXPECT_EQ(loggerNames.size(), 4);
EXPECT_EQ(loggerNames.at(0), "log");
EXPECT_EQ(loggerNames.at(1), "newLog");
EXPECT_EQ(loggerNames.at(2), "stdout");
EXPECT_EQ(loggerNames.at(3), "testLog");
}

View File

@@ -0,0 +1,24 @@
# Test files for const
test_sources = [
'resourceManagerTest.cpp',
]
foreach test_file : test_sources
exe_name = test_file.split('.')[0]
message('Building test: ' + exe_name)
# Create an executable target for each test
test_exe = executable(
exe_name,
test_file,
dependencies: [gtest_dep, resourceManager_dep, gtest_main, macros_dep],
include_directories: include_directories('../../src/resource/public'),
install_rpath: '@loader_path/../../src' # Ensure runtime library path resolves correctly
)
# Add the executable as a test
test(
exe_name,
test_exe,
env: ['MESON_SOURCE_ROOT=' + meson.project_source_root(), 'MESON_BUILD_ROOT=' + meson.project_build_root()])
endforeach

View File

@@ -0,0 +1,61 @@
#include <gtest/gtest.h>
#include "resourceManager.h"
#include "config.h"
#include "eosIO.h"
#include "helm.h"
#include "resourceManagerTypes.h"
#include <string>
#include <stdexcept>
#include <vector>
#include <set>
#include "debug.h"
/**
* @file configTest.cpp
* @brief Unit tests for the resourceManager class.
*/
std::string TEST_CONFIG = std::string(getenv("MESON_SOURCE_ROOT")) + "/tests/testsConfig.yaml";
/**
* @brief Test suite for the resourceManager class.
*/
class resourceManagerTest : public ::testing::Test {};
/**
* @brief Test the constructor of the resourceManager class.
*/
TEST_F(resourceManagerTest, constructor) {
Config::getInstance().loadConfig(TEST_CONFIG);
EXPECT_NO_THROW(ResourceManager::getInstance());
}
TEST_F(resourceManagerTest, getAvaliableResources) {
Config::getInstance().loadConfig(TEST_CONFIG);
ResourceManager& rm = ResourceManager::getInstance();
std::vector<std::string> resources = rm.getAvaliableResources();
std::set<std::string> expected = {"eos:helm", "mesh:sphere"};
std::set<std::string> actual(resources.begin(), resources.end());
EXPECT_EQ(expected, actual);
}
TEST_F(resourceManagerTest, getResource) {
Config::getInstance().loadConfig(TEST_CONFIG);
ResourceManager& rm = ResourceManager::getInstance();
std::string name = "eos:helm";
const Resource &r = rm.getResource(name);
// BREAKPOINT();
const auto &eos = std::get<std::unique_ptr<EosIO>>(r);
EXPECT_EQ("helm", eos->getFormat());
EOSTable &table = eos->getTable();
// -- Extract the Helm table from the EOSTable
helmholtz::HELMTable &helmTable = *std::get<std::unique_ptr<helmholtz::HELMTable>>(table);
EXPECT_DOUBLE_EQ(helmTable.f[0][0], -1692098915534.8142);
EXPECT_THROW(rm.getResource("opac:GS98:high:doesNotExist"), std::runtime_error);
}

View File

@@ -0,0 +1,222 @@
import pandas as pd
# Define fixed-width column specifications based on the format:
# a1 (width 1), i3 (width 3), i5 (width 5), i5 (width 5), i5 (width 5),
# 1x (skip 1), a3 (width 3), a4 (width 4), 1x (skip 1),
# f14.6 (width 14), f12.6 (width 12), f13.5 (width 13),
# 1x (skip 1), f10.5 (width 10), 1x (skip 1),
# a2 (width 2), f13.5 (width 13), f11.5 (width 11),
# 1x (skip 1), i3 (width 3), 1x (skip 1),
# f13.6 (width 13), f12.6 (width 12)
# Compute cumulative positions (0-indexed):
colSpecs = [
(0, 1), # control
(1, 4), # NZ
(4, 9), # N
(9, 14), # Z
(14, 19), # A
# skip 1 char at position 19; next field starts at 20
(20, 23), # el
(23, 27), # o
# skip 1 char at position 27; next field starts at 28
(28, 42), # massExcess (f14.6)
(42, 54), # massExcessUnc (f12.6)
(54, 67), # bindingEnergy (f13.5)
# skip 1 char at position 67; next field starts at 68
(68, 78), # bindingEnergyUnc (f10.5)
# skip 1 char at position 78; next field starts at 79
(79, 81), # betaCode (a2)
(81, 94), # betaDecayEnergy (f13.5)
(94, 105), # betaDecayEnergyUnc (f11.5)
# skip 1 char at position 105; next field starts at 106
(106, 109),# atomicMassInt (i3)
# skip 1 char at position 109; next field starts at 110
(110, 123),# atomicMassFrac (f13.6)
(123, 135) # atomicMassUnc (f12.6)
]
# Define column names (using camelCase for variables)
columnNames = [
"control",
"nz",
"n",
"z",
"a",
"el",
"o",
"massExcess",
"massExcessUnc",
"bindingEnergy",
"bindingEnergyUnc",
"betaCode",
"betaDecayEnergy",
"betaDecayEnergyUnc",
"atomicMassInt",
"atomicMassFrac",
"atomicMassUnc"
]
def combine_atomic_mass(row):
"""
Combine the integer and fractional parts of the atomic mass.
For example, if atomicMassInt is '1' and atomicMassFrac is '008664.91590',
this function returns float('1008664.91590').
"""
intPart = str(row["atomicMassInt"]).strip()
fracPart = str(row["atomicMassFrac"]).strip()
try:
combined = int(intPart) + float(fracPart)/1e6
return combined
except ValueError:
return None
def mkInstanceName(row):
"""
Make a c++ instance name from the element and atomic number.
"""
speciesName = f"{row['el'].strip()}-{row['a']}"
return speciesName.replace("-", "_")
def formatSpecies(row):
"""
Format c++ instantiation of Species struct from row data.
"""
name = f"{row['el'].strip()}-{row['a']}"
instanceName = name.replace("-", "_")
nz = int(row['nz'])
n = int(row['n'])
z = int(row['z'])
a = int(row['a'])
bindingEnergy = float(row['bindingEnergy'])
atomicMass = float(row['atomicMass'])
atomicMassUnc = float(row['atomicMassUnc'])
NaN = "std::numeric_limits<double>::quiet_NaN()"
try:
betaDecayEnergy = float(row['betaDecayEnergy'].replace("#", "").replace("*", ""))
except ValueError:
betaDecayEnergy = NaN
instantiation = f"static const Species {instanceName}(\"{name}\", \"{row['el']}\", {nz}, {n}, {z}, {a}, {bindingEnergy}, \"{row['betaCode']}\", {betaDecayEnergy}, {atomicMass}, {atomicMassUnc});"
return instantiation
def formatHeader(dataFrame):
"""
Format c++ header file from DataFrame.
"""
header = f"""#ifndef SPECIES_MASS_DATA_H
#define SPECIES_MASS_DATA_H
#include <unordered_map>
#include <string_view>
#include <string>
namespace chemSpecies {{
struct Species {{
const std::string_view m_name; //< Name of the species
const std::string_view m_el; //< Element symbol
const int m_nz; //< NZ
const int m_n; //< N
const int m_z; //< Z
const int m_a; //< A
const double m_bindingEnergy; //< Binding energy
const std::string_view m_betaCode; //< Beta decay code
const double m_betaDecayEnergy; //< Beta decay energy
const double m_atomicMass; //< Atomic mass
const double m_atomicMassUnc; //< Atomic mass uncertainty
Species(const std::string_view name, const std::string_view el, const int nz, const int n, const int z, const int a, const double bindingEnergy, const std::string_view betaCode, const double betaDecayEnergy, const double atomicMass, const double atomicMassUnc)
: m_name(name), m_el(el), m_nz(nz), m_n(n), m_z(z), m_a(a), m_bindingEnergy(bindingEnergy), m_betaCode(betaCode), m_betaDecayEnergy(betaDecayEnergy), m_atomicMass(atomicMass), m_atomicMassUnc(atomicMassUnc) {{}};
Species(const Species& species) {{
m_name = species.m_name;
m_el = species.m_el;
m_nz = species.m_nz;
m_n = species.m_n;
m_z = species.m_z;
m_a = species.m_a;
m_bindingEnergy = species.m_bindingEnergy;
m_betaCode = species.m_betaCode;
m_betaDecayEnergy = species.m_betaDecayEnergy;
m_atomicMass = species.m_atomicMass;
m_atomicMassUnc = species.m_atomicMassUnc;
}}
double mass() const {{
return m_atomicMass;
}}
double massUnc() const {{
return m_atomicMassUnc;
}}
double bindingEnergy() const {{
return m_bindingEnergy;
}}
double betaDecayEnergy() const {{
return m_betaDecayEnergy;
}}
std::string_view betaCode() const {{
return m_betaCode;
}}
std::string_view name() const {{
return m_name;
}}
std::string_view el() const {{
return m_el;
}}
int nz() const {{
return m_nz;
}}
int n() const {{
return m_n;
}}
int z() const {{
return m_z;
}}
int a() const {{
return m_a;
}}
friend std::ostream& operator<<(std::ostream& os, const Species& species) {{
os << static_cast<std::string>(species.m_name) << " (" << species.m_atomicMass << " u)";
return os;
}}
}};
{'\n '.join([formatSpecies(row) for index, row in dataFrame.iterrows()])}
static const std::unordered_map<std::string, Species> species = {{
{'\n '.join([f'{{"{row["el"].strip()}-{row["a"]}", {mkInstanceName(row)}}},' for index, row in dataFrame.iterrows()])}
}};
}}; // namespace chemSpecies
#endif // SPECIES_MASS_DATA_H
"""
return header
if __name__ == "__main__":
import argparse
import os
parser = argparse.ArgumentParser(description="Convert mass data to c++ header file.")
parser.add_argument("input", help="Input file path.")
parser.add_argument("-o", "--output", help="Output file path.", default="../../assets/static/atomic/include/atomicSpecies.h")
args = parser.parse_args()
if not os.path.exists(args.input):
raise FileNotFoundError(f"File not found: {args.input}")
# Read the file (adjust the skiprows value if your header differs)
dataFrame = pd.read_fwf(args.input, colspecs=colSpecs, names=columnNames, skiprows=36)
# Combine the two atomic mass fields into one float column
dataFrame["atomicMass"] = dataFrame.apply(combine_atomic_mass, axis=1)
dataFrame.drop(columns=["atomicMassInt", "atomicMassFrac"], inplace=True)
# Format the header
header = formatHeader(dataFrame)
with open(args.output, "w") as f:
f.write(header)

13
utils/atomic/readme.md Normal file
View File

@@ -0,0 +1,13 @@
# Information
Simple python utility for turning the file assets/atomic/weights.dat into a c++ header which can be included to provide easy access to all atomic weights inside 4DSSE
## Requirments
In order to use this utility you will need
- Python
- Pandas
## Usage
```bash
python convertWeightsToHeader.py <path/to/weights.dat> -o atomicWeights.h
```

View File

@@ -1,47 +1,22 @@
Poly:
Gaussian:
Sigma: 0.1
Solver:
ViewInitialGuess: false
Debug:
Global:
GLVis:
Keyset: ''
View: 'false'
Exit: 'false'
F_gf_View:
Keyset: defaultKeyset
EOS:
Helm:
LogFile: "log"
Network:
Approx8:
NonStiff:
AbsTol: 1.0e-06
RelTol: 1.0e-06
Stiff:
AbsTol: 1.0e-06
RelTol: 1.0e-06
Probe:
GLVis:
Visualization: true
Host: localhost
Port: 19916
LogManager:
DefaultLogName: 4DSSE.log
# This file was auto-generated by generateDefaultConfig.py
# Do not modify this file directly.
#=================================== TYPE HINTS ===================================
# Poly:
# Gaussian:
# Sigma: double
# Solver:
# ViewInitialGuess: bool
# Debug:
# Global:
# GLVis:
# Keyset: sd:string
# View: bo
# Exit: bo
# F_gf_View:
# Keyset: std:string
# Probe:
# GLVis:
# Visualization: bool
# Host: std::string
# Port: int
# LogManager:
# DefaultLogName: std::string
#
GLVis:
Host: "localhost"
Port: 19916
Visualization: true
LogManager:
DefaultLogName: "4DSSE.log"
opac:
lowTemp:
numeric:
maxIter: 10

View File

@@ -31,6 +31,9 @@ def parse_value(value, type_hint):
if type_hint in {"int", "long"}:
return (int(value), type_hint)
elif type_hint in {"float", "double"}:
return float(value)
elif value == "defaultDataDir":
return "data" # special case for defaultDataDir
return (float(value), type_hint)
elif type_hint == "bool":
return (value.lower() in {"true", "1"}, type_hint)
@@ -38,6 +41,9 @@ def parse_value(value, type_hint):
return (value.strip('"'), type_hint) # Remove quotes for string literals
elif value.startswith("'") and value.endswith("'"):
return (value.strip("'"), type_hint) # Remove single quotes
return value.strip("'") # Remove single quotes
elif value.startswith('"') and value.endswith('"'):
return (value.strip('"'). type_hint)# Remove quotes for string literals
return (value, type_hint) # Return as-is if unsure
@@ -66,10 +72,19 @@ def scan_files(directory):
print(f"Match: {match.group()}")
type_hint, hierarchy, value = match.groups()
keys = hierarchy.split(":")
if keys[0] == "Data" and keys[1] == "Dir":
continue # Skip Data:Dir as it is a special case
insert_into_dict(hierarchy_dict, keys, value, type_hint)
return hierarchy_dict
class QuotedString(str):
pass
def represent_quoted_string(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
def split_dict_recursive(originalDict):
dataDict = {}
typeDict = {}
@@ -87,6 +102,19 @@ def split_dict_recursive(originalDict):
def save_yaml(data, output_file):
"""Saves the nested dictionary to a YAML file."""
yaml.add_representer(QuotedString, represent_quoted_string)
def quote_strings(data):
if isinstance(data, dict):
return {k: quote_strings(v) for k, v in data.items()}
elif isinstance(data, list):
return [quote_strings(item) for item in data]
elif isinstance(data, str):
return QuotedString(data)
else:
return data
data = quote_strings(data)
options, types = split_dict_recursive(data)
with open(output_file, 'w', encoding='utf-8') as f:
yaml.dump(options, f, default_flow_style=False, sort_keys=False, indent=4)

View File

@@ -48,18 +48,23 @@ class OPATTable:
logT: Iterable[float] #< Logarithm of T values
logKappa: Iterable[Iterable[float]] #< Logarithm of Kappa values
defaultHeader = Header(
magic="OPAT",
version=1,
numTables=0,
headerSize=256,
indexOffset=0,
creationDate=datetime.now().strftime("%b %d, %Y"),
sourceInfo="no source provided by user",
comment="default header",
numIndex=2,
reserved=b"\x00" * 24
)
def make_default_header() -> Header:
"""
@brief Create a default header for an OPAT file.
@return The default header.
"""
return Header(
magic="OPAT",
version=1,
numTables=0,
headerSize=256,
indexOffset=0,
creationDate=datetime.now().strftime("%b %d, %Y"),
sourceInfo="no source provided by user",
comment="default header",
numIndex=2,
reserved=b"\x00" * 24
)
class OpatIO:
"""
@@ -103,7 +108,7 @@ class OpatIO:
Save the OPAT file as a binary file.
"""
def __init__(self):
self.header: Header = defaultHeader
self.header: Header = make_default_header()
self.tables: List[Tuple[Tuple[float, float], OPATTable]] = []
@staticmethod
@@ -353,7 +358,7 @@ class OpatIO:
tableString.append(logRRow + logRRowTrue)
for i, logT in enumerate(table.logT):
row = f"{logT:<10.4f}"
for kappa in table.logKappa[i]:
for kappa in table.logKappa[:, i]:
row += f"{kappa:<10.4f}"
tableString.append(row)
tableString.append("=" * 80)