diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index db26440..df71251 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -29,7 +29,7 @@ jobs:
timeout-minutes: 15
strategy:
matrix:
- environment: [test-py311, test-py312, test-py313]
+ environment: [test-py311, test-py312]
steps:
- name: Checkout
uses: actions/checkout@v4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0e4c7c2..3bae887 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -17,7 +17,7 @@ jobs:
with:
pixi-version: v0.40.2
cache: false
- environments: build
+ environments: dist
activate-environment: true
- name: Build distributions
run: pixi run build-dist
diff --git a/.gitignore b/.gitignore
index 7f977f2..c743f91 100644
--- a/.gitignore
+++ b/.gitignore
@@ -60,3 +60,15 @@ diff.md
# Lock file
*.lock
+
+# Tutorial required files
+!tutorial_dataset.h5
+
+# Tutorial generated files
+configure_profile.yaml
+configure_computer.yaml
+configure_code.yaml
+.aiida_run
+
+# Development test sandbox
+test_dev
diff --git a/LICENSE b/LICENSE
index f288702..0a04128 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,674 +1,165 @@
- GNU GENERAL PUBLIC LICENSE
+ GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
-
-
- Copyright (C)
-
- 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 .
-
-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:
-
- Copyright (C)
- 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
-.
-
- 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
-.
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser 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
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/pyproject.toml b/pyproject.toml
index 257beb2..81e1f08 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,23 +11,27 @@ classifiers = [
"Programming Language :: Python",
"Operating System :: POSIX :: Linux",
"Intended Audience :: Science/Research",
- "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
+ "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
"Development Status :: 3 - Alpha",
"Framework :: AiiDA"
]
keywords = ["aiida", "plugin", "fans"]
requires-python = ">=3.11"
dependencies = [
- "aiida-core>=2.3",
+ "aiida-core>=2.6",
"h5py"
]
# Entry Points
-[project.entry-points]
-"aiida.data" = { "fans" = "aiida_fans.data:FANSParameters" }
-"aiida.calculations" = { "fans" = "aiida_fans.calculations:FANSCalculation" }
-"aiida.parsers" = { "fans" = "aiida_fans.parsers:FANSParser" }
-"aiida.cmdline.data" = { "fans" = "aiida_fans.cli:data_cli" }
+# [project.entry-points."aiida.data"]
+# "fans" = "aiida_fans.data:FANSParameters"
+[project.entry-points."aiida.calculations"]
+"fans.stashed" = "aiida_fans.calculations:FansStashedCalculation"
+"fans.fragmented" = "aiida_fans.calculations:FansFragmentedCalculation"
+[project.entry-points."aiida.parsers"]
+"fans" = "aiida_fans.parsers:FansParser"
+# [project.entry-points."aiida.cmdline.data"]
+# "fans" = "aiida_fans.cli:data_cli"
# Build System
[build-system]
@@ -44,7 +48,7 @@ platforms = ["linux-64"]
### pixi: default dependencies (in addition to aiida-core)
[tool.pixi.dependencies]
-fans = "*"
+# None
[tool.pixi.pypi-dependencies]
# None
@@ -52,41 +56,47 @@ fans = "*"
[tool.pixi.tasks]
# None
-### pixi: features (in addition to fans)
-[tool.pixi.feature.dev]
-pypi-dependencies = {aiida-fans = { path = ".", editable = true }}
-[tool.pixi.feature.prod]
+### pixi: features
+[tool.pixi.feature.self]
pypi-dependencies = {aiida-fans = { path = ".", editable = true }}
-[tool.pixi.feature.fmt]
+[tool.pixi.feature.plugin]
+dependencies = {aiida-fans = "==0.1.5"}
+# [tool.pixi.feature.aiida]
+# dependencies = {aiida-core = "2.6.*"}
+[tool.pixi.feature.fans]
+dependencies = {fans = "0.4.*"}
+[tool.pixi.feature.ruff]
dependencies = {ruff = "*"}
tasks = {fmt = "ruff check", dummy = "echo dummy", my-dummy="echo my-dummy"}
[tool.pixi.feature.build]
pypi-dependencies = {build = "*"}
tasks = {build-dist = "python -m build"}
-[tool.pixi.feature.docs]
+[tool.pixi.feature.sphinx]
dependencies = {sphinx = "*", sphinx-book-theme = "*"}
tasks = {build-docs = "sphinx-build -M html docs/source docs/build"}
-[tool.pixi.feature.test]
+[tool.pixi.feature.pytest]
dependencies = {pytest = "*"}
tasks = {test = "echo dummy test passes"}
-[tool.pixi.feature.py3]
-dependencies = {python = ">=3.11"}
+[tool.pixi.feature.marimo]
+dependencies = {marimo = "0.13.*"}
+tasks = {tutorial = "marimo edit tutorial.py"}
[tool.pixi.feature.py311]
dependencies = {python = "3.11.*"}
[tool.pixi.feature.py312]
dependencies = {python = "3.12.*"}
-[tool.pixi.feature.py313]
-dependencies = {python = "3.13.*"}
+# [tool.pixi.feature.py313]
+# dependencies = {python = "3.13.*"}
### pixi: environments
[tool.pixi.environments]
-dev = { features = ["dev", "fmt", "test"], solve-group = "default" }
-fmt = { features = ["fmt", "py3"], no-default-feature = true }
-build = { features = ["build", "py3"], no-default-feature = true }
-docs = { features = ["docs", "py3"], no-default-feature = true }
-test-py311 = { features = ["prod", "test", "py311"], solve-group = "py311" }
-test-py312 = { features = ["prod", "test", "py312"], solve-group = "py312" }
-test-py313 = { features = ["prod", "test", "py313"], solve-group = "py313" }
+dev = { features = ["self", "ruff", "pytest"], solve-group = "default" }
+fmt = { features = ["ruff", "py312"], no-default-feature = true }
+dist = { features = ["build", "py312"], no-default-feature = true }
+docs = { features = ["sphinx", "py312"], no-default-feature = true }
+test-py311 = { features = ["self", "fans", "pytest", "py311"], solve-group = "py311" }
+test-py312 = { features = ["self", "fans", "pytest", "py312"], solve-group = "py312" }
+# test-py313 = { features = ["self", "fans", "pytest", "py313"], solve-group = "py313" }
+tutorial = { features = ["plugin", "fans", "marimo"], no-default-feature = true}
## Build Tools: setuptools_scm
@@ -95,7 +105,10 @@ version_file = "src/aiida_fans/_version.py"
## Style Tools: ruff
[tool.ruff]
-extend-exclude = ["conf.py"]
+extend-exclude = [
+ "conf.py",
+ "tutorial.py"
+]
line-length = 120
[tool.ruff.lint]
ignore = [
diff --git a/src/aiida_fans/calculations.py b/src/aiida_fans/calculations.py
index 8f2575f..a53965a 100644
--- a/src/aiida_fans/calculations.py
+++ b/src/aiida_fans/calculations.py
@@ -1,260 +1,146 @@
-"""Calculations provided by aiida_fans."""
+"""CalcJob subclasses for aiida-fans calculations."""
from json import dump
-from typing import Any, Callable
+from pathlib import Path
+from shutil import copyfileobj
-import h5py
from aiida.common.datastructures import CalcInfo, CodeInfo
from aiida.common.folders import Folder
from aiida.engine import CalcJob
from aiida.engine.processes.process_spec import CalcJobProcessSpec
-from aiida.orm import ArrayData, Dict, Float, Int, List, SinglefileData, Str
-from plumpy.utils import AttributesFrozendict
+from aiida.orm import Dict, Float, Int, List, SinglefileData, Str
+from h5py import File as h5File
-from aiida_fans.helpers import InputEncoder
+from aiida_fans.helpers import make_input_dict
-class FANSCalculation(CalcJob):
- """AiiDA calculation plugin wrapping the FANS executable."""
-
- @staticmethod
- def __input_validator_selector(input: str, note: str) -> Callable[[Any, Any], str | None]:
- validators: dict[str, Callable[[Any, Any], str | None]] = {
- "microstructure.file": lambda _i, _p: None,
- "microstructure.datasetname": lambda _i, _p: None,
- "microstructure.L": lambda i, _p: note if len(i) != 3 else None, # TODO: check elements are numbers
- "problem_type": lambda i, _p: note if i.value not in {"thermal", "mechanical"} else None,
- "matmodel": lambda i, _p: note
- if i.value
- not in {
- "LinearThermalIsotropic",
- "LinearElasticIsotropic",
- "PseudoPlasticLinearHardening",
- "PseudoPlasticNonLinearHardening",
- "J2ViscoPlastic_LinearIsotropicHardening",
- "J2ViscoPlastic_NonLinearIsotropicHardening",
- }
- else None,
- "material_properties": lambda _i, _p: None, # TODO: material properties
- "method": lambda i, _p: note if i.value not in {"cg", "fp"} else None,
- "error_parameters.measure": lambda i, _p: note if i.value not in {"Linfinity", "L1", "L2"} else None,
- "error_parameters.type": lambda i, _p: note if i.value not in {"absolute", "relative"} else None,
- "error_parameters.tolerance": lambda _i, _p: None,
- "n_it": lambda _i, _p: None,
- "macroscale_loading": lambda _i, _p: None, # TODO: macroscale loading
- "results": lambda i, _p: note
- if not set(i.get_list())
- <= {
- "stress_average",
- "strain_average",
- "absolute_error",
- "phase_stress_average",
- "phase_strain_average",
- "microstructure",
- "displacement",
- "stress",
- "strain",
- }
- else None,
- }
- return validators[input]
+class FansCalcBase(CalcJob):
+ """Base class of all calculations using FANS."""
@classmethod
def define(cls, spec: CalcJobProcessSpec) -> None:
- """Define inputs, outputs, and exit_codes of the calculation."""
+ """Define inputs, outputs, and exit codes of the calculation."""
super().define(spec)
- # Metadata
+ # Default Metadata
+ spec.inputs["metadata"]["label"].default = "FANS"
+ ## Processing Power
+ spec.inputs["metadata"]["options"]["withmpi"].default = True
spec.inputs["metadata"]["options"]["resources"].default = {
"num_machines": 1,
- "num_mpiprocs_per_machine": 4,
+ "num_mpiprocs_per_machine": 4
}
- spec.inputs["metadata"]["options"]["withmpi"].default = True
- spec.inputs["metadata"]["options"]["parser_name"].default = "fans"
+ ## Filenames
spec.inputs["metadata"]["options"]["input_filename"].default = "input.json"
spec.inputs["metadata"]["options"]["output_filename"].default = "output.h5"
+ ## Parser
+ spec.inputs["metadata"]["options"]["parser_name"].default = "fans"
- # New Ports:
- spec.input_namespace("microstructure", help=(note := "The microstructure definition."))
- spec.input(
- (input := "microstructure.file"),
- valid_type=SinglefileData,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "This specifies the path to the HDF5 file that contains the microstructure data."),
- )
- spec.input(
- (input := "microstructure.datasetname"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "This is the path within the HDF5 file to the specific dataset that represents the microstructure."
- ),
- )
- spec.input(
- (input := "microstructure.L"),
- valid_type=List,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "Microstructure length defines the physical dimensions of the microstructure in the x, y, and z directions." # noqa: E501
- ),
- )
-
- spec.input(
- (input := "problem_type"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "This defines the type of physical problem you are solving. Common options include `thermal` problems and `mechanical` problems." # noqa: E501
- ),
- )
- spec.input(
- (input := "matmodel"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "This specifies the material model to be used in the simulation."),
- )
- spec.input(
- (input := "material_properties"),
- valid_type=Dict,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "This provides the necessary material parameters for the chosen material model."),
- )
- spec.input(
- (input := "method"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "This indicates the numerical method to be used for solving the system of equations. `cg` stands for the Conjugate Gradient method, and `fp` stands for the Fixed Point method." # noqa: E501
- ),
- )
-
- spec.input_namespace(
- "error_parameters",
- help=(
- note
- := "This section defines the error parameters for the solver. Error control is applied on the finite element nodal residual of the problem." # noqa: E501
- ),
- )
- spec.input(
- (input := "error_parameters.measure"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "Specifies the norm used to measure the error. Options include `Linfinity`, `L1`, or `L2`."),
- )
- spec.input(
- (input := "error_parameters.type"),
- valid_type=Str,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "Defines the type of error measurement. Options are `absolute` or `relative`."),
- )
- spec.input(
- (input := "error_parameters.tolerance"),
- valid_type=Float,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "Sets the tolerance level for the solver, defining the convergence criterion based on the chosen error measure. The solver iterates until the solution meets this tolerance." # noqa: E501
- ),
- )
-
- spec.input(
- (input := "n_it"),
- valid_type=Int,
- validator=cls.__input_validator_selector(input, note),
- help=(note := "Specifies the maximum number of iterations allowed for the FANS solver."),
- )
- spec.input(
- (input := "macroscale_loading"),
- valid_type=ArrayData,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "This defines the external loading applied to the microstructure. It is an array of arrays, where each sub-array represents a loading condition applied to the system. The format of the loading array depends on the problem type." # noqa: E501
- ),
- )
- spec.input(
- (input := "results"),
- valid_type=List,
- validator=cls.__input_validator_selector(input, note),
- help=(
- note
- := "This array lists the quantities that should be stored into the results HDF5 file during the simulation." # noqa: E501
- ),
- )
-
- spec.output("results", valid_type=SinglefileData)
-
- # Exit Codes:
+ # Custom Metadata
+ spec.input("metadata.options.results_prefix", valid_type=str, default="")
+ spec.input("metadata.options.results", valid_type=list, default=[])
+
+ # Input Ports
+ ## Microstructure Definition
+ spec.input_namespace("microstructure")
+ spec.input("microstructure.file", valid_type=SinglefileData)
+ spec.input("microstructure.datasetname", valid_type=Str)
+ spec.input("microstructure.L", valid_type=List)
+ ## Problem Type and Material Model
+ spec.input("problem_type", valid_type=Str)
+ spec.input("matmodel", valid_type=Str)
+ spec.input("material_properties", valid_type=Dict)
+ ## Solver Settings
+ spec.input("method", valid_type=Str)
+ spec.input("n_it", valid_type=Int)
+ spec.input_namespace("error_parameters")
+ spec.input("error_parameters.measure", valid_type=Str)
+ spec.input("error_parameters.type", valid_type=Str)
+ spec.input("error_parameters.tolerance", valid_type=Float)
+ ## Macroscale Loading Conditions
+ spec.input("macroscale_loading", valid_type=List)
+
+ # Output Ports
+ spec.output("output", valid_type=SinglefileData)
+ spec.output("results", valid_type=Dict, required=False)
+
+ # Exit Codes
spec.exit_code(400, "PLACEHOLDER", "This is an error code, yet to be implemented.")
def prepare_for_submission(self, folder: Folder) -> CalcInfo:
- """Creates the input file required by the calculation.
-
- Args:
- folder (Folder): where the plugin should temporarily place all files needed by the calculation
-
- Returns:
- CalcInfo: the data to be passed to the ExecManager
- """
- # Write Microstructure Subset to Folder
- datasetname : str = self.inputs.microstructure.datasetname.value
- with folder.open("microstructure.h5","bw") as f_dest:
- with h5py.File(f_dest,"w") as h5_dest:
- with self.inputs.microstructure.file.open(mode="rb") as f_src:
- with h5py.File(f_src,'r') as h5_src:
- h5_src.copy(datasetname, h5_dest, name=datasetname)
-
- # Write input.json to Folder
- json_to_be = dict(self.inputs)
- del json_to_be["code"], json_to_be["metadata"]
- to_fix = {}
- for key, value in json_to_be.items():
- if isinstance(value, AttributesFrozendict): # can be moved to InputEncoder?
- to_fix[key] = {}
- for k, v in json_to_be[key].items():
- to_fix[key][k] = v
- json_to_be = json_to_be | to_fix
-
- to_add = {}
- for key, value in json_to_be.items():
- if key == "microstructure":
- for k, v in value.items():
- if k == "file":
- to_add[f"ms_{k}name"] = "microstructure.h5"
- else:
- to_add[f"ms_{k}"] = v
-
- json_to_be = to_add | json_to_be
- del json_to_be["microstructure"]
-
- with folder.open(self.options.input_filename, "w", "utf8") as handle:
- dump(json_to_be, handle, cls=InputEncoder, indent=4)
-
- # Specifying code info.
+ """Prepare the calculation for submission."""
+ # Specifying the code info:
codeinfo = CodeInfo()
codeinfo.code_uuid = self.inputs.code.uuid
- codeinfo.stdout_name = self.options.input_filename + ".log"
- codeinfo.stderr_name = self.options.input_filename + ".err"
+ codeinfo.stdout_name = self.metadata.label + ".log"
+ codeinfo.stderr_name = self.metadata.label + ".err"
codeinfo.cmdline_params = [self.options.input_filename, self.options.output_filename]
- # Specifying calc info.
+ # Specifying the calc info:
calcinfo = CalcInfo()
calcinfo.codes_info = [codeinfo]
calcinfo.local_copy_list = []
calcinfo.remote_copy_list = []
- calcinfo.retrieve_list = [
- self.options.input_filename + ".log",
- self.options.input_filename + ".err",
- ]
+ calcinfo.retrieve_list = [codeinfo.stdout_name, codeinfo.stderr_name]
calcinfo.retrieve_temporary_list = [
self.options.output_filename
]
- calcinfo.provenance_exclude_list = [
- "microstructure.h5"
- ]
return calcinfo
+
+
+class FansStashedCalculation(FansCalcBase):
+ """Calculations using FANS and the "Stashed" microstructure distribution strategy."""
+
+ @classmethod
+ def define(cls, spec: CalcJobProcessSpec) -> None:
+ """Define inputs, outputs, and exit codes of the calculation."""
+ return super().define(spec)
+
+ def prepare_for_submission(self, folder: Folder) -> CalcInfo:
+ """Prepare the calculation for submission."""
+ ms_filepath: Path = Path(self.inputs.code.computer.get_workdir()) / \
+ "stash/microstructures" / \
+ self.inputs.microstructure.file.filename
+ # if microstructure does not exist in stash, make it
+ if not ms_filepath.is_file():
+ ms_filepath.parent.mkdir(parents=True, exist_ok=True)
+ with self.inputs.microstructure.file.open(mode='rb') as source:
+ with ms_filepath.open(mode='wb') as target:
+ copyfileobj(source, target)
+
+ # input.json as dict
+ input_dict = make_input_dict(self)
+ input_dict["microstructure"]["filepath"] = str(ms_filepath)
+ # write input.json to working directory
+ with folder.open(self.options.input_filename, "w", "utf8") as json:
+ dump(input_dict, json, indent=4)
+
+ return super().prepare_for_submission(folder)
+
+class FansFragmentedCalculation(FansCalcBase):
+ """Calculations using FANS and the "Fragmented" microstructure distribution strategy."""
+
+ @classmethod
+ def define(cls, spec: CalcJobProcessSpec) -> None:
+ """Define inputs, outputs, and exit codes of the calculation."""
+ return super().define(spec)
+
+ def prepare_for_submission(self, folder: Folder) -> CalcInfo:
+ """Prepare the calculation for submission."""
+ # Write Microstructure Subset to Folder
+ datasetname : str = self.inputs.microstructure.datasetname.value
+ with folder.open("microstructure.h5","bw") as f_dest:
+ with h5File(f_dest,"w") as h5_dest:
+ with self.inputs.microstructure.file.open(mode="rb") as f_src:
+ with h5File(f_src,'r') as h5_src:
+ h5_src.copy(datasetname, h5_dest, name=datasetname)
+
+ # input.json as dict
+ input_dict = make_input_dict(self)
+ input_dict["microstructure"]["filepath"] = "microstructure.h5"
+ # write input.json to working directory
+ with folder.open(self.options.input_filename, "w", "utf8") as json:
+ dump(input_dict, json, indent=4)
+
+ return super().prepare_for_submission(folder)
diff --git a/src/aiida_fans/helpers.py b/src/aiida_fans/helpers.py
index 2dad749..f527c54 100644
--- a/src/aiida_fans/helpers.py
+++ b/src/aiida_fans/helpers.py
@@ -1,26 +1,41 @@
-"""Tools and utilities required by aiida_fans."""
+"""Tools required by aiida-fans."""
-import json
+from typing import Any
-from aiida.orm import ArrayData, Dict, Float, Int, List, SinglefileData, Str
+from aiida.engine import CalcJob
+from numpy import allclose, ndarray
-class InputEncoder(json.JSONEncoder):
- """Prepares a dictionary of calcjob inputs for json representation."""
+def make_input_dict(job: CalcJob) -> dict[str, Any]:
+ """Prepares a dictionary that maps to an input.json from calcjob inputs."""
+ return {
+ ## Microstructure Definition
+ "microstructure": {
+ "filepath": None, # path to stashed microstructure, must be overwritten by impl
+ "datasetname": job.inputs.microstructure.datasetname.value,
+ "L": job.inputs.microstructure.L.get_list()
+ },
+ "results_prefix": job.inputs.metadata.options.results_prefix,
+ ## Problem Type and Material Model
+ "problem_type": job.inputs.problem_type.value,
+ "matmodel": job.inputs.matmodel.value,
+ "material_properties": job.inputs.material_properties.get_dict(),
+ ## Solver Settings
+ "method": job.inputs.method.value,
+ "n_it": job.inputs.n_it.value,
+ "error_parameters": {
+ "measure": job.inputs.error_parameters.measure.value,
+ "type": job.inputs.error_parameters.type.value,
+ "tolerance": job.inputs.error_parameters.tolerance.value
+ },
+ ## Macroscale Loading Conditions
+ "macroscale_loading": job.inputs.macroscale_loading.get_list(),
+ ## Results Specification
+ "results": job.inputs.metadata.options.results
+ }
- def default(self, obj):
- """Converts aiida datatypes to their python counterparts."""
- match obj:
- case Str() | Int() | Float():
- return obj.value
- case List():
- return obj.get_list()
- case Dict():
- return obj.get_dict()
- case ArrayData():
- return [a[1].tolist() for a in obj.get_iterarrays()] #! Caution: may be disordered
- case SinglefileData():
- return obj.filename
- case _:
- # Let the base class default method raise the TypeError
- return super().default(obj)
+def arraydata_equal(first: dict[str, ndarray], second: dict[str, ndarray]) -> bool:
+ """Return whether two dicts of arrays are roughly equal."""
+ if first.keys() != second.keys():
+ return False
+ return all(allclose(first[key], second[key]) for key in first)
diff --git a/src/aiida_fans/parsers.py b/src/aiida_fans/parsers.py
index 4e01788..f755ba8 100644
--- a/src/aiida_fans/parsers.py
+++ b/src/aiida_fans/parsers.py
@@ -1,43 +1,56 @@
-"""Parsers provided by aiida_fans."""
+"""Parser subclass for aiida-fans calculations."""
from pathlib import Path
from aiida.engine import ExitCode
-from aiida.orm import SinglefileData
+from aiida.orm import CalcJobNode, Dict, SinglefileData
from aiida.parsers.parser import Parser
-from aiida.plugins import CalculationFactory
+from h5py import Dataset, Group
+from h5py import File as h5File
-FANSCalculation = CalculationFactory("fans")
+class FansParser(Parser):
+ """Extracts data from FANS results."""
-class FANSParser(Parser):
- """Extracts valuable data from FANS results."""
+ def __init__(self, node: CalcJobNode):
+ """Calls `super().__init__()` then defines `self.results_dict`."""
+ super().__init__(node)
+ self.results_dict = dict()
- def parse(self, **kwargs) -> ExitCode:
- """Parse outputs, store results in database.
-
- Returns:
- ExitCode: non-zero exit code, if parsing fails
- """
- retrieved_temporary_folder = Path(kwargs["retrieved_temporary_folder"])
- output_filename = self.node.get_option("output_filename")
-
- # Check that output_filename is valid
- if (type(output_filename) is not str) or (output_filename == ""):
- return self.exit_codes.ERROR_INVALID_OUTPUT
-
- # Check that folder content is as expected.
- files_retrieved = set(self.retrieved.list_object_names())
- files_expected = set()#{output_filename}
- if not files_expected <= files_retrieved:
- self.logger.error(f"Found files '{files_retrieved}', expected to find '{files_expected}'")
+ def parse(self, **kwargs) -> ExitCode | None:
+ """Parse outputs and store results as nodes."""
+ output_path: Path = Path(kwargs["retrieved_temporary_folder"]) / self.node.get_option("output_filename") # type: ignore
+ if output_path.is_file():
+ self.out("output", node=SinglefileData(output_path))
+ else:
return self.exit_codes.ERROR_MISSING_OUTPUT
- # Add output HDF5 file to repository.
- output_path = retrieved_temporary_folder / output_filename
- self.logger.info(f"Parsing '{output_path}'")
- with output_path.open("rb") as handle:
- output_node = SinglefileData(file=handle)
- self.out("results", output_node)
-
- return ExitCode(0)
+ with h5File(output_path) as h5:
+ results = h5[
+ self.node.inputs.microstructure.datasetname.value + \
+ "_results/" + \
+ self.node.get_option('results_prefix')
+ ]
+ results.visititems(self.parse_h5)
+
+ if self.results_dict:
+ self.out("results", Dict(self.results_dict))
+
+ def parse_h5(self, name: str, object: Group | Dataset) -> None:
+ """Callable for the .visititems method of h5py Groups."""
+ if isinstance(object, Group):
+ return
+ if "average" in name:
+ keys = name.split("/")
+ res = self.results_dict
+ data = list(object[:])
+ self.nestle(res, keys, data)
+
+ def nestle(self, bottom: dict, layers: list[str], top: list[float]) -> None:
+ """Recursive function to generate a nested results dictionary."""
+ layer = layers.pop(0)
+ if len(layers) > 0:
+ bottom.setdefault(layer, dict())
+ self.nestle(bottom[layer], layers, top)
+ else:
+ bottom[layer] = top
diff --git a/src/aiida_fans/utils.py b/src/aiida_fans/utils.py
new file mode 100644
index 0000000..6aa478a
--- /dev/null
+++ b/src/aiida_fans/utils.py
@@ -0,0 +1,218 @@
+"""Utilities provided by aiida_fans."""
+
+from typing import Any, Literal
+
+from aiida.engine import run, submit
+from aiida.orm import CalcJobNode, Data, Node, QueryBuilder
+from aiida.plugins import CalculationFactory, DataFactory
+from numpy import ndarray
+
+from aiida_fans.helpers import arraydata_equal
+
+
+def aiida_type(value: Any) -> type[Data]:
+ """Find the corresponding AiiDA datatype for a variable with pythonic type.
+
+ Args:
+ value (Any): a python variable
+
+ Raises:
+ NotImplementedError: only certain mappings are supported
+
+ Returns:
+ type[Data]: an AiiDA data type
+ """
+ match value:
+ case str():
+ return DataFactory("core.str") # Str
+ case int():
+ return DataFactory("core.int") # Int
+ case float():
+ return DataFactory("core.float") # Float
+ case list():
+ return DataFactory("core.list") # List
+ case dict():
+ if all(map(lambda t: isinstance(t, ndarray), value.values())):
+ return DataFactory("core.array") # ArrayData
+ else:
+ return DataFactory("core.dict") # Dict
+ case _:
+ raise NotImplementedError(f"Received an input of value: {value} with type: {type(value)}")
+
+def fetch(label: str, value: Any) -> list[Node]:
+ """Return a list of nodes matching the label and value provided.
+
+ Args:
+ label (str): the label of the node to fetch
+ value (Any): the value of the node to fetch
+
+ Returns:
+ list[Node]: the list of nodes matching the give criteria
+ """
+ datatype = aiida_type(value)
+ nodes = QueryBuilder(
+ ).append(cls=datatype, tag="n"
+ ).add_filter("n", {"label": label}
+ ).add_filter("n", {"attributes": {"==": datatype(value).base.attributes.all}}
+ ).all(flat=True)
+
+ if datatype != DataFactory("core.array"):
+ return nodes # type: ignore
+ else:
+ array_nodes = []
+ for array_node in nodes:
+ array_value = {
+ k: v for k, v in [
+ (name, array_node.get_array(name)) for name in array_node.get_arraynames() # type: ignore
+ ]
+ }
+ if arraydata_equal(value, array_value):
+ array_nodes.append(array_node)
+ return array_nodes
+
+def generate(label: str, value: Any) -> Node:
+ """Return a single node with the label and value provided.
+
+ Uses an existing node when possible, but otherwise creates one instead.
+
+ Args:
+ label (str): the label of the node to generate
+ value (Any): the pythonic value of the node to generate
+
+ Raises:
+ RuntimeError: panic if more than one node is found matching the criteria
+
+ Returns:
+ Node: a stored node with label and value
+ """
+ bone = fetch(label, value)
+ if len(bone) == 0:
+ return aiida_type(value)(value, label=label).store()
+ elif len(bone) == 1:
+ return bone.pop()
+ else:
+ raise RuntimeError
+
+def convert(ins: dict[str, Any], path: list[str] = []):
+ """Takes a dictionary of inputs and converts the values to their respective Nodes.
+
+ Args:
+ ins (dict[str, Any]): a dictionary of inputs
+ path (list[str], optional): a list of predecessor keys for nested dictionaries. Defaults to [].
+ """
+ for k, v in ins.items():
+ if k == "metadata" or isinstance(v, Node):
+ continue
+ if k in ["microstructure", "error_parameters"]:
+ convert(v, path=[*path, k])
+ else:
+ ins[k] = generate(".".join([*path, k]), v)
+
+def compile_query(ins: dict[str,Any], qb: QueryBuilder) -> None:
+ """Interate over the converted input dictionary and append to the QueryBuilder for each node.
+
+ Args:
+ ins (dict[str,Any]): a dictionary of converted inputs
+ qb (QueryBuilder): a CalcJobNode QueryBuilder with tag='calc'
+ """
+ for k, v in ins.items():
+ if k == "metadata":
+ continue
+ if k in ["microstructure", "error_parameters"] and isinstance(v, dict):
+ compile_query(v, qb)
+ else:
+ qb.append(
+ cls=type(v),
+ with_outgoing="calc",
+ filters={"pk": v.pk}
+ )
+
+
+def execute_fans(
+ mode: Literal["Submit", "Run"],
+ inputs: dict[str, Any],
+ strategy: Literal["Fragmented", "Stashed"] = "Fragmented",
+ ):
+ """This utility function simplifies the process of executing aiida-fans jobs.
+
+ The only nodes you must provide are the `code` and `microstructure` inputs.
+ Other inputs can be given as standard python variables. Your repository will
+ be automatically scanned for equivalent nodes. These will be used whenever
+ possible, otherwise new nodes will be created.
+
+ The `strategy` specifies which microstructure distribution method you wish to use.
+ It defaults to "Fragmented".
+
+ You must load an AiiDA profile yourself before using this function.
+
+ **Args:**
+ **mode** *(Literal["Submit", "Run"])*
+ **inputs** *(dict[str, Any])*
+ **strategy** *(Literal["Fragmented", "Stashed"]), optional*
+
+ ---
+
+ **Example:**
+ ```
+ from aiida import load_profile
+ from aiida.orm import load_code, load_node
+ from aiida_fans.utils import execute_fans
+ load_profile()
+ inputs = {
+ "code": load_code("fans"),
+ "microstructure": load_node(label="microstructure"),
+ ...
+ "metadata": {
+ "label": "an example calculation"
+ }
+ }
+ execute_fans("Submit", inputs, "Stashed")
+ ```
+ """
+ # update inputs with metadata.options.stash if necessary:
+ match strategy:
+ case "Stashed":
+ calcjob = CalculationFactory("fans.stashed")
+ case "Fragmented":
+ calcjob = CalculationFactory("fans.fragmented")
+ case _:
+ print("ERROR: Calculation strategy must be either 'Fragmented' or 'Stashed'.")
+ raise ValueError
+
+ # move results_prefix and results items to metadata.options
+ inputs.setdefault("metadata", {}).setdefault("options", {})["results_prefix"] = inputs.pop("results_prefix", "")
+ inputs.setdefault("metadata", {}).setdefault("options", {})["results"] = inputs.pop("results", [])
+
+ # fetch the inputs if possible or otherwise create them
+ convert(inputs)
+
+ # check if identical calculation already exists
+ qb = QueryBuilder().append(cls=CalcJobNode, tag="calc", project="id")
+ compile_query(inputs, qb)
+ results = qb.all(flat=True)
+ if (count := len(results)) != 0:
+ print(f"It seems this calculation has already been performed {count} time{"s" if count > 1 else ""}. {results}")
+ confirmation = input("Are you sure you want to rerun it? [y/N] ").strip().lower() in ["y", "yes"]
+ else:
+ confirmation = True
+
+ if confirmation:
+ match mode:
+ case "Run":
+ run(calcjob, inputs) # type: ignore
+ case "Submit":
+ submit(calcjob, inputs) # type: ignore
+
+def submit_fans(
+ inputs: dict[str, Any],
+ strategy: Literal["Fragmented", "Stashed"] = "Fragmented",
+):
+ """See `execute_fans` for implementation and usage details."""
+ execute_fans("Submit", inputs, strategy)
+
+def run_fans(
+ inputs: dict[str, Any],
+ strategy: Literal["Fragmented", "Stashed"] = "Fragmented",
+):
+ """See `execute_fans` for implementation and usage details."""
+ execute_fans("Run", inputs, strategy)
diff --git a/tutorial/README.md b/tutorial/README.md
new file mode 100644
index 0000000..9882601
--- /dev/null
+++ b/tutorial/README.md
@@ -0,0 +1,59 @@
+# aiida-fans-tutorial
+Learn how to use aiida-fans in this marimo powered tutorial.
+
+## Usage
+
+Assuming you have FANS, python 3.13, venv, and pip installed on a linux system, the recommended way to use this tutorial is by creating a virtual environment in this directory with the following command:
+
+```
+python -m venv .venv
+```
+Then activate this environment like so:
+
+```
+source .venv/bin/activate
+```
+
+You can ensure the the environment was succesfully activated with `which python` and ultimately deactivate the environment with `deactivate` when you're finished.
+
+You may need to install/upgrade pip now with your virtual environment activated. Run the following command:
+
+```
+python -m pip install --upgrade pip
+```
+
+Once pip is up to date, run the following command to install the tutorial's dependencies:
+
+```
+python -m pip install -r requirements.txt
+```
+
+Now you are ready to launch the notebook and begin the tutorial. Run the following command and access the marimo notebook at the port provided:
+
+```
+marimo run tutorial.py
+```
+
+## Alternative Usage
+
+### 1. Conda
+
+> [!WARNING]
+> This method is a work-in-progress!
+
+### 2. Pixi
+
+> [!WARNING]
+> This method is a work-in-progress!
+
+You can use pixi to install everything you need as defined by the pyproject.toml file. It should bundle python, FANS, AiiDA, aiida-fans, and marimo all into a virtual environment located in a .pixi directory. You can proceed to directly begin the tutorial with:
+
+```
+marimo run tutorial.py
+```
+
+Activating the environment may look something like this:
+
+```
+pixi shell --manifest-path ~/FANS/tutorial/pyproject.toml
+```
diff --git a/tutorial/tutorial.py b/tutorial/tutorial.py
new file mode 100644
index 0000000..be2abc6
--- /dev/null
+++ b/tutorial/tutorial.py
@@ -0,0 +1,1386 @@
+
+
+import marimo
+
+__generated_with = "0.13.0"
+app = marimo.App(app_title="AiiDA-FANS Tutorial")
+
+
+@app.cell(hide_code=True)
+def _():
+ import marimo as mo
+ from pathlib import Path
+ return Path, mo
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ nav_menu = mo.nav_menu(
+ {
+ "#aiida-setup": "AiiDA Setup",
+ "#fans-rundown": "FANS Rundown",
+ "#submitting-jobs": "Submitting Jobs",
+ "#analysing-the-results": "Analysing the Results",
+ "Links": {
+ "https://github.com/ethan-shanahan/aiida-fans": "aiida-fans",
+ "https://github.com/DataAnalyticsEngineering/FANS": "FANS",
+ "https://www.aiida.net/": "AiiDA",
+ },
+ }
+ )
+
+ _tip = mo.md("""
+ **Requirements:**
+
+ The rest of this tutorial assumes you have read the attached README and have installed the requirements described therein. Although not foolproof, you can run the following commands to check if AiiDA, the plugin, and FANS are installed correctly.
+
+ ```
+ verdi plugin list aiida.calculations fans
+ FANS
+ ```
+
+ Notice that we assume FANS is located on your PATH (or at least it is in your active environment). While this is not necessary in general practice, the tutorial will continue under this assumption.
+ """).callout("warn")
+
+ mo.md(rf"""{nav_menu}
+
+ ---
+
+ # AiiDA-FANS Tutorial
+
+ The goal of this tutorial is to give you an idea of how to utilise the `aiida-fans` plugin as well as an introduction to `AiiDA` and `FANS`. By the end of this tutorial, you should know how to:
+
+ - Setup your AiiDA profile, computer, and code.
+ - Define FANS options and prepare a parameter space study.
+ - Write a `submit.py` script to run your jobs.
+ - Query and read the results.
+
+ {_tip}
+ """)
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ _note = mo.md(r"""
+ **Note:** _not your first profile..._
+
+ This section assumes you have not already set up an appropriate profile, computer, and code for using AiiDA and FANS. If you have already done this, you may wish to skip to the next section.
+
+ However, this tutorial is designed to work with a blank profile specifically.
+ """).callout("info")
+
+ mo.md(rf"""
+ ## AiiDA Setup
+
+ Before we can truly begin, we must set up AiiDA on your machine. This means three things.
+
+ 1. Create a Profile
+ 2. Specify a Computer
+ 3. Define a Code
+
+ AiiDA has multiple user interfaces but their CLI, `verdi`, is particularly well suited to these three steps since they need to be performed only rarely. Therefore, you will need access to the terminal to proceed.
+
+ {_note}
+ """)
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ### 1. Create a Profile
+
+ By default, AiiDA stores app data at the user level. Even when AiiDA is installed in a virtual environment, it will still read and write to `.aiida` in your home directory. However, AiiDA provides users a way to seperate their data into "profiles". Let's create a profile for this tutorial.
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ profile_settings = mo.hstack(
+ [
+ mo.vstack([
+ "Profile Name:",
+ "First Name:",
+ "Last Name:",
+ "Email:",
+ "Institution:",
+ ], align="start", heights="equal", gap=0.8),
+ mo.vstack([
+ "{profile_name}",
+ "{first_name}",
+ "{last_name}",
+ "{email}",
+ "{institution}",
+ ], align="start", heights="equal", gap=0.5)
+ ],
+ justify="center", align="stretch", gap=2.0,
+ ).batch(
+ profile_name=mo.ui.text("aiida-fans-tutorial"),
+ first_name=mo.ui.text("Max"),
+ last_name=mo.ui.text("Mustermann"),
+ email=mo.ui.text("example@nomail.com"),
+ institution=mo.ui.text("MIB"),
+ ).form(
+ show_clear_button=True, clear_button_label="Reset", bordered=True
+ )
+
+ mo.vstack([
+ mo.md("**Fill in the details below to generate your custom profile configuration.**"),
+ profile_settings
+ ], align="center")
+ return (profile_settings,)
+
+
+@app.cell(hide_code=True)
+def _(mo, profile_settings):
+ mo.stop(
+ profile_settings.value is None,
+ mo.status.spinner(title="Awaiting input above ...", remove_on_exit=False)
+ )
+
+ profile_config = \
+ rf"""profile: {profile_settings.value["profile_name"]}
+ first_name: {profile_settings.value["first_name"]}
+ last_name: {profile_settings.value["last_name"]}
+ email: {profile_settings.value["email"]}
+ institution: {profile_settings.value["institution"]}
+ use_rabbitmq: false
+ set_as_default: true
+ non_interactive: true
+ """
+
+ with open("configure_profile.yaml", "w") as _f:
+ _f.write(profile_config)
+
+ mo.md(f"""
+ With the values you input above, a `configure_profile.yaml` has been automatically written to the working directory. It contains the following data:
+
+ ```yaml
+ {profile_config}
+ ```
+ """).callout(kind="success")
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo, profile_settings):
+ _note = mo.md(rf"""
+ **Note:** _on default profiles..._
+
+ We have made the new profile our default profile. This means that any further calls to `verdi` will implicitly use the {"" if profile_settings.value is None else profile_settings.value["profile_name"]} profile. You can change the profile on a per-call basis with the `-p/--profile` option. To change the default profile use:
+
+ ```
+ verdi profile set-default
+ ```
+ """).callout(kind="info")
+
+ mo.md(f"""
+ To create your new profile from this file run:
+
+ ```
+ verdi profile setup core.sqlite_dos --config configure_profile.yaml
+ ```
+
+ Hopefully, that completed successfully. Using these commands, you should see your new profile listed (alone if this is your first profile) and a report on it also:
+
+ ```
+ verdi profile list
+ verdi profile show {"" if profile_settings.value is None else profile_settings.value["profile_name"]}
+ ```
+
+ {_note}
+ """)
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ### 2. Specify a Computer
+
+ Before you proceed, ensure that your local computer satisfies the following requirements:
+
+ - it runs a Unix-like operating system (Linux distros and MacOS should work fine)
+ - it has `bash` installed
+
+ AiiDA does not assume what computer you wish to run jobs on, so even if you are only using your local machine, you must tell it as much. That is what we will do here; specify the localhost computer.
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ computer_settings = mo.hstack(
+ [
+ mo.vstack([
+ "Computer Label:",
+ "MPI processes:",
+ "Description:",
+ ], align="start", heights="equal", gap=0.8),
+ mo.vstack([
+ "{label}",
+ "{mpiprocs}",
+ "{description}",
+ ], align="start", heights="equal", gap=0.5)
+ ],
+ justify="center", align="stretch", gap=2.0,
+ ).batch(
+ label=mo.ui.text("localhost"),
+ mpiprocs=mo.ui.text("2"),
+ description=mo.ui.text_area("This is my local machine."),
+ ).form(
+ show_clear_button=True, clear_button_label="Reset", bordered=True
+ )
+
+ mo.vstack([
+ mo.md("**Fill in the details below to generate your custom computer configuration.**"),
+ computer_settings
+ ], align="center")
+ return (computer_settings,)
+
+
+@app.cell(hide_code=True)
+def _(Path, computer_settings, mo):
+ mo.stop(
+ computer_settings.value is None,
+ mo.status.spinner(title="Awaiting input above ...", remove_on_exit=False)
+ )
+
+ computer_config = \
+ rf"""label: {computer_settings.value["label"]}
+ description: {computer_settings.value["description"]}
+ hostname: localhost
+ transport: core.local
+ scheduler: core.direct
+ shebang: #!/bin/bash
+ work_dir: {Path.cwd()}/.aiida_run""" + r"""
+ mpirun_command: mpiexec -n {tot_num_mpiprocs}""" + rf"""
+ mpiprocs_per_machine: {computer_settings.value["mpiprocs"]}
+ default_memory_per_machine: null
+ use_double_quotes: false
+ prepend_text: ' '
+ append_text: ' '
+ non_interactive: true
+ """
+
+ with open("configure_computer.yaml", "w") as _f:
+ _f.write(computer_config)
+
+ mo.md(f"""
+ With the values you input above, a `configure_computer.yaml` has been automatically written to the working directory. It contains the following data:
+
+ ```yaml
+ {computer_config}
+ ```
+ """).callout(kind="success")
+ return
+
+
+@app.cell(hide_code=True)
+def _(computer_settings, mo):
+ mo.md(rf"""
+ To specify your new computer from this file run:
+
+ ```
+ verdi computer setup --config configure_computer.yaml
+ ```
+
+ Then you must configure the computer with the following command:
+
+ ```
+ verdi computer configure core.local {"" if computer_settings.value is None else computer_settings.value["label"]}
+ ```
+
+ The default options should be suitable.
+
+ Hopefully, that completed successfully. Using this command, you should test that AiiDA can connect to the machine:
+
+ ```
+ verdi computer test {"" if computer_settings.value is None else computer_settings.value["label"]}
+ ```
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ### 3. Define a Code
+
+ The final step to setup AiiDA is to define the "code" you wish to utilise. Here, the "code" refers to FANS. This step is important as it tells AiiDA how to execute FANS and which plugin should handle its jobs. AiiDA provides many ways of handling the "code" of your project. Since we installed FANS in the environment, we can simply make use of it there.
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ code_settings = mo.hstack(
+ [
+ mo.vstack([
+ mo.vstack([
+ "Code Label:",
+ "Code Executable:",
+ "Description:",
+ ], align="start", heights="equal", gap=0.8),
+ "Environment Activation Script:",
+ ], align="start", heights="equal", gap=5.55),
+ mo.vstack([
+ "{label}",
+ "{executable}",
+ "{description}",
+ "{environment}",
+ ], align="start", heights="equal", gap=0.5)
+ ],
+ justify="center", align="stretch", gap=2.0,
+ ).batch(
+ label=mo.ui.text("FANS"),
+ executable=mo.ui.text("FANS"),
+ description=mo.ui.text_area("The FANS executable."),
+ environment=mo.ui.text_area("eval \"$(conda shell.bash hook)\"\nconda activate aiida-fans-tutorial"),
+ ).form(
+ show_clear_button=True, clear_button_label="Reset", bordered=True
+ )
+
+ mo.vstack([
+ mo.md("**Fill in the details below to generate your custom code configuration.**"),
+ code_settings
+ ], align="center")
+ return (code_settings,)
+
+
+@app.cell(hide_code=True)
+def _(code_settings, computer_settings, mo):
+ mo.stop(
+ code_settings.value is None or computer_settings.value is None,
+ mo.status.spinner(title="Awaiting input above ...", remove_on_exit=False)
+ )
+
+ code_config = \
+ rf"""label: {code_settings.value["label"]}
+ description: {code_settings.value["description"]}
+ default_calc_job_plugin: fans
+ use_double_quotes: false
+ with_mpi: true
+ computer: {computer_settings.value["label"]}
+ filepath_executable: {code_settings.value["executable"]}
+ prepend_text: |
+ {"\n".join([f" {ln}" for ln in code_settings.value["environment"].split("\n")])}
+ append_text: ' '
+ non_interactive: true
+ """
+
+ with open("configure_code.yaml", "w") as _f:
+ _f.write(code_config)
+
+ mo.md(f"""
+ With the values you input above, a `configure_code.yaml` has been automatically written to the working directory. It contains the following data:
+
+ ```yaml
+ {code_config}
+ ```
+ """).callout(kind="success")
+ return
+
+
+@app.cell(hide_code=True)
+def _(code_settings, mo):
+ _note = mo.md(r"""
+ **Note:** _your first node..._
+
+ You should also note that the code is saved by AiiDA as a node, and thus we have created our first node. Any calculation jobs we perform will be connected to this code node in the provenance graph.
+
+ To list all the nodes stored in your profile, run:
+
+ ```
+ verdi node list
+ ```
+ """).callout(kind="info")
+
+ mo.md(rf"""
+ To define your new code from this file run:
+
+ ```
+ verdi code create core.code.installed --config configure_code.yaml
+ ```
+
+ Hopefully, that completed successfully. Using these commands, you can show the details of your new code and verify that AiiDA can connect to it:
+
+ ```
+ verdi code show {"" if code_settings.value is None else code_settings.value["label"]}
+ verdi code test {"" if code_settings.value is None else code_settings.value["label"]}
+ ```
+
+ {_note}
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ## FANS Rundown
+
+ FANS requires a JSON input file. The input file can be thought of in 5 sections, each specifying the various problem parameters as well as runtime settings. Each setting also notes the appropriate AiiDA datatype. This is the type of node that you must give AiiDA when running jobs, as we will see later.
+
+ ### Microstructure Definition
+
+ ```json
+ "ms_filename": "microstructures/sphere32.h5",
+ "ms_datasetname": "/sphere/32x32x32/ms",
+ "ms_L": [1.0, 1.0, 1.0]
+ ```
+
+ - `ms_filename`: This specifies the path to the HDF5 file that contains the microstructure data. (AiiDA type: `SinglefileData`)
+ - `ms_datasetname`: This is the path within the HDF5 file to the specific dataset that represents the microstructure. (AiiDA type: `Str`)
+ - `ms_L`: Microstructure length defines the physical dimensions of the microstructure in the x, y, and z directions. (AiiDA type: `List`)
+
+ ### Problem Type and Material Model
+
+ ```json
+ "problem_type": "mechanical",
+ "matmodel": "LinearElasticIsotropic",
+ "material_properties": {
+ "bulk_modulus": [62.5000, 222.222],
+ "shear_modulus": [28.8462, 166.6667]
+ }
+ ```
+
+ - `problem_type`: This defines the type of physical problem you are solving. Common options include "thermal" problems and "mechanical" problems. (AiiDA type: `Str`)
+ - `matmodel`: This specifies the material model to be used in the simulation. Examples include `LinearThermalIsotropic` for isotropic linear thermal problems, `LinearElasticIsotropic` for isotropic linear elastic mechanical problems, `PseudoPlasticLinearHardening`/`PseudoPlasticNonLinearHardening` for plasticity mimicking model with linear/nonlinear hardening, and `J2ViscoPlastic_LinearIsotropicHardening`/ `J2ViscoPlastic_NonLinearIsotropicHardening` for rate dependent J2 plasticity model with linear/nonlinear isotropic hardening. (AiiDA type: `Str`)
+ - `material_properties`: This provides the necessary material parameters for the chosen material model. For thermal problems, you might specify `conductivity`, while mechanical problems might require `bulk_modulus`, `shear_modulus`, and more properties for advanced material models. These properties can be defined as arrays to represent multiple phases within the microstructure. (AiiDA type: `Dict`)
+
+ ### Solver Settings
+
+ ```json
+ "method": "cg",
+ "error_parameters":{
+ "measure": "Linfinity",
+ "type": "absolute",
+ "tolerance": 1e-10
+ },
+ "n_it": 100
+ ```
+
+ - `method`: This indicates the numerical method to be used for solving the system of equations. `cg` stands for the Conjugate Gradient method, and `fp` stands for the Fixed Point method. (AiiDA type: `Str`)
+ - `error_parameters`: This section defines the error parameters for the solver. Error control is applied on the finite element nodal residual of the problem.
+ - `measure`: Specifies the norm used to measure the error. Options include `Linfinity`, `L1`, or `L2`. (AiiDA type: `Str`)
+ - `type`: Defines the type of error measurement. Options are `absolute` or `relative`. (AiiDA type: `Str`)
+ - `tolerance`: Sets the tolerance level for the solver, defining the convergence criterion based on the chosen error measure. The solver iterates until the solution meets this tolerance. (AiiDA type: `Float`)
+ - `n_it`: Specifies the maximum number of iterations allowed for the FANS solver. (AiiDA type: `Int`)
+
+
+ ### Macroscale Loading Conditions
+
+ ```json
+ "macroscale_loading": [
+ [
+ [0.004, -0.002, -0.002, 0, 0, 0],
+ [0.008, -0.004, -0.004, 0, 0, 0],
+ [0.012, -0.006, -0.006, 0, 0, 0],
+ [0.016, -0.008, -0.008, 0, 0, 0],
+ ],
+ [
+ [0, 0, 0, 0.002, 0, 0],
+ [0, 0, 0, 0.004, 0, 0],
+ [0, 0, 0, 0.006, 0, 0],
+ [0, 0, 0, 0.008, 0, 0],
+ ]
+ ]
+ ```
+
+ - `macroscale_loading`: This defines the external loading applied to the microstructure. It is an array of arrays, where each sub-array represents a loading condition applied to the system. The format of the loading array depends on the problem type (AiiDA type: `ArrayData`):
+ - For `thermal` problems, the array typically has 3 components, representing the temperature gradients in the x, y, and z directions.
+ - For `mechanical` problems, the array must have 6 components, corresponding to the components of the strain tensor in Mandel notation (e.g., $[[ε_{11}, ε_{22}, ε_{33}, \sqrt{2} ε_{12}, \sqrt{2} ε_{13}, \sqrt{2} ε_{23}]]$).
+
+ In the case of path/time-dependent loading as shown, for example as in plasticity problems, the `macroscale_loading` array can include multiple steps with corresponding loading conditions.
+
+ ### Results Specification
+
+ ```json
+ "results": [
+ "stress", "strain",
+ "stress_average", "strain_average",
+ "phase_stress_average", "phase_strain_average",
+ "microstructure",
+ "displacement",
+ "absolute_error",
+ ]
+ ```
+
+ - `results`: This array lists the quantities that should be stored into the results HDF5 file during the simulation. Each string in the array corresponds to a specific result (AiiDA type: `List`):
+ - `stress` and `strain`: The stress and strain fields at each voxel in the microstructure.
+ - `stress_average` and `strain_average`: Volume averaged- homogenized stress and strain over the entire microstructure.
+ - `phase_stress_average` and `phase_strain_average`: Volume averaged- homogenized stress and strain for each phase within the microstructure.
+ - `microstructure`: The original microstructure data.
+ - `displacement`: The displacement fluctuation field (for mechanical problems) and temperature fluctuation field (for thermal problems).
+ - `absolute_error`: The L-infinity error of finite element nodal residual at each iteration.
+
+ Additional material model specific results can be included depending on the problem type and material model.
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ## Submitting Jobs
+
+ Now that AiiDA is suitably prepared and we're familiar with the FANS parameter specifications, its time to get to work. We will conduct a mock experiment to demonstrate the simplicity and flexibility that using the plugin offers. Breaking down the submission of jobs into two steps makes for a clean workflow.
+ """
+ )
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ import_button = mo.ui.run_button(label="RUN")
+
+ mo.md(rf"""
+ ### Creating Input Parameters
+
+ We will create all the input parameters we wish to study today at once. To begin, we import everything that will be needed and call the `load_profile()` function to activate the default profile within this script.
+
+ Press this button only after you have created a default profile as described above in [AiiDA Setup](#aiida-setup).
+
+ {import_button}
+
+ ```py
+ from aiida.engine import run # run jobs
+ from aiida.plugins import CalculationFactory # generates fans calculation
+ from aiida.orm import (
+ Group, # node organisation tool
+ SinglefileData, # \
+ Str, # |
+ Float, # |
+ Int, # |- AiiDA datatypes
+ List, # |
+ Dict, # |
+ ArrayData, # /
+ CalcJobNode, # node type for calculation jobs
+ QueryBuilder, # advanced query tool
+ load_node, # basic query tool for nodes
+ load_code, # basic query tool for codes
+ )
+ from numpy import array # numpy array
+ from itertools import product # for parameter space generation
+ from random import uniform # for parameter space generation
+
+ from aiida import load_profile # injects profile context into script
+ load_profile()
+ ```
+ """)
+ return (import_button,)
+
+
+@app.cell(hide_code=True)
+def imports(import_button, mo):
+ mo.stop(not import_button.value) # run on click
+
+ try:
+ from aiida.common.exceptions import ProfileConfigurationError, ConfigurationError
+
+ from aiida.engine import run
+ from aiida.plugins import CalculationFactory
+ from aiida.orm import (
+ Group,
+ SinglefileData,
+ Str,
+ Float,
+ Int,
+ List,
+ Dict,
+ ArrayData,
+ CalcJobNode,
+ QueryBuilder,
+ load_node,
+ load_code,
+ )
+ from numpy import array
+ from itertools import product
+ from random import uniform
+
+ from aiida import load_profile
+ load_profile()
+
+ except ImportError:
+ mo.stop(True, output=mo.md("**Imports failed to load properly!**").style(text_align="center").callout(kind="danger"))
+
+ except ProfileConfigurationError:
+ mo.stop(True, output=mo.md("**Your profile failed to load properly!**").style(text_align="center").callout(kind="danger"))
+
+ mo.md("**Success!**").style(text_align="center").callout(kind="success")
+ return (
+ ArrayData,
+ CalcJobNode,
+ CalculationFactory,
+ ConfigurationError,
+ Dict,
+ Float,
+ Group,
+ Int,
+ List,
+ QueryBuilder,
+ SinglefileData,
+ Str,
+ array,
+ load_code,
+ product,
+ run,
+ uniform,
+ )
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ _code = r"""
+ groups = QueryBuilder( # we will use the advanced query method
+ ).append( # it consists of a series of `.append` methods
+ Group, filters={
+ Group.fields.label: "inputs" # here we filter by groups labeled "inputs"
+ }
+ ).all( # conclude with a method to fetch the results
+ flat=True
+ )
+
+ if len(groups) == 0: # if the "inputs" group does not exist...
+ inputs = Group( # make it
+ label="inputs",
+ description="Herein are all the manually defined inputs for FANS."
+ ).store() # the `.store` method saves it in the database
+
+ elif len(groups) == 1: # otherwise don't make it
+ inputs = groups.pop()
+ """
+
+ mo.md(rf"""
+ Next, we will create a "group". This is purely an organisational tool that AiiDA provides. It may come in handy later to see what nodes belong to the inputs we are creating today.
+
+ We use the `QueryBuilder` to find all groups with label "inputs". If none exist, we create one and provide it a short description.
+
+ ```py
+ {_code}
+ ```
+ """)
+ return
+
+
+@app.cell(hide_code=True)
+def group(Group, QueryBuilder, import_button, mo):
+ mo.stop(not import_button.value) # run on click
+
+ groups = QueryBuilder( # we will use the advanced query method
+ ).append( # it consists of a series of `.append` methods
+ Group, filters={
+ Group.fields.label: "inputs" # here we filter by groups labeled "inputs"
+ }
+ ).all( # conclude with a method to fetch the results
+ flat=True
+ )
+
+ if len(groups) == 0: # if the "inputs" group does not exist...
+ inputs = Group( # make it
+ label="inputs",
+ description="Herein are all the manually defined inputs for FANS."
+ ).store() # the `.store` method saves it in the database
+
+ elif len(groups) == 1: # otherwise don't make it
+ inputs = groups.pop()
+
+ else:
+ raise
+ return (inputs,)
+
+
+@app.cell
+def _(Path, mo):
+ try:
+ dataset_path = Path("tutorial_dataset.h5").absolute()
+ except:
+ mo.stop(True)
+ return (dataset_path,)
+
+
+@app.cell
+def _(dataset_path, mo):
+ _code = r"""
+ microstructurequery = QueryBuilder(
+ ).append(
+ SinglefileData, filters={
+ SinglefileData.fields.label: "microstructure"
+ }
+ ).all(
+ flat=True
+ )
+
+ if len(microstructurequery) == 0:
+ microstructurefile = SinglefileData(
+ Path('""" + str(dataset_path) + r"""'),
+ label="microstructure"
+ ).store()
+ elif len(microstructurequery) == 1:
+ microstructurefile = microstructurequery.pop()
+ else:
+ raise
+
+ inputs.add_nodes(microstructurefile) # add the node to the "inputs" group
+ """
+
+ mo.md(rf"""
+ Next, we store the microstructure file in the database. Using a similar strategy as with the group definition, the `QueryBuilder` first searches for existing microstructures. If none are found, we define a new one in the form of a `SinglefileData` node. This built-in AiiDA datatype points to a file via a path. Finally, the microstructure node is included in our "inputs" group.
+
+ ```py
+ {_code}
+ ```
+ """)
+ return
+
+
+@app.cell
+def microstructure(
+ QueryBuilder,
+ SinglefileData,
+ dataset_path,
+ import_button,
+ inputs,
+ mo,
+):
+ mo.stop(not import_button.value) # run on click
+
+ microstructurequery = QueryBuilder(
+ ).append(
+ SinglefileData, filters={
+ SinglefileData.fields.label: "microstructure"
+ }
+ ).all(flat=True)
+
+ if len(microstructurequery) == 0:
+ microstructurefile = SinglefileData(
+ dataset_path,
+ label="microstructure"
+ ).store()
+ elif len(microstructurequery) == 1:
+ microstructurefile = microstructurequery.pop()
+ else:
+ raise
+
+ inputs.add_nodes(microstructurefile)
+ return
+
+
+@app.cell
+def _(mo):
+ mo.md(r"""
+ **Note:** _more nodes..._
+
+ The microstructure file node we just created is saved by AiiDA as a node. Just as before, we can list all the nodes we've created thus far; and it may be helpful to do so every once in a while to ensure everything is proceeding as expected.
+
+ To list all the nodes stored in your profile, run:
+
+ ```
+ verdi node list
+ ```
+ """).callout(kind="info")
+ return
+
+
+@app.cell
+def _(mo):
+ def_nodes_button = mo.ui.run_button(label="RUN", kind="warn")
+ def_nodes_code_switch = mo.ui.switch(label="*show full code...*")
+
+ _code = r"""
+ # Microstructure Definition
+ Str("/dset_0/image", label="ms_datasetname"),
+ Str("/dset_1/image", label="ms_datasetname"),
+ Str("/dset_2/image", label="ms_datasetname"),
+ List([1.0, 1.0, 1.0], label="ms_L"),
+
+ ...
+
+ # Problem Type and Material Model: Moduli
+ Dict({"bulk_modulus": bulk, "shear_modulus": shear}, label="material_properties")
+ for bulk, shear in product(
+ [[uniform(50, 75), uniform(200, 250)] for _ in range(2)],
+ [[uniform(25, 50), uniform(150, 200)] for _ in range(2)]
+ )
+
+ ...
+ """
+
+ mo.md(rf"""
+ Now, we will define the rest of our parameters. This is mostly straightforward, but we treat `ms_datasetname` and `material_properties` a little differently.
+
+ - `ms_datasetname`: Three different datasets are chosen from the sample microstructure file provided.
+ - `material_properties`: A mock parameter space study is realised by randomly picking bulk and shear moduli from within a range.
+
+ When it comes time to run our calculations, we will run the "product" of all these parameters.
+
+ ```py
+ {_code}
+ ```
+ {def_nodes_code_switch}
+ """)
+ return def_nodes_button, def_nodes_code_switch
+
+
+@app.cell(hide_code=True)
+def _(def_nodes_button, def_nodes_code_switch, mo):
+ def gatekeep1():
+ mo.stop(not def_nodes_button.value and def_nodes_code_switch.value, output=mo.show_code())
+ mo.stop(not def_nodes_button.value)
+ return (gatekeep1,)
+
+
+@app.cell
+def node_definition(
+ ArrayData,
+ Dict,
+ Float,
+ Int,
+ List,
+ Str,
+ array,
+ gatekeep1,
+ product,
+ uniform,
+):
+ gatekeep1() # Ignore this line.
+
+ nodes = [
+
+ # Microstructure Definition
+ Str("/dset_0/image", label="ms_datasetname"),
+ Str("/dset_1/image", label="ms_datasetname"),
+ Str("/dset_2/image", label="ms_datasetname"),
+ List([1.0, 1.0, 1.0], label="ms_L"),
+
+ # Problem Type and Material Model
+ Str("mechanical", label="problem_type"),
+ Str("LinearElasticIsotropic", label="matmodel")
+ ] + [
+ Dict({"bulk_modulus": bulk, "shear_modulus": shear}, label="material_properties")
+ for bulk, shear in product(
+ [[uniform(50, 75), uniform(200, 250)] for _ in range(2)],
+ [[uniform(25, 50), uniform(150, 200)] for _ in range(2)]
+ )] + [
+
+ # Solver Settings
+ Str("cg", label="method"),
+ Str("Linfinity", label="error_parameters.measure"),
+ Str("absolute", label="error_parameters.type"),
+ Float(1e-10, label="error_parameters.tolerance"),
+ Int(100, label="n_it"),
+
+ # Macroscale Loading Conditions
+ ArrayData({
+ "0": array([[0,0,0,0,0,0]])
+ }, label="macroscale_loading"),
+
+ # Results Specification
+ List(["stress", "strain", "stress_average", "strain_average",
+ "absolute_error", "phase_stress_average", "phase_strain_average",
+ "microstructure", "displacement"], label="results")
+
+ ]
+ return (nodes,)
+
+
+@app.cell
+def _(def_nodes_button, mo):
+ mo.md(rf"""
+ While the cell above defined all the parameters, they still need to be stored in the database. Otherwise, they will be lost when the session ends. AiiDA automatically stores nodes when submitting them to a job, but it is good practice to handle this yourself. Moreover, you get to see your database grow step by step. After clicking the button below, try running `verdi node list` in your terminal to see all the new additions we've made so far, and `verdi node show ` for more information about specific nodes.
+
+ It is important to note that this time we did not make any checks through the QueryBuilder to ensure that indentical nodes don't already exist. This means that if you click the button below repeatedly, you *may* cause duplicate nodes to be created. Since these are some the first nodes we're making, it is not so critical, but in practice you would want to first fetch existing nodes you want to reuse before creating the remainder of the nodes you wish to study.
+
+ {def_nodes_button}
+
+ ```py
+ for node in nodes: # iterate over the list of new node
+ node.store() # store each one in the database
+ inputs.add_nodes(node) # assign each one to the "inputs" group
+ ```
+ """)
+ return
+
+
+@app.cell
+def node_storage(def_nodes_button, inputs, mo, nodes):
+ mo.stop(not def_nodes_button.value) # Ignore this line.
+
+ for node in nodes: # iterate over the list of new node
+ node.store() # store each one in the database
+ inputs.add_nodes(node) # assign each one to the "inputs" group
+ return
+
+
+@app.cell
+def _(mo):
+ mk_params_code_switch = mo.ui.switch(label="*show full code...*")
+
+ _code = r"""
+ some_params = [{
+ "problem_type": fetch("problem_type", "mechanical"),
+ "matmodel": fetch("matmodel", "LinearElasticIsotropic"),
+ ...
+ }]
+
+ ...
+
+ ms_datasetname_params = [
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_0/image"),}
+ },
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_1/image"),}
+ },
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_2/image"),}
+ }
+ ]
+
+ material_properties_params = [
+ {"material_properties": mp.pop()}
+ for mp in QueryBuilder().append(
+ Dict, filters={
+ Dict.fields.label: "material_properties"
+ }
+ ).iterall()
+ ]
+ """
+
+ mo.md(rf"""
+ ### Executing Calculations
+
+ Now that all the input parameters have been specified, it it time to run some calculations. We create lists of dictionaries for each set of paramaters we wish to vary. In our case, `microsctructure` needs a list, as does `material_properties`. Everything else falls into a list of length one. The keys of the dictionaries here are important and are specified by the plugin. More information is available in the documentation, but efforts are being made to synchronise these with the FANS parameter specification.
+
+ Below, some nodes are fetched using a helper function (see [Appendix A](#appendix)) which essentially queries the database for a single node with a particular label and value. You could also use the nodes we created above instead, passing them forward as variables, but here we demonstrate how you might run calculations using a either new or old nodes at once.
+
+ Click the button bellow when you are sure that all the nodes above have been successfully created and stored. Try `verdi node list` to see them all.
+
+
+ ```py
+ {_code}
+ ```
+
+ {mk_params_code_switch}
+ """)
+ return (mk_params_code_switch,)
+
+
+@app.cell
+def _(def_nodes_button, mk_params_code_switch, mo):
+ def gatekeep2():
+ mo.stop(not def_nodes_button.value and mk_params_code_switch.value, output=mo.show_code())
+ mo.stop(not def_nodes_button.value)
+
+ def gatekeep3():
+ return mo.show_code() if mk_params_code_switch.value else None
+ return
+
+
+@app.cell
+def parameter_definition(
+ ArrayData,
+ Dict,
+ QueryBuilder,
+ SinglefileData,
+ fetch,
+ mk_params_code_switch,
+ mo,
+):
+ some_params = [{
+ "problem_type": fetch("problem_type", "mechanical"),
+ "matmodel": fetch("matmodel", "LinearElasticIsotropic"),
+ "method": fetch("method", "cg"),
+ "error_parameters": {
+ "measure": fetch("error_parameters.measure", "Linfinity"),
+ "type": fetch("error_parameters.type", "absolute"),
+ "tolerance": fetch("error_parameters.tolerance", 1e-10)
+ },
+ "n_it": fetch("n_it", 100),
+ "macroscale_loading": QueryBuilder().append(
+ ArrayData, filters={
+ ArrayData.fields.label: "macroscale_loading"
+ }
+ ).first(flat=True),
+ "results": fetch("results", ["stress", "strain", "stress_average", "strain_average", "absolute_error", "phase_stress_average", "phase_strain_average", "microstructure", "displacement"])
+ }]
+
+ ms_file = QueryBuilder().append(
+ SinglefileData, filters={
+ SinglefileData.fields.label: "microstructure"
+ }
+ ).first(flat=True)
+
+ ms_L = fetch("ms_L", [1.0, 1.0, 1.0])
+
+ ms_datasetname_params = [
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_0/image"),}
+ },
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_1/image"),}
+ },
+ {"microstructure":{"file": ms_file,"L": ms_L,
+ "datasetname": fetch("ms_datasetname", "/dset_2/image"),}
+ }
+ ]
+
+ material_properties_params = [
+ {"material_properties": mp.pop()}
+ for mp in QueryBuilder().append(
+ Dict, filters={
+ Dict.fields.label: "material_properties"
+ }
+ ).iterall()
+ ]
+
+ mo.show_code() if mk_params_code_switch.value else None # Ignore this line.
+ return material_properties_params, ms_datasetname_params, some_params
+
+
+@app.cell
+def _(code_settings, mo):
+ calculate_button = mo.ui.run_button(label="RUN", kind="warn")
+
+ get_calc_state, set_calc_state = mo.state(False)
+
+ _code = r"""
+ FANSCalculation = CalculationFactory("fans") # get the plugin's process class
+ code = {"code": load_code('""" + f"{"')}" if code_settings.value is None else code_settings.value["label"] + "')}" : <22}" + """ # get the existing code node
+
+ for sp, dsp, mpp in product(some_params, ms_datasetname_params, material_properties_params):
+ all_params = sp | dsp | mpp # merge this permutation of params
+ run(FANSCalculation, all_params | code) # finally run the job
+ """
+
+ mo.md(rf"""
+ Once these lists are defined, we use the `product` function to explore every permutation of their contents. Each permutation is coupled with the code node, defined earlier, and given to the `run` function with the plugin specific `FANSCalculation` process class.
+
+ Much like last time, we aren't checking if these calculations have already been run, so clicking the button below repeatedly will request duplicate calulations to be run and duplicate results will be generated.
+
+ {calculate_button}
+
+ ```py
+ {_code}
+ ```
+ """)
+ return calculate_button, get_calc_state, set_calc_state
+
+
+@app.cell
+def calculations(
+ CalculationFactory,
+ ConfigurationError,
+ calculate_button,
+ code_settings,
+ load_code,
+ material_properties_params,
+ mo,
+ ms_datasetname_params,
+ product,
+ run,
+ set_calc_state,
+ some_params,
+):
+ mo.stop(not calculate_button.value)
+
+ FANSCalculation = CalculationFactory("fans") # get the plugin's process class
+ try: # get the existing code node
+ code = {"code": load_code(code_settings.value["label"])}
+ except ConfigurationError:
+ mo.stop(True, output=mo.md("**Your code failed to load properly!**\n\nPlease submit the 'Define a Code' form in the [AiiDA Setup](aiida-setup) section.").style(text_align="center").callout(kind="danger"))
+
+ for sp, dsp, mpp in mo.status.progress_bar(
+ list(product(some_params, ms_datasetname_params, material_properties_params)),
+ title="Calculating Jobs...", completion_title="Finished!"
+ ):
+ all_params = sp | dsp | mpp # merge this permutation of params
+ run(FANSCalculation, all_params | code) # finally run the job
+ else:
+ set_calc_state(True)
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ query_button = mo.ui.run_button(label="RUN")
+
+ get_query_state, set_query_state = mo.state(False)
+
+ mo.md(rf"""
+ ## Analysing the Results
+
+ Once our calculations are complete, we can make use of the QueryBuilder again to find and analyse the results.
+
+ {query_button}
+ """)
+ return get_query_state, query_button, set_query_state
+
+
+@app.cell(hide_code=True)
+def _(mo, query_button, set_query_state):
+ #! DO NOT DELETE
+ # This cell saves the query_button state to allow for user confirmation!
+ mo.stop(not query_button.value) # run on click
+ set_query_state(True)
+ return
+
+
+@app.cell(hide_code=True)
+def _(get_calc_state, set_calc_state):
+ #! DO NOT DELETE
+ # This cell triggers the following cell upon confirmation!
+ set_calc_state(get_calc_state())
+ return
+
+
+@app.cell
+def _(
+ CalcJobNode,
+ Int,
+ QueryBuilder,
+ Str,
+ get_calc_state,
+ get_query_state,
+ mo,
+ set_calc_state,
+ set_query_state,
+):
+ confirm = mo.ui.button(label="Are you sure?", on_click=lambda _: set_calc_state(True))
+ are_you_sure = mo.md(rf"""
+ It seems the jobs were not calculated in this session. If you are sure that they have been completed, you may proceed.
+
+ {confirm}
+ """).callout(kind="danger")
+ mo.stop(not get_query_state())
+ mo.stop(not get_calc_state(), output=are_you_sure)
+ set_query_state(False)
+
+
+ # QUERY:
+
+ calc = QueryBuilder().append(CalcJobNode).first(flat=True)
+ # Inputs
+ ins = list(calc.inputs._get_keys())
+ ins = "
".join(ins)
+ # Microstructure Dataset Name
+ ms_datasetname = calc.inputs.microstructure.datasetname.value
+ # Material Properties
+ mat_props = {
+ "b": (
+ calc.inputs.material_properties["bulk_modulus"][0],
+ calc.inputs.material_properties["bulk_modulus"][1]
+ ),
+ "s": (
+ calc.inputs.material_properties["shear_modulus"][0],
+ calc.inputs.material_properties["shear_modulus"][1]
+ )
+ }
+ # Outputs
+ outs = list(calc.outputs._get_keys())
+ outs = ", ".join(outs)
+ # Stresses and Strains
+ log = calc.outputs.retrieved.get_object_content("input.json.log").split("\n")
+ stresses = []
+ strains = []
+ for ln in log:
+ if "Effective Stress" in ln:
+ stresses.append(list(map(
+ lambda n: round(float(n), ndigits=3),
+ ln.lstrip("# Effective Stress .. ")
+ .replace("(", "").replace(")", "").strip(" ")
+ .split(" ")
+ )))
+ if "Effective Strain" in ln:
+ strains.append(list(map(
+ lambda n: round(float(n), ndigits=3),
+ ln.lstrip("# Effective Strain .. ")
+ .replace("(", "").replace(")", "").strip(" ")
+ .split(" ")
+ )))
+ stress_strains = [{"stress": stress, "strain": strain} for stress, strain in zip(stresses, strains)]
+ # Filtered Query
+ filtered_calcs = \
+ QueryBuilder(
+ ).append( # In the first `.append` we look for nodes
+ Str, # of the `Str` AiiDA datatype,
+ filters={ # then apply the filters for:
+ Int.fields.label: "ms_datasetname", #
+ Int.fields.value: {"==": "/dset_0/image"} #
+ },
+ tag="ms_datasetname" # The `tag` is an internal reference.
+
+ ).append( # In the second `.append` we look for nodes
+ CalcJobNode, # of the `CalcJobNode` AiiDA datatype,
+ with_incoming="ms_datasetname" # and specify required incoming nodes with
+ # the `tag` we defined above.
+ ).all(flat=True)
+
+
+ # DISPLAY:
+
+ _code = r"""
+ QueryBuilder(
+ ).append( # In the first `.append` we look for nodes
+ Str, # of the `Str` AiiDA datatype,
+ filters={ # then apply the filters for:
+ Int.fields.label: "ms_datasetname", #
+ Int.fields.value: {"==": "dset_0"} #
+ },
+ tag="ms_datasetname" # The `tag` is an internal reference.
+
+ ).append( # In the second `.append` we look for nodes
+ CalcJobNode, # of the `CalcJobNode` AiiDA datatype,
+ with_incoming="ms_datasetname" # and specify required incoming nodes with
+ # the `tag` we defined above.
+ ).all(flat=True)
+ """
+
+ mo.md(rf"""
+ ### Fetch a single calculation...
+
+ We will begin by querying the database for the first `CalcJobNode` present. This is the AiiDA datatype given to nodes that represent the exectution of an individual job.
+
+ ```py
+ calc = QueryBuilder().append(CalcJobNode).first(flat=True)
+ ```
+
+ From this calculation job node we can gleam some identifying information, such as the type of calculation job (i.e. the process label) or its primary key in the database. Additionally, we can list the available inputs and outputs provided by this kind of job.
+
+ | | |
+ |--------------------|---------------------------------------|
+ | **Process Label:** | {calc.process_label} |
+ | **Primary Key:** | {calc.pk} |
+ | **Inputs:** | {ins} |
+ | **Outputs:** | {outs} |
+
+ ### Identify some input parameters...
+
+ Of course, it would be helpful to know exactly what inputs were used in the calculation of this particular job. The inputs can be accessed via dot notation which provides the respective values as AiiDA datatypes.
+
+ When it comes to the microstructure dataset name, the inputs's value is accessed through the `value` attribute.
+
+ ```py
+ calc.inputs.microstructure.datasetname.value
+ ```
+
+ | | |
+ |-|-|
+ | **Microstructure Dataset Name:** | {ms_datasetname} |
+
+ In the case of the material properties, this attribute takes the form an AiiDA `Dict` which has methods just like an ordinary `dict`.
+
+ ```py
+ calc.inputs.material_properties.items()
+ ```
+
+ | | | |
+ |-|-|-|
+ |Bulk Modulus: | {mat_props["b"][0]} | {mat_props["b"][1]} |
+ |Shear Modulus: | {mat_props["s"][0]} | {mat_props["s"][1]} |
+
+ ### Effective stress and strain...
+
+ To extract the effective stress and strain per loading condition from the output of FANS, we can use the `std_out` it produces. This text is stored in the `retrieved` folder output. We can get its contents and parse it to determine our results.
+
+ ```py
+ log = calc.outputs.retrieved.get_object_content("input.json.log")
+ for ln in log:
+ ...
+ ```
+
+ | Loading
Condition: | Stress: | Strain: |
+ |---|-------------------------------|-------------------------------|
+ | **1** | {stress_strains[0]["stress"]} | {stress_strains[0]["strain"]} |
+
+ ### Perform a filtered query...
+
+ Aside from manually examining the inputs and outputs of individual calculation jobs, the `QueryBuilder` offers the ability to filter your query based on a variety of criteria. In this instance, we query for all jobs that used the "dset_0" microstructure dataset. This time, we are given back a list of calculation job nodes to do with as we please.
+
+ ```py
+ {_code}
+ ```
+
+ | | | | | |
+ |-|-|-|-|-|
+ | **Primary Keys:** | {filtered_calcs[0].pk} | {filtered_calcs[1].pk} | {filtered_calcs[2].pk} | {filtered_calcs[3].pk} |
+
+ """)
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(r"""# Appendix""")
+ return
+
+
+@app.cell(hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ## A. `fetch()`
+
+ This is a helper function to simplify the querying of individual nodes when the label and value are known.
+ """
+ )
+ return
+
+
+@app.cell
+def _(Dict, Float, Int, List, QueryBuilder, Str, mo):
+ def fetch(label : str, value):
+ """Helper function to return a node whose label and value are known.
+
+ Returns an error if more or less than 1 suitable node is found.
+ """
+ match value:
+ case str():
+ datatype = Str
+ case int():
+ datatype = Int
+ case float():
+ datatype = Float
+ case list():
+ datatype = List
+ case dict():
+ datatype = Dict
+ case _:
+ raise NotImplementedError
+
+ bone = QueryBuilder().append(
+ datatype,
+ filters={
+ datatype.fields.label: label,
+ "attributes.value": value
+ } if datatype is not List else {
+ datatype.fields.label: label,
+ "attributes.list": value
+ },
+ ).all(flat=True)
+
+ if len(bone) != 1:
+ raise RuntimeError
+
+ return bone.pop()
+
+ mo.show_code()
+ return (fetch,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tutorial/tutorial_dataset.h5 b/tutorial/tutorial_dataset.h5
new file mode 100644
index 0000000..2811cb7
Binary files /dev/null and b/tutorial/tutorial_dataset.h5 differ