pax_global_header00006660000000000000000000000064125500340510014505gustar00rootroot0000000000000052 comment=a1430d4ad9df22b58da2cbeb3de75063fe519cd6 fiat-1.6.0/000077500000000000000000000000001255003405100124345ustar00rootroot00000000000000fiat-1.6.0/.bzrignore000066400000000000000000000002171255003405100144360ustar00rootroot00000000000000(^|/)CVS($|/) (^|/)\.hg($|/) (^|/)\.hgtags($|/) ^project.log$ ^tailor.state$ ^tailor.state.old$ ^tailor.state.journal$ syntax: glob FIAT/*.pyc fiat-1.6.0/.gitignore000066400000000000000000000000131255003405100144160ustar00rootroot00000000000000FIAT/*.pyc fiat-1.6.0/AUTHORS000066400000000000000000000007701255003405100135100ustar00rootroot00000000000000Main author: Robert C. Kirby email: robert.c.kirby@ttu.edu www: http://www.math.ttu.edu/~kirby/ Contributors: Marie Rognes email: meg@simula.no Anders Logg email: logg@simula.no www: http://home.simula.no/~logg/ Kristian B. Ølgaard email: k.b.oelgaard@gmail.com Garth N. Wells email: gnw20@cam.ac.uk www: http://www.eng.cam.ac.uk/~gnw20/ Andy R. Terrel email: aterrel@uchicago.edu Jan Blechta email: blechta@karlin.mff.cuni.cz fiat-1.6.0/COPYING000066400000000000000000001043741255003405100135000ustar00rootroot00000000000000 GNU 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 . fiat-1.6.0/COPYING.LESSER000066400000000000000000000167271255003405100145000ustar00rootroot00000000000000 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. 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. fiat-1.6.0/ChangeLog000066400000000000000000000031321255003405100142050ustar00rootroot00000000000000 - Support DG on facets through the element "Discontinuous Lagrange Trace" 1.5.0 [2014-01-12] - Require Python 2.7 - Python 3 support - Remove ScientificPython dependency and add dependency on SymPy 1.4.0 [2014-06-02] - Support discontinuous/broken Raviart-Thomas 1.3.0 [2014-01-07] - Version bump. 1.1.0 [2013-01-07] - Support second kind Nedelecs on tetrahedra over degree >= 2 - Support Brezzi-Douglas-Fortin-Marini elements (of degree 1, 2), again 1.0.0 [2011-12-07] - No changes since 1.0-beta, only updating the version number 1.0-beta [2011-08-11] - Change of license to LGPL v3+ - Minor fixes 0.9.9 [2011-02-23] - Add __version__ - Add second kind Nedeles on triangles 0.9.2 [2010-07-01] - Bug fix for 1D quadrature 0.9.1 [2010-02-03] - Cleanups and small fixes 0.9.0 [2010-02-01] - New improved interface with support for arbitrary reference elements 0.3.5 0.3.4 0.3.3 - Bug fix in Nedelec - Support for ufc element 0.3.1 - Bug fix in DOF orderings for H(div) elements - Preliminary type system for DOF - Allow user to change ordering of reference dof - Brezzi-Douglas-Fortin-Marini elements working 0.3.0 - Small changes to H(div) elements preparing for integration with FFC - Switch to numpy - Added primitive testing harness in fiat/testing 0.2.4 - Fixed but in P0.py 0.2.3 - Updated topology/ geometry so to allow different orderings of entities 0.2.2 - Added Raviart-Thomas element, verified RT0 against old version of code - Started work on BDFM, Nedelec (not working) - Fixed projection, union of sets (error in SVD usage) - Vector-valued spaces have general number of components fiat-1.6.0/FIAT/000077500000000000000000000000001255003405100131575ustar00rootroot00000000000000fiat-1.6.0/FIAT/P0.py000066400000000000000000000040251255003405100140110ustar00rootroot00000000000000# Copyright (C) 2005 The University of Chicago # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # # Written by Robert C. Kirby # # This work is partially supported by the US Department of Energy # under award number DE-FG02-04ER25650 # # Last changed: 2005-05-16 from . import reference_element, dual_set, functional, polynomial_set, finite_element import numpy class P0Dual( dual_set.DualSet ): def __init__( self, ref_el ): entity_ids = {} nodes = [] vs = numpy.array( ref_el.get_vertices() ) bary=tuple( numpy.average( vs, 0 ) ) nodes = [ functional.PointEvaluation( ref_el, bary ) ] entity_ids = { } sd = ref_el.get_spatial_dimension() top = ref_el.get_topology() for dim in sorted( top ): entity_ids[dim] = {} for entity in sorted( top[dim] ): entity_ids[dim][entity] = [] entity_ids[sd] = { 0 : [ 0 ] } dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class P0( finite_element.FiniteElement ): def __init__( self, ref_el ): poly_set = polynomial_set.ONPolynomialSet( ref_el, 0 ) dual = P0Dual( ref_el ) finite_element.FiniteElement.__init__( self, poly_set, dual, 0 ) if __name__ == "__main__": T = reference_element.UFCTriangle() U = P0( T ) print(U.get_dual_set().entity_ids) print(U.get_nodal_basis().tabulate( T.make_lattice(1) )) fiat-1.6.0/FIAT/__init__.py000066400000000000000000000044021255003405100152700ustar00rootroot00000000000000"""FInite element Automatic Tabulator -- supports constructing and evaluating arbitrary order Lagrange and many other elements. Simplices in one, two, and three dimensions are supported.""" __version__ = "1.6.0dev" # Import finite element classes from FIAT.finite_element import FiniteElement from FIAT.argyris import Argyris from FIAT.argyris import QuinticArgyris from FIAT.brezzi_douglas_marini import BrezziDouglasMarini from FIAT.brezzi_douglas_fortin_marini import BrezziDouglasFortinMarini from FIAT.discontinuous_lagrange import DiscontinuousLagrange from FIAT.trace import DiscontinuousLagrangeTrace from FIAT.discontinuous_raviart_thomas import DiscontinuousRaviartThomas from FIAT.hermite import CubicHermite from FIAT.lagrange import Lagrange from FIAT.morley import Morley from FIAT.nedelec import Nedelec from FIAT.nedelec_second_kind import NedelecSecondKind from FIAT.P0 import P0 from FIAT.raviart_thomas import RaviartThomas from FIAT.crouzeix_raviart import CrouzeixRaviart from FIAT.regge import Regge # List of supported elements and mapping to element classes supported_elements = {"Argyris": Argyris, "Brezzi-Douglas-Marini": BrezziDouglasMarini, "Brezzi-Douglas-Fortin-Marini": BrezziDouglasFortinMarini, "Crouzeix-Raviart": CrouzeixRaviart, "Discontinuous Lagrange": DiscontinuousLagrange, "Discontinuous Lagrange Trace": DiscontinuousLagrangeTrace, "Discontinuous Raviart-Thomas": DiscontinuousRaviartThomas, "Hermite": CubicHermite, "Lagrange": Lagrange, "Morley": Morley, "Nedelec 1st kind H(curl)": Nedelec, "Nedelec 2nd kind H(curl)": NedelecSecondKind, "Raviart-Thomas": RaviartThomas, "Regge": Regge} # List of extra elements extra_elements = {"P0": P0, "Quintic Argyris": QuinticArgyris} # Important functionality from .quadrature import make_quadrature from .reference_element import ufc_simplex fiat-1.6.0/FIAT/argyris.py000066400000000000000000000134101255003405100152100ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, polynomial_set, dual_set, functional import numpy class ArgyrisDualSet( dual_set.DualSet ): def __init__( self, ref_el, degree ): entity_ids = {} nodes = [] cur = 0 top = ref_el.get_topology() verts = ref_el.get_vertices() sd = ref_el.get_spatial_dimension() if sd != 2: raise Exception("Illegal spatial dimension") pe = functional.PointEvaluation pd = functional.PointDerivative pnd = functional.PointNormalDerivative # get jet at each vertex entity_ids[0] = {} for v in sorted( top[0] ): nodes.append( pe( ref_el, verts[v] ) ) # first derivatives for i in range( sd ): alpha = [0] * sd alpha[i] = 1 nodes.append( pd( ref_el, verts[v], alpha ) ) # second derivatives alphas = [ [2, 0], [0, 2], [1, 1] ] for alpha in alphas: nodes.append( pd( ref_el, verts[v], alpha ) ) entity_ids[0][v] = list(range(cur, cur+6)) cur += 6 # edge dof entity_ids[1] = {} for e in sorted( top[1] ): # normal derivatives at degree - 4 points on each edge ndpts = ref_el.make_points( 1, e, degree - 3 ) ndnds = [ pnd( ref_el, e, pt ) for pt in ndpts ] nodes.extend( ndnds ) entity_ids[1][e] = list(range(cur, cur + len(ndpts))) cur += len( ndpts ) # point value at degree-5 points on each edge if degree > 5: ptvalpts = ref_el.make_points( 1, e, degree - 4 ) ptvalnds = [ pe( ref_el, pt ) for pt in ptvalpts ] nodes.extend( ptvalnds ) entity_ids[1][e] += list(range(cur, cur+len(ptvalpts))) cur += len( ptvalpts ) # internal dof entity_ids[2] = {} if degree > 5: internalpts = ref_el.make_points( 2, 0, degree - 3 ) internalnds = [ pe( ref_el, pt ) for pt in internalpts ] nodes.extend( internalnds ) entity_ids[2][0] = list(range(cur, cur+len(internalpts))) cur += len(internalpts) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class QuinticArgyrisDualSet( dual_set.DualSet ): """The dual basis for Lagrange elements. This class works for simplices of any dimension. Nodes are point evaluation at equispaced points.""" def __init__( self, ref_el ): entity_ids = {} nodes = [] cur = 0 # make nodes by getting points # need to do this dimension-by-dimension, facet-by-facet top = ref_el.get_topology() verts = ref_el.get_vertices() sd = ref_el.get_spatial_dimension() if sd != 2: raise Exception("Illegal spatial dimension") pd = functional.PointDerivative # get jet at each vertex entity_ids[0] = {} for v in sorted( top[0] ): nodes.append( functional.PointEvaluation( ref_el, verts[v] ) ) # first derivatives for i in range( sd ): alpha = [0] * sd alpha[i] = 1 nodes.append( pd( ref_el, verts[v], alpha ) ) # second derivatives alphas = [ [2, 0], [0, 2], [1, 1] ] for alpha in alphas: nodes.append( pd( ref_el, verts[v], alpha ) ) entity_ids[0][v] = list(range(cur, cur+6)) cur += 6 # edge dof -- normal at each edge midpoint entity_ids[1] = {} for e in sorted( top[1] ): pt = ref_el.make_points( 1, e, 2 )[0] n = functional.PointNormalDerivative( ref_el, e, pt ) nodes.append( n ) entity_ids[1][e] = [cur] cur += 1 dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class Argyris( finite_element.FiniteElement ): """The Argyris finite element.""" def __init__( self, ref_el, degree ): poly_set = polynomial_set.ONPolynomialSet( ref_el, degree ) dual = ArgyrisDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree ) class QuinticArgyris( finite_element.FiniteElement ): """The Argyris finite element.""" def __init__( self, ref_el ): poly_set = polynomial_set.ONPolynomialSet( ref_el, 5 ) dual = QuinticArgyrisDualSet( ref_el ) finite_element.FiniteElement.__init__( self, poly_set, dual, 5 ) if __name__=="__main__": from . import reference_element from . import lagrange T = reference_element.DefaultTriangle() for k in range(5, 11): U = Argyris( T, k ) U2 = lagrange.Lagrange( T, k ) c = U.get_nodal_basis().get_coeffs() sigma = numpy.linalg.svd( c, compute_uv = 0) print("Argyris ", k, max(sigma) / min(sigma)) c = U2.get_nodal_basis().get_coeffs() sigma = numpy.linalg.svd( c, compute_uv = 0) print("Lagrange ", k, max(sigma) / min(sigma )) print() fiat-1.6.0/FIAT/asci2vtk2d.py000066400000000000000000000032761255003405100155150ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . #!/usr/bin/env python # 2d mode: x y z, z = f(x,y) import sys if len(sys.argv) > 1: filename = sys.argv[1] print(filename) base = filename.split(".")[0] output = "%s.vtk" % (base,) print("output to %s" % output) else: print("python asci2vtk.py foo") sys.exit(0) fin = open( filename, "r" ) coords = [ ] for line in fin: coords.append( line.split() ) fin.close() n = len( coords ) print("%s points" % (str(n),)) fout = open( output, "w" ) fout.write("""# vtk DataFile Version 2.0 points ASCII DATASET UNSTRUCTURED_GRID POINTS %s float\n""" % str(n)) for c in coords: fout.write("%s %s %s\n" % (c[0], c[1], 0)) fout.write("CELLS %s %s\n" % (n, 2*n)) for i in range( n ): fout.write("1 %s\n" % i) fout.write("CELL_TYPES %s\n" % (n,)) for i in range( n ): fout.write("1\n") fout.write("POINT_DATA %s\n" % (n,)) fout.write("""SCALARS Z float 1 LOOKUP_TABLE default\n""") for i in range( n ): fout.write("%s" % coords[i][2]) fout.close() fiat-1.6.0/FIAT/asci2vtk3d.py000066400000000000000000000033221255003405100155060ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . #!/usr/bin/env python # 3d mode: x y z f, f = f(x,y,z) import sys if len(sys.argv) > 1: filename = sys.argv[1] print(filename) base = filename.split(".")[0] output = "%s.vtk" % (base,) print("output to %s" % (output,)) else: print("python asci2vtk3d.py foo") sys.exit(0) fin = open( filename, "r" ) coords = [ ] for line in fin: coords.append( line.split() ) fin.close() n = len( coords ) print("%s points" % (str(n),)) fout = open( output, "w" ) fout.write("""# vtk DataFile Version 2.0 points ASCII DATASET UNSTRUCTURED_GRID POINTS %s float\n""" % (str(n),)) for c in coords: fout.write("%s %s %s\n" % (c[0], c[1], c[2])) fout.write("CELLS %s %s\n" % (n, 2*n)) for i in range( n ): fout.write("1 %s\n" % (i,)) fout.write("CELL_TYPES %s\n" % (n,)) for i in range( n ): fout.write("1\n") fout.write("POINT_DATA %s\n" % (n,)) fout.write("""SCALARS Z float 1 LOOKUP_TABLE default\n""") for i in range( n ): fout.write("%s\n", ncoords[i][3]) fout.close() fiat-1.6.0/FIAT/brezzi_douglas_fortin_marini.py000066400000000000000000000111641255003405100214770ustar00rootroot00000000000000from . import finite_element, quadrature, functional, \ dual_set, reference_element, polynomial_set, lagrange import numpy class BDFMDualSet( dual_set.DualSet ): def __init__( self, ref_el, degree ): # Initialize containers for map: mesh_entity -> dof number and # dual basis entity_ids = {} nodes = [] sd = ref_el.get_spatial_dimension() t = ref_el.get_topology() # Define each functional for the dual set # codimension 1 facet normals. # note this will die for degree greater than 1. for i in range( len( t[sd-1] ) ): pts_cur = ref_el.make_points( sd - 1, i, sd + degree ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointScaledNormalEvaluation( ref_el, i, \ pt_cur ) nodes.append( f ) # codimension 1 facet tangents. # because the tangent component is discontinuous, these actually # count as internal nodes. tangent_count=0 for i in range( len( t[sd-1] ) ): pts_cur = ref_el.make_points( sd - 1, i, sd + degree - 1 ) tangent_count+=len( pts_cur ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointEdgeTangentEvaluation( ref_el, i, \ pt_cur ) nodes.append( f ) # sets vertices (and in 3d, edges) to have no nodes for i in range( sd - 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] cur = 0 # set codimension 1 (edges 2d, faces 3d) dof pts_facet_0 = ref_el.make_points( sd - 1, 0, sd + degree ) pts_per_facet = len( pts_facet_0 ) entity_ids[sd-1] = {} for i in range( len( t[sd-1] ) ): entity_ids[sd-1][i] = list(range( cur, cur + pts_per_facet)) cur += pts_per_facet # internal nodes entity_ids[sd] = {0: list(range(cur, cur+tangent_count))} cur+=tangent_count dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) def BDFMSpace(ref_el, order): sd = ref_el.get_spatial_dimension() if sd !=2: raise Exception("BDFM_k elements only valid for dim 2") # Note that order will be 2. # Linear vector valued space. Since the embedding degree of this element # is 2, this is implemented by taking the quadratic space and selecting # the linear polynomials. vec_poly_set = polynomial_set.ONPolynomialSet( ref_el, order, (sd,) ) # Linears are the first three polynomials in each dimension. vec_poly_set = vec_poly_set.take([0, 1, 2, 6, 7, 8]) # Scalar quadratic Lagrange element. lagrange_ele = lagrange.Lagrange(ref_el, order) # Select the dofs associated with the edges. edge_dofs_dict=lagrange_ele.dual.get_entity_ids()[sd-1] edge_dofs=numpy.array([(edge, dof) for edge, dofs in list(edge_dofs_dict.items()) for dof in dofs]) tangent_polys=lagrange_ele.poly_set.take(edge_dofs[:, 1]) new_coeffs=numpy.zeros((tangent_polys.get_num_members(), sd, tangent_polys.coeffs.shape[-1])) # Outer product of the tangent vectors with the quadratic edge polynomials. for i, (edge, dof) in enumerate(edge_dofs): tangent=ref_el.compute_edge_tangent(edge) new_coeffs[i,:,:]=numpy.outer(tangent, tangent_polys.coeffs[i,:]) bubble_set = polynomial_set.PolynomialSet( ref_el, \ order, \ order, \ vec_poly_set.get_expansion_set(), \ new_coeffs, \ vec_poly_set.get_dmats() ) element_set = polynomial_set.polynomial_set_union_normalized( bubble_set, vec_poly_set ) return element_set class BrezziDouglasFortinMarini( finite_element.FiniteElement ): """The BDFM element""" def __init__(self, ref_el, degree): if degree != 2: raise Exception("BDFM_k elements only valid for k == 2") poly_set = BDFMSpace(ref_el, degree) dual = BDFMDualSet(ref_el, degree-1) finite_element.FiniteElement.__init__(self, poly_set, dual, degree, mapping="contravariant piola") return if __name__=="__main__": T = reference_element.UFCTriangle() BDFM = BrezziDouglasFortinMarini(T, 2) fiat-1.6.0/FIAT/brezzi_douglas_marini.py000066400000000000000000000074131255003405100201200ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, raviart_thomas, quadrature, functional, \ dual_set, reference_element, polynomial_set, nedelec class BDMDualSet( dual_set.DualSet ): def __init__( self, ref_el, degree ): # Initialize containers for map: mesh_entity -> dof number and # dual basis entity_ids = {} nodes = [] sd = ref_el.get_spatial_dimension() t = ref_el.get_topology() # Define each functional for the dual set # codimension 1 facets for i in range( len( t[sd-1] ) ): pts_cur = ref_el.make_points( sd - 1, i, sd + degree ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointScaledNormalEvaluation( ref_el, i, \ pt_cur ) nodes.append( f ) # internal nodes if degree > 1: Q = quadrature.make_quadrature( ref_el, 2 * (degree + 1) ) qpts = Q.get_points() Nedel = nedelec.Nedelec( ref_el, degree - 1 ) Nedfs = Nedel.get_nodal_basis() zero_index = tuple( [ 0 for i in range( sd ) ] ) Ned_at_qpts = Nedfs.tabulate( qpts )[ zero_index ] for i in range( len( Ned_at_qpts ) ): phi_cur = Ned_at_qpts[i,:] l_cur = functional.FrobeniusIntegralMoment( ref_el, Q, \ phi_cur ) nodes.append(l_cur) # sets vertices (and in 3d, edges) to have no nodes for i in range( sd - 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] cur = 0 # set codimension 1 (edges 2d, faces 3d) dof pts_facet_0 = ref_el.make_points( sd - 1, 0, sd + degree ) pts_per_facet = len( pts_facet_0 ) entity_ids[sd-1] = {} for i in range( len( t[sd-1] ) ): entity_ids[sd-1][i] = list(range( cur, cur + pts_per_facet)) cur += pts_per_facet # internal nodes, if applicable entity_ids[sd] = {0: []} if degree > 1: num_internal_nodes = len( Ned_at_qpts ) entity_ids[sd][0] = list(range( cur, cur + num_internal_nodes)) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class BrezziDouglasMarini( finite_element.FiniteElement ): """The BDM element""" def __init__( self, ref_el, degree ): if degree < 1: raise Exception("BDM_k elements only valid for k >= 1") sd = ref_el.get_spatial_dimension() poly_set = polynomial_set.ONPolynomialSet( ref_el, degree, (sd,) ) dual = BDMDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree, mapping="contravariant piola") return if __name__=="__main__": T = reference_element.UFCTetrahedron() for k in range(1, 3): print(k) BDM = BrezziDouglasMarini( T, k ) print() fiat-1.6.0/FIAT/crouzeix_raviart.py000066400000000000000000000057541255003405100171440ustar00rootroot00000000000000# Copyright (C) 2010 Marie E. Rognes # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # # Written by Marie E. Rognes based on original # implementation by Robert C. Kirby. # # Last changed: 2010-01-28 from . import finite_element, polynomial_set, dual_set, functional def _initialize_entity_ids(topology): entity_ids = {} for (i, entity) in list(topology.items()): entity_ids[i] = {} for j in entity: entity_ids[i][j] = [] return entity_ids class CrouzeixRaviartDualSet(dual_set.DualSet): """Dual basis for Crouzeix-Raviart element (linears continuous at boundary midpoints).""" def __init__(self, cell, degree): # Get topology dictionary d = cell.get_spatial_dimension() topology = cell.get_topology() # Initialize empty nodes and entity_ids entity_ids = _initialize_entity_ids(topology) nodes = [None for i in list(topology[d-1].keys())] # Construct nodes and entity_ids for i in topology[d-1]: # Construct midpoint x = cell.make_points(d-1, i, d)[0] # Degree of freedom number i is evaluation at midpoint nodes[i] = functional.PointEvaluation(cell, x) entity_ids[d-1][i] += [i] # Initialize super-class dual_set.DualSet.__init__(self, nodes, cell, entity_ids) class CrouzeixRaviart(finite_element.FiniteElement): """The Crouzeix-Raviart finite element: K: Triangle/Tetrahedron Polynomial space: P_1 Dual basis: Evaluation at facet midpoints """ def __init__(self, cell, degree): # Crouzeix Raviart is only defined for polynomial degree == 1 if not (degree == 1): raise Exception("Crouzeix-Raviart only defined for degree 1") # Construct polynomial spaces, dual basis and initialize # FiniteElement space = polynomial_set.ONPolynomialSet(cell, 1) dual = CrouzeixRaviartDualSet(cell, 1) finite_element.FiniteElement.__init__(self, space, dual, 1) if __name__ == "__main__": from . import reference_element cells = [reference_element.UFCTriangle(), reference_element.UFCTetrahedron()] for cell in cells: print("Checking CrouzeixRaviart(cell, 1)") element = CrouzeixRaviart(cell, 1) print([L.pt_dict for L in element.dual_basis()]) print() fiat-1.6.0/FIAT/discontinuous_lagrange.py000066400000000000000000000054721255003405100203070ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, polynomial_set, dual_set, functional, P0 class DiscontinuousLagrangeDualSet( dual_set.DualSet ): """The dual basis for Lagrange elements. This class works for simplices of any dimension. Nodes are point evaluation at equispaced points. This is the discontinuous version where all nodes are topologically associated with the cell itself""" def __init__( self, ref_el, degree ): entity_ids = {} nodes = [] # make nodes by getting points # need to do this dimension-by-dimension, facet-by-facet top = ref_el.get_topology() cur = 0 for dim in sorted( top ): entity_ids[dim] = {} for entity in sorted( top[dim] ): pts_cur = ref_el.make_points( dim, entity, degree ) nodes_cur = [ functional.PointEvaluation( ref_el, x ) \ for x in pts_cur ] nnodes_cur = len( nodes_cur ) nodes += nodes_cur entity_ids[dim][entity]=[] cur += nnodes_cur entity_ids[dim][0] = list(range(len(nodes))) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class HigherOrderDiscontinuousLagrange( finite_element.FiniteElement ): """The discontinuous Lagrange finite element. It is what it is.""" def __init__( self, ref_el, degree ): poly_set = polynomial_set.ONPolynomialSet( ref_el, degree ) dual = DiscontinuousLagrangeDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree ) def DiscontinuousLagrange( ref_el, degree ): if degree == 0: return P0.P0( ref_el ) else: return HigherOrderDiscontinuousLagrange( ref_el, degree ) if __name__=="__main__": from . import reference_element T = reference_element.DefaultTetrahedron() for k in range(2, 3): U = DiscontinuousLagrange( T, k ) Ufs = U.get_nodal_basis() pts = T.make_lattice( k ) print(pts) for foo, bar in list(Ufs.tabulate( pts, 1 ).items()): print(foo) print(bar) print() fiat-1.6.0/FIAT/discontinuous_raviart_thomas.py000066400000000000000000000061561255003405100215520ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # # Modified by Jan Blechta 2014 from . import expansions, polynomial_set, quadrature, reference_element, dual_set, \ quadrature, finite_element, functional import numpy from functools import reduce from .raviart_thomas import RTSpace class DRTDualSet( dual_set.DualSet ): """Dual basis for Raviart-Thomas elements consisting of point evaluation of normals on facets of codimension 1 and internal moments against polynomials. This is the discontinuous version where all nodes are topologically associated with the cell itself""" def __init__( self, ref_el, degree ): entity_ids = {} nodes = [] sd = ref_el.get_spatial_dimension() t = ref_el.get_topology() # codimension 1 facets for i in range( len( t[sd-1] ) ): pts_cur = ref_el.make_points( sd - 1, i, sd + degree ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointScaledNormalEvaluation( ref_el, i, \ pt_cur ) nodes.append( f ) # internal nodes. Let's just use points at a lattice if degree > 0: cpe = functional.ComponentPointEvaluation pts = ref_el.make_points( sd, 0, degree + sd ) for d in range( sd ): for i in range( len( pts ) ): l_cur = cpe( ref_el, d, (sd,), pts[i] ) nodes.append( l_cur ) # sets vertices (and in 3d, edges) to have no nodes for i in range( sd - 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] # set codimension 1 (edges 2d, faces 3d) to have no dofs entity_ids[sd-1] = {} for i in range( len( t[sd-1] ) ): entity_ids[sd-1][i] = [] # cell dofs entity_ids[sd] = {0: list(range(len(nodes)))} dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class DiscontinuousRaviartThomas( finite_element.FiniteElement ): """The discontinuous Raviart-Thomas finite element""" def __init__( self, ref_el, q ): degree = q - 1 poly_set = RTSpace( ref_el, degree ) dual = DRTDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree, mapping="contravariant piola") fiat-1.6.0/FIAT/dual_set.py000066400000000000000000000031021255003405100153250ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . import numpy class DualSet: def __init__( self, nodes, ref_el, entity_ids ): self.nodes = nodes self.ref_el = ref_el self.entity_ids = entity_ids return def get_nodes( self ): return self.nodes def get_entity_ids( self ): return self.entity_ids def get_reference_element( self ): return self.ref_el def to_riesz( self, poly_set ): tshape = self.nodes[0].target_shape num_nodes = len( self.nodes ) es = poly_set.get_expansion_set( ) num_exp = es.get_num_members( poly_set.get_embedded_degree() ) riesz_shape = tuple( [ num_nodes ] + list( tshape ) + [ num_exp ] ) self.mat = numpy.zeros( riesz_shape, "d" ) for i in range( len( self.nodes ) ): self.mat[i][:] = self.nodes[i].to_riesz( poly_set ) return self.mat fiat-1.6.0/FIAT/expansions.py000066400000000000000000000365141255003405100157310ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . """Principal orthogonal expansion functions as defined by Karniadakis and Sherwin. These are parametrized over a reference element so as to allow users to get coordinates that they want.""" import numpy import math import sympy from . import reference_element from . import jacobi def _tabulate_dpts(tabulator, D, n, order, pts): X = sympy.DeferredVector('x') def form_derivative(F): '''Forms the derivative recursively, i.e., F -> [F_x, F_y, F_z], [F_x, F_y, F_z] -> [[F_xx, F_xy, F_xz], [F_yx, F_yy, F_yz], [F_zx, F_zy, F_zz]] and so forth. ''' out = [] try: out = [sympy.diff(F, X[j]) for j in range(D)] except AttributeError: # Intercept errors like # AttributeError: 'list' object has no attribute # 'free_symbols' for f in F: out.append(form_derivative(f)) return out def numpy_lambdify(X, F): '''Unfortunately, SymPy's own lambdify() doesn't work well with NumPy in that simple functions like lambda x: 1.0, when evaluated with NumPy arrays, return just "1.0" instead of an array of 1s with the same shape as x. This function does that. ''' try: lambda_x = [numpy_lambdify(X, f) for f in F] except TypeError: # 'function' object is not iterable # SymPy's lambdify also works on functions that return arrays. # However, use it componentwise here so we can add 0*x to each # component individually. This is necessary to maintain shapes # if evaluated with NumPy arrays. lmbd_tmp = sympy.lambdify(X, F) lambda_x = lambda x: lmbd_tmp(x) + 0*x[0] return lambda_x def evaluate_lambda(lmbd, x): '''Properly evaluate lambda expressions recursively for iterables. ''' try: values = [evaluate_lambda(l, x) for l in lmbd] except TypeError: # 'function' object is not iterable values = lmbd(x) return values # Tabulate symbolically symbolic_tab = tabulator(n, X) # Make sure that the entries of symbolic_tab are lists so we can # append derivatives symbolic_tab = [[phi] for phi in symbolic_tab] # data = (order+1) * [None] for r in range(order+1): shape = [len(symbolic_tab), len(pts)] + r * [D] data[r] = numpy.empty(shape) for i, phi in enumerate(symbolic_tab): # Evaluate the function numerically using lambda expressions deriv_lambda = numpy_lambdify(X, phi[r]) data[r][i] = \ numpy.array(evaluate_lambda(deriv_lambda, pts.T)).T # Symbolically compute the next derivative. # This actually happens once too many here; never mind for # now. phi.append(form_derivative(phi[-1])) return data def xi_triangle(eta): """Maps from [-1,1]^2 to the (-1,1) reference triangle.""" eta1, eta2 = eta xi1 = 0.5 * (1.0 + eta1) * (1.0 - eta2) - 1.0 xi2 = eta2 return (xi1, xi2) def xi_tetrahedron(eta): """Maps from [-1,1]^3 to the -1/1 reference tetrahedron.""" eta1, eta2, eta3 = eta xi1 = 0.25 * (1. + eta1) * (1. - eta2) * (1. - eta3) - 1. xi2 = 0.5 * (1. + eta2) * (1. - eta3) - 1. xi3 = eta3 return xi1, xi2, xi3 class LineExpansionSet: """Evaluates the Legendre basis on a line reference element.""" def __init__(self, ref_el): if ref_el.get_spatial_dimension() != 1: raise Exception("Must have a line") self.ref_el = ref_el self.base_ref_el = reference_element.DefaultLine() v1 = ref_el.get_vertices() v2 = self.base_ref_el.get_vertices() self.A, self.b = reference_element.make_affine_mapping(v1, v2) self.mapping = lambda x: numpy.dot(self.A, x) + self.b self.scale = numpy.sqrt(numpy.linalg.det(self.A)) def get_num_members(self, n): return n+1 def tabulate(self, n, pts): """Returns a numpy array A[i,j] = phi_i(pts[j])""" if len(pts) > 0: ref_pts = numpy.array([self.mapping(pt) for pt in pts]) psitilde_as = jacobi.eval_jacobi_batch(0, 0, n, ref_pts) results = numpy.zeros((n+1, len(pts)), type(pts[0][0])) for k in range(n + 1): results[k, :] = psitilde_as[k, :] * math.sqrt(k + 0.5) return results else: return [] def tabulate_derivatives(self, n, pts): """Returns a tuple of length one (A,) such that A[i,j] = D phi_i(pts[j]). The tuple is returned for compatibility with the interfaces of the triangle and tetrahedron expansions.""" ref_pts = numpy.array([self.mapping(pt) for pt in pts]) psitilde_as_derivs = jacobi.eval_jacobi_deriv_batch(0, 0, n, ref_pts) # Jacobi polynomials defined on [-1, 1], first derivatives need scaling psitilde_as_derivs *= 2.0/self.ref_el.volume() results = numpy.zeros((n+1, len(pts)), "d") for k in range(0, n + 1): results[k, :] = psitilde_as_derivs[k, :] * numpy.sqrt(k + 0.5) vals = self.tabulate(n, pts) deriv_vals = (results,) # Create the ordinary data structure. dv = [] for i in range(vals.shape[0]): dv.append([]) for j in range(vals.shape[1]): dv[-1].append((vals[i][j], [deriv_vals[0][i][j]])) return dv class TriangleExpansionSet: """Evaluates the orthonormal Dubiner basis on a triangular reference element.""" def __init__(self, ref_el): if ref_el.get_spatial_dimension() != 2: raise Exception("Must have a triangle") self.ref_el = ref_el self.base_ref_el = reference_element.DefaultTriangle() v1 = ref_el.get_vertices() v2 = self.base_ref_el.get_vertices() self.A, self.b = reference_element.make_affine_mapping(v1, v2) self.mapping = lambda x: numpy.dot(self.A, x) + self.b # self.scale = numpy.sqrt(numpy.linalg.det(self.A)) def get_num_members(self, n): return (n+1)*(n+2)//2 def tabulate(self, n, pts): if len(pts) == 0: return numpy.array([]) else: return numpy.array(self._tabulate(n, numpy.array(pts).T)) def _tabulate(self, n, pts): '''A version of tabulate() that also works for a single point. ''' m1, m2 = self.A.shape ref_pts = [sum(self.A[i][j] * pts[j] for j in range(m2)) + self.b[i] for i in range(m1) ] def idx(p, q): return (p+q)*(p+q+1)//2 + q def jrc(a, b, n): an = float((2*n+1+a+b)*(2*n+2+a+b)) \ / float(2*(n+1)*(n+1+a+b)) bn = float((a*a-b*b) * (2*n+1+a+b)) \ / float(2*(n+1)*(2*n+a+b)*(n+1+a+b)) cn = float((n+a)*(n+b)*(2*n+2+a+b)) \ / float((n+1)*(n+1+a+b)*(2*n+a+b)) return an, bn, cn results = ((n+1)*(n+2)//2) * [None] results[0] = 1.0 \ + pts[0] - pts[0] \ + pts[1] - pts[1] if n == 0: return results x = ref_pts[0] y = ref_pts[1] f1 = (1.0+2*x+y)/2.0 f2 = (1.0 - y) / 2.0 f3 = f2**2 results[idx(1, 0)] = f1 for p in range(1, n): a = (2.0*p+1)/(1.0+p) # b = p / (p+1.0) results[idx(p+1, 0)] = a * f1 * results[idx(p, 0)] \ - p/(1.0+p) * f3 * results[idx(p-1, 0)] for p in range(n): results[idx(p, 1)] = 0.5 * (1+2.0*p+(3.0+2.0*p)*y) \ * results[idx(p, 0)] for p in range(n-1): for q in range(1, n-p): (a1, a2, a3) = jrc(2*p+1, 0, q) results[idx(p, q+1)] = \ (a1 * y + a2) * results[idx(p, q)] \ - a3 * results[idx(p, q-1)] for p in range(n+1): for q in range(n-p+1): results[idx(p, q)] *= math.sqrt((p+0.5)*(p+q+1.0)) return results #return self.scale * results def tabulate_derivatives(self, n, pts): order = 1 data = _tabulate_dpts(self._tabulate, 2, n, order, numpy.array(pts)) # Put data in the required data structure, i.e., # k-tuples which contain the value, and the k-1 derivatives # (gradient, Hessian, ...) m = data[0].shape[0] n = data[0].shape[1] data2 = [[tuple([data[r][i][j] for r in range(order+1)]) for j in range(n)] for i in range(m)] return data2 def tabulate_jet(self, n, pts, order=1): return _tabulate_dpts(self._tabulate, 2, n, order, numpy.array(pts)) class TetrahedronExpansionSet: """Collapsed orthonormal polynomial expanion on a tetrahedron.""" def __init__(self, ref_el): if ref_el.get_spatial_dimension() != 3: raise Exception("Must be a tetrahedron") self.ref_el = ref_el self.base_ref_el = reference_element.DefaultTetrahedron() v1 = ref_el.get_vertices() v2 = self.base_ref_el.get_vertices() self.A, self.b = reference_element.make_affine_mapping(v1, v2) self.mapping = lambda x: numpy.dot(self.A, x) + self.b self.scale = numpy.sqrt(numpy.linalg.det(self.A)) return def get_num_members(self, n): return (n+1)*(n+2)*(n+3)//6 def tabulate(self, n, pts): if len(pts) == 0: return numpy.array([]) else: return numpy.array(self._tabulate(n, numpy.array(pts).T)) def _tabulate(self, n, pts): '''A version of tabulate() that also works for a single point. ''' m1, m2 = self.A.shape ref_pts = [sum(self.A[i][j] * pts[j] for j in range(m2)) + self.b[i] for i in range(m1) ] def idx(p, q, r): return (p+q+r)*(p+q+r+1)*(p+q+r+2)//6 + (q+r)*(q+r+1)//2 + r def jrc(a, b, n): an = float((2*n+1+a+b)*(2*n+2+a+b)) \ / float(2*(n+1)*(n+1+a+b)) bn = float((a*a-b*b) * (2*n+1+a+b)) \ / float(2*(n+1)*(2*n+a+b)*(n+1+a+b)) cn = float((n+a)*(n+b)*(2*n+2+a+b)) \ / float((n+1)*(n+1+a+b)*(2*n+a+b)) return an, bn, cn results = ((n+1)*(n+2)*(n+3)//6) * [None] results[0] = 1.0 \ + pts[0] - pts[0] \ + pts[1] - pts[1] \ + pts[2] - pts[2] if n == 0: return results x = ref_pts[0] y = ref_pts[1] z = ref_pts[2] factor1 = 0.5 * (2.0 + 2.0*x + y + z) factor2 = (0.5*(y+z))**2 factor3 = 0.5 * (1 + 2.0 * y + z) factor4 = 0.5 * (1 - z) factor5 = factor4 ** 2 results[idx(1, 0, 0)] = factor1 for p in range(1, n): a1 = (2.0 * p + 1.0) / (p + 1.0) a2 = p / (p + 1.0) results[idx(p+1, 0, 0)] = a1 * factor1 * results[idx(p, 0, 0)] \ - a2 * factor2 * results[idx(p-1, 0, 0)] # q = 1 for p in range(0, n): results[idx(p, 1, 0)] = results[idx(p, 0, 0)] \ * (p * (1.0 + y) + (2.0 + 3.0 * y + z) / 2) for p in range(0, n-1): for q in range(1, n-p): (aq, bq, cq) = jrc(2*p+1, 0, q) qmcoeff = aq * factor3 + bq * factor4 qm1coeff = cq * factor5 results[idx(p, q+1, 0)] = qmcoeff * results[idx(p, q, 0)] \ - qm1coeff * results[idx(p, q-1, 0)] # now handle r=1 for p in range(n): for q in range(n-p): results[idx(p, q, 1)] = results[idx(p, q, 0)] \ * (1.0 + p + q + (2.0 + q + p) * z) # general r by recurrence for p in range(n-1): for q in range(0, n-p-1): for r in range(1, n-p-q): ar, br, cr = jrc(2*p+2*q+2, 0, r) results[idx(p, q, r+1)] = \ (ar * z + br) * results[idx(p, q, r) ] \ - cr * results[idx(p, q, r-1) ] for p in range(n+1): for q in range(n-p+1): for r in range(n-p-q+1): results[idx(p, q, r)] *= \ math.sqrt((p+0.5)*(p+q+1.0)*(p+q+r+1.5)) return results def tabulate_derivatives(self, n, pts): order = 1 D = 3 data = _tabulate_dpts(self._tabulate, D, n, order, numpy.array(pts)) # Put data in the required data structure, i.e., # k-tuples which contain the value, and the k-1 derivatives # (gradient, Hessian, ...) m = data[0].shape[0] n = data[0].shape[1] data2 = [[tuple([data[r][i][j] for r in range(order+1)]) for j in range(n)] for i in range(m)] return data2 def tabulate_jet(self, n, pts, order=1): return _tabulate_dpts(self._tabulate, 3, n, order, numpy.array(pts)) def get_expansion_set( ref_el ): """Returns an ExpansionSet instance appopriate for the given reference element.""" if ref_el.get_shape() == reference_element.LINE: return LineExpansionSet(ref_el) elif ref_el.get_shape() == reference_element.TRIANGLE: return TriangleExpansionSet(ref_el) elif ref_el.get_shape() == reference_element.TETRAHEDRON: return TetrahedronExpansionSet(ref_el) else: raise Exception("Unknown reference element type.") def polynomial_dimension(ref_el, degree): """Returns the dimension of the space of polynomials of degree no greater than degree on the reference element.""" if ref_el.get_shape() == reference_element.LINE: return max(0, degree + 1) elif ref_el.get_shape() == reference_element.TRIANGLE: return max((degree+1)*(degree+2)//2, 0) elif ref_el.get_shape() == reference_element.TETRAHEDRON: return max(0, (degree+1)*(degree+2)*(degree+3)//6) else: raise Exception("Unknown reference element type.") if __name__ == "__main__": from . import expansions E = reference_element.DefaultTriangle() k = 3 pts = E.make_lattice(k) Phis = expansions.get_expansion_set(E) phis = Phis.tabulate(k, pts) dphis = Phis.tabulate_derivatives(k, pts) # dphis_x = numpy.array([[d[1][0] for d in dphi] for dphi in dphis]) # dphis_y = numpy.array([[d[1][1] for d in dphi] for dphi in dphis]) # dphis_z = numpy.array([[d[1][2] for d in dphi] for dphi in dphis]) # print dphis_x # for dmat in make_dmats(E, k): # print dmat # print fiat-1.6.0/FIAT/factorial.py000066400000000000000000000017741255003405100155060ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . def factorial( n ): """Computes n! for n an integer >= 0. Raises an ArithmeticError otherwise.""" if not isinstance(n, type(1)) or n < 0: raise ArithmeticError("factorial only defined on natural numbers.") f = 1 for i in range(1, n+1): f = f * i return f fiat-1.6.0/FIAT/finite_element.py000066400000000000000000000116411255003405100165230ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . import numpy from .polynomial_set import PolynomialSet class FiniteElement: """Class implementing Ciarlet's abstraction of a finite element being a domain, function space, and set of nodes.""" def __init__( self , poly_set , dual , order, mapping="affine"): # first, compare ref_el of poly_set and dual # need to overload equality #if poly_set.get_reference_element() != dual.get_reference_element: # raise Exception, "" # The order (degree) of the polynomial basis self.order = order self.ref_el = poly_set.get_reference_element() self.dual = dual # Appropriate mapping for the element space self._mapping = mapping # build generalized Vandermonde matrix old_coeffs = poly_set.get_coeffs() dualmat = dual.to_riesz( poly_set ) shp = dualmat.shape if len( shp ) > 2: num_cols = numpy.prod( shp[1:] ) A = numpy.reshape( dualmat, (dualmat.shape[0], num_cols) ) B = numpy.reshape( old_coeffs, (old_coeffs.shape[0], num_cols ) ) else: A = dualmat B = old_coeffs V = numpy.dot( A, numpy.transpose( B ) ) self.V=V (u, s, vt) = numpy.linalg.svd( V ) Vinv = numpy.linalg.inv( V ) new_coeffs_flat = numpy.dot( numpy.transpose( Vinv ), B) new_shp = tuple( [ new_coeffs_flat.shape[0] ] \ + list( shp[1:] ) ) new_coeffs = numpy.reshape( new_coeffs_flat, \ new_shp ) self.poly_set = PolynomialSet( self.ref_el, \ poly_set.get_degree(), \ poly_set.get_embedded_degree(), \ poly_set.get_expansion_set(), \ new_coeffs, \ poly_set.get_dmats() ) return def degree(self): "Return the degree of the (embedding) polynomial space." return self.poly_set.get_embedded_degree() def get_reference_element( self ): "Return the reference element for the finite element." return self.ref_el def get_nodal_basis( self ): """Return the nodal basis, encoded as a PolynomialSet object, for the finite element.""" return self.poly_set def get_dual_set( self ): "Return the dual for the finite element." return self.dual def get_order( self ): "Return the order of the element (may be different from the degree)" return self.order def dual_basis(self): """Return the dual basis (list of functionals) for the finite element.""" return self.dual.get_nodes() def entity_dofs(self): """Return the map of topological entities to degrees of freedom for the finite element.""" return self.dual.get_entity_ids() def get_coeffs(self): """Return the expansion coefficients for the basis of the finite element.""" return self.poly_set.get_coeffs() def mapping(self): """Return a list of appropriate mappings from the reference element to a physical element for each basis function of the finite element.""" return [self._mapping]*self.space_dimension() def num_sub_elements(self): "Return the number of sub-elements." return 1 def space_dimension(self): "Return the dimension of the finite element space." return self.poly_set.get_num_members() def tabulate(self, order, points): """Return tabulated values of derivatives up to given order of basis functions at given points.""" return self.poly_set.tabulate(points, order) def value_shape(self): "Return the value shape of the finite element functions." return self.poly_set.get_shape() def dmats(self): """Return dmats: expansion coefficients for basis function derivatives.""" return self.get_nodal_basis().get_dmats() def get_num_members(self, arg): "Return number of members of the expansion set." return self.get_nodal_basis().get_expansion_set().get_num_members(arg) fiat-1.6.0/FIAT/functional.py000066400000000000000000000401121255003405100156710ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # functionals require: # - a degree of accuracy (-1 indicates that it works for all functions # such as point evaluation) # - a reference element domain # - type information import numpy from functools import reduce from collections import OrderedDict def index_iterator(shp): """Constructs a generator iterating over all indices in shp in generalized column-major order So if shp = (2,2), then we construct the sequence (0,0),(0,1),(1,0),(1,1)""" if len(shp) == 0: return elif len(shp) == 1: for i in range(shp[0]): yield [i] else: shp_foo = shp[1:] for i in range(shp[0]): for foo in index_iterator(shp_foo): yield [i] + foo # also put in a "jet_dict" that maps # pt --> {wt, multiindex, comp} # the multiindex is an iterable of nonnegative # integers class Functional: """Class implementing an abstract functional. All functionals are discrete in the sense that the are written as a weighted sum of (components of) their argument evaluated at particular points.""" def __init__(self, ref_el, target_shape, pt_dict, deriv_dict, functional_type ): self.ref_el = ref_el self.target_shape = target_shape self.pt_dict = pt_dict self.deriv_dict = deriv_dict self.functional_type = functional_type if len(deriv_dict) > 0: per_point = reduce(lambda a, b: a + b, list(deriv_dict.values())) alphas = \ [foo[1] for foo in per_point] self.max_deriv_order = max([sum(foo) for foo in alphas]) else: self.max_deriv_order = 0 return def evaluate(self, f): """Evaluates the functional on some callable object f.""" result = 0 # non-derivative part # TODO pt_dict? comp? for pt in pt_dict: wc_list = pt_dict[pt] for (w, c) in wc_list: if comp == tuple: result += w * f(pt) else: result += w * f(pt)[comp] # Import AD modules from ScientificPython # import Scientific.Functions.Derivatives as Derivatives for pt in self.deriv_dict: dpt = tuple([Derivatives.DerivVar(pt[i], i, self.max_deriv_order) for i in range(len(pt)) ]) for (w, a, c) in self.deriv_dict[pt]: fpt = f(dpt) order = sum(a) if c == tuple(): val_cur = fpt[order] else: val_cur = fpt[c][order] for i in range(len[a]): for j in range(a[j]): val_cur = val_cur[i] result += val_cur return result def get_point_dict(self): """Returns the functional information, which is a dictionary mapping each point in the support of the functional to a list of pairs containing the weight and component.""" return self.pt_dict def get_reference_element(self): """Returns the reference element.""" return self.ref_el def get_type_tag(self): """Returns the type of function (e.g. point evaluation or normal component, which is probably handy for clients of FIAT""" return self.functional_type # overload me in subclasses to make life easier!! def to_riesz(self, poly_set): """Constructs an array representation of the functional over the base of the given polynomial_set so that f(phi) for any phi in poly_set is given by a dot product.""" es = poly_set.get_expansion_set() ed = poly_set.get_embedded_degree() pt_dict = self.get_point_dict() pts = list(pt_dict.keys()) # bfs is matrix that is pdim rows by num_pts cols # where pdim is the polynomial dimension bfs = es.tabulate(ed, pts) result = numpy.zeros(poly_set.coeffs.shape[1:], "d") shp = poly_set.get_shape() # loop over points for j in range(len(pts)): pt_cur = pts[j] wc_list = pt_dict[pt_cur] # loop over expansion functions for i in range(bfs.shape[0]): for (w, c) in wc_list: result[c][i] += w * bfs[i, j] def pt_to_dpt(pt, dorder): dpt = [] for i in range(len(pt)): dpt.append(Derivatives.DerivVar(pt[i], i, dorder)) return tuple(dpt) # loop over deriv points dpt_dict = self.deriv_dict mdo = self.max_deriv_order dpts = list(dpt_dict.keys()) dpts_dv = [pt_to_dpt(pt, mdo) for pt in dpts] dbfs = es.tabulate(ed, dpts_dv) for j in range(len(dpts)): dpt_cur = dpts[j] for i in range(dbfs.shape[0]): for (w, a, c) in dpt_dict[dpt_cur]: dval_cur = dbfs[i, j][sum(a)] for k in range(len(a)): for l in range(a[k]): dval_cur = dval_cur[k] result[c][i] += w * dval_cur return result def tostr(self): return self.functional_type class PointEvaluation(Functional): """Class representing point evaluation of scalar functions at a particular point x.""" def __init__(self, ref_el, x): pt_dict = {x: [(1.0, tuple())]} Functional.__init__(self, ref_el, tuple(), pt_dict, {}, "PointEval") return def tostr(self): x = list(map(str, list(self.pt_dict.keys())[0])) return "u(%s)" % (','.join(x),) class ComponentPointEvaluation(Functional): """Class representing point evaluation of a particular component of a vector function at a particular point x.""" def __init__(self, ref_el, comp, shp, x): if len(shp) != 1: raise Exception("Illegal shape") if comp < 0 or comp >= shp[0]: raise Exception("Illegal component") self.comp = comp pt_dict = {x: [(1.0, (comp,))]} Functional.__init__(self, ref_el, shp, pt_dict, {}, "ComponentPointEval") def tostr(self): x = list(map(str, list(self.pt_dict.keys())[0])) return "(u[%d](%s)" % (self.comp, ','.join(x)) class PointDerivative(Functional): """Class representing point partial differentiation of scalar functions at a particular point x.""" def __init__(self, ref_el, x, alpha): dpt_dict = {x: [(1.0, alpha, tuple())]} self.alpha = alpha self.order = sum(self.alpha) Functional.__init__(self, ref_el, tuple(), {}, dpt_dict, "PointDeriv" ) return def to_riesz(self, poly_set): x = list(self.deriv_dict.keys())[0] dx = tuple([Derivatives.DerivVar(x[i], i, self.order) for i in range(len(x)) ]) es = poly_set.get_expansion_set() ed = poly_set.get_embedded_degree() bfs = es.tabulate(ed, [dx])[:, 0] idx = [] for i in range(len(self.alpha)): for j in range(self.alpha[i]): idx.append(i) idx = tuple(idx) return numpy.array([numpy.array(b[self.order])[idx] for b in bfs]) class PointNormalDerivative(Functional): def __init__(self, ref_el, facet_no, pt): n = ref_el.compute_normal(facet_no) self.n = n sd = ref_el.get_spatial_dimension() alphas = [] for i in range(sd): alpha = [0]*sd alpha[i] = 1 alphas.append(alpha) dpt_dict = {pt: [(n[i], alphas[i], tuple()) for i in range(sd)]} Functional.__init__(self, ref_el, tuple(), {}, dpt_dict, "PointNormalDeriv" ) return def to_riesz(self, poly_set): #import Scientific.Functions.FirstDerivatives as FirstDerivatives x = list(self.deriv_dict.keys())[0] dx = tuple([FirstDerivatives.DerivVar(x[i], i) for i in range(len(x)) ]) es = poly_set.get_expansion_set() ed = poly_set.get_embedded_degree() bfs = es.tabulate(ed, [dx])[:, 0] bfs_grad = numpy.array([b[1] for b in bfs]) return numpy.dot(bfs_grad, self.n) class IntegralMoment (Functional): """ An IntegralMoment is a functional """ def __init__(self, ref_el, Q, f_at_qpts, comp=tuple(), shp=tuple() ): """ Create IntegralMoment *Arguments* ref_el The reference element (cell) Q (QuadratureRule) A quadrature rule for the integral f_at_qpts ??? comp (tuple) A component ??? (Optional) shp (tuple) The shape ??? (Optional) """ qpts, qwts = Q.get_points(), Q.get_weights() pt_dict = OrderedDict() self.comp = comp for i in range(len(qpts)): pt_cur = tuple(qpts[i]) pt_dict[pt_cur] = [(qwts[i] * f_at_qpts[i], comp)] Functional.__init__(self, ref_el, shp, pt_dict, {}, "IntegralMoment" ) def to_riesz(self, poly_set): T = poly_set.get_reference_element() sd = T.get_spatial_dimension() es = poly_set.get_expansion_set() ed = poly_set.get_embedded_degree() pts = list(self.pt_dict.keys()) bfs = es.tabulate(ed, pts) wts = numpy.array([foo[0][0] for foo in list(self.pt_dict.values())]) result = numpy.zeros(poly_set.coeffs.shape[1:], "d") result[self.comp, :] = numpy.dot(bfs, wts) return result class FrobeniusIntegralMoment(Functional): def __init__(self, ref_el, Q, f_at_qpts): # f_at_qpts is num components x num_qpts if len(Q.get_points()) != f_at_qpts.shape[1]: raise Exception("Mismatch in number of quadrature points and values") # make sure that shp is same shape as f given shp = (f_at_qpts.shape[0],) qpts, qwts = Q.get_points(), Q.get_weights() pt_dict = {} for i in range(len(qpts)): pt_cur = tuple(qpts[i]) pt_dict[pt_cur] = [(qwts[i] * f_at_qpts[j, i], (j,)) for j in range(f_at_qpts.shape[0])] Functional.__init__(self, ref_el, shp, pt_dict, {}, "FrobeniusIntegralMoment" ) # point normals happen on a d-1 dimensional facet # pt is the "physical" point on that facet class PointNormalEvaluation(Functional): """Implements the evaluation of the normal component of a vector at a point on a facet of codimension 1.""" def __init__(self, ref_el, facet_no, pt): n = ref_el.compute_normal(facet_no) self.n = n sd = ref_el.get_spatial_dimension() pt_dict = {pt: [(n[i], (i,)) for i in range(sd)]} shp = (sd,) Functional.__init__(self, ref_el, shp, pt_dict, {}, "PointNormalEval" ) return class PointEdgeTangentEvaluation(Functional): """Implements the evaluation of the tangential component of a vector at a point on a facet of dimension 1.""" def __init__(self, ref_el, edge_no, pt): t = ref_el.compute_edge_tangent(edge_no) self.t = t sd = ref_el.get_spatial_dimension() pt_dict = {pt: [(t[i], (i,)) for i in range(sd)]} shp = (sd,) Functional.__init__(self, ref_el, shp, pt_dict, {}, "PointEdgeTangent" ) def tostr(self): x = list(map(str, list(self.pt_dict.keys())[0])) return "(u.t)(%s)" % (','.join(x),) def to_riesz(self, poly_set): # should be singleton xs = list(self.pt_dict.keys()) phis = poly_set.get_expansion_set().tabulate(poly_set.get_embedded_degree(), xs) return numpy.outer(self.t, phis) class PointFaceTangentEvaluation(Functional): """Implements the evaluation of a tangential component of a vector at a point on a facet of codimension 1.""" def __init__(self, ref_el, face_no, tno, pt): t = ref_el.compute_face_tangents(face_no)[tno] self.t = t self.tno = tno sd = ref_el.get_spatial_dimension() pt_dict = {pt: [(t[i], (i,)) for i in range(sd)]} shp = (sd,) Functional.__init__(self, ref_el, shp, pt_dict, {}, "PointFaceTangent" ) def tostr(self): x = list(map(str, list(self.pt_dict.keys())[0])) return "(u.t%d)(%s)" % (self.tno, ','.join(x),) def to_riesz(self, poly_set): xs = list(self.pt_dict.keys()) phis = poly_set.get_expansion_set().tabulate(poly_set.get_embedded_degree(), xs) return numpy.outer(self.t, phis) class PointScaledNormalEvaluation(Functional): """Implements the evaluation of the normal component of a vector at a point on a facet of codimension 1, where the normal is scaled by the volume of that facet.""" def __init__(self, ref_el, facet_no, pt): self.n = ref_el.compute_scaled_normal(facet_no) sd = ref_el.get_spatial_dimension() shp = (sd,) pt_dict = {pt: [(self.n[i], (i,)) for i in range(sd)]} Functional.__init__(self, ref_el, shp, pt_dict, {}, "PointScaledNormalEval" ) return def tostr(self): x = list(map(str, list(self.pt_dict.keys())[0])) return "(u.n)(%s)" % (','.join(x),) def to_riesz(self, poly_set): xs = list(self.pt_dict.keys()) phis = poly_set.get_expansion_set().tabulate(poly_set.get_embedded_degree(), xs) return numpy.outer(self.n, phis) class PointwiseInnerProductEvaluation(Functional): """ This is a functional on symmetric 2-tensor fields. Let u be such a field, p be a point, and v,w be vectors. This implements the evaluation v^T u(p) w. Clearly v^iu_{ij}w^j = u_{ij}v^iw^j. Thus the value can be computed from the Frobenius inner product of u with wv^T. This gives the correct weights. """ def __init__(self, ref_el, v, w, p): sd = ref_el.get_spatial_dimension() wvT = numpy.outer(w, v) pt_dict = {p: [(wvT[i][j], (i, j, )) for [i, j] in index_iterator((sd, sd))]} shp = (sd, sd, ) Functional.__init__(self, ref_el, shp, pt_dict, {}, "PointwiseInnerProductEval" ) return def moments_against_set(ref_el, U, Q): # check that U and Q are both over ref_el qpts = Q.get_points() qwts = Q.get_weights() Uvals = U.tabulate(pts) # handle scalar case for i in range(Uvals.shape[0]): # loop over members of U pass if __name__ == "__main__": # test functionals from . import polynomial_set, reference_element ref_el = reference_element.DefaultTriangle() sd = ref_el.get_spatial_dimension() U = polynomial_set.ONPolynomialSet(ref_el, 5) f = PointDerivative(ref_el, (0.0, 0.0), (1, 0)) print(numpy.allclose(Functional.to_riesz(f, U), f.to_riesz(U))) f = PointNormalDerivative(ref_el, 0, (0.0, 0.0)) print(numpy.allclose(Functional.to_riesz(f, U), f.to_riesz(U))) fiat-1.6.0/FIAT/hermite.py000066400000000000000000000057151255003405100151760ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, polynomial_set, dual_set, functional class CubicHermiteDualSet( dual_set.DualSet ): """The dual basis for Lagrange elements. This class works for simplices of any dimension. Nodes are point evaluation at equispaced points.""" def __init__( self, ref_el ): entity_ids = {} nodes = [] cur = 0 # make nodes by getting points # need to do this dimension-by-dimension, facet-by-facet top = ref_el.get_topology() verts = ref_el.get_vertices() sd = ref_el.get_spatial_dimension() # get jet at each vertex entity_ids[0] = {} for v in sorted( top[0] ): nodes.append( functional.PointEvaluation( ref_el, verts[v] ) ) pd = functional.PointDerivative for i in range( sd ): alpha = [0] * sd alpha[i] = 1 nodes.append( pd( ref_el, verts[v], alpha ) ) entity_ids[0][v] = list(range(cur, cur+1+sd)) cur += sd + 1 # no edge dof entity_ids[1] = {} # face dof # point evaluation at barycenter entity_ids[2] = {} for f in sorted( top[2] ): pt = ref_el.make_points( 2, f, 3 )[0] n = functional.PointEvaluation( ref_el, pt ) nodes.append( n ) entity_ids[2] = list(range(cur, cur+1)) cur += 1 for dim in range(3, sd+1): entity_ids[dim] = {} for facet in top[dim]: entity_ids[dim][facet] = [] dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class CubicHermite( finite_element.FiniteElement ): """The Lagrange finite element. It is what it is.""" def __init__( self, ref_el ): poly_set = polynomial_set.ONPolynomialSet( ref_el, 3 ) dual = CubicHermiteDualSet( ref_el ) finite_element.FiniteElement.__init__( self, poly_set, dual, 3 ) if __name__=="__main__": from . import reference_element T = reference_element.DefaultTetrahedron() U = CubicHermite( T ) Ufs = U.get_nodal_basis() pts = T.make_lattice( 3 ) print(pts) print(list(Ufs.tabulate(pts).values())[0]) fiat-1.6.0/FIAT/jacobi.py000066400000000000000000000077151255003405100147720ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . """Several functions related to the one-dimensional jacobi polynomials: Evaluation, evaluation of derivatives, plus computation of the roots via Newton's method. These mainly are used in defining the expansion functions over the simplices and in defining quadrature rules over each domain.""" import math, numpy def eval_jacobi(a, b, n, x): """Evaluates the nth jacobi polynomial with weight parameters a,b at a point x. Recurrence relations implemented from the pseudocode given in Karniadakis and Sherwin, Appendix B""" if 0 == n: return 1.0; elif 1 == n: return 0.5 * ( a - b + ( a + b + 2.0 ) * x ) else: # 2 <= n apb = a + b pn2 = 1.0 pn1 = 0.5 * ( a - b + ( apb + 2.0 ) * x ) p = 0 for k in range(2, n+1): a1 = 2.0 * k * ( k + apb ) * ( 2.0 * k + apb - 2.0 ) a2 = ( 2.0 * k + apb - 1.0 ) * ( a * a - b * b ) a3 = ( 2.0 * k + apb - 2.0 ) \ * ( 2.0 * k + apb - 1.0 ) \ * ( 2.0 * k + apb ) a4 = 2.0 * ( k + a - 1.0 ) * ( k + b - 1.0 ) \ * ( 2.0 * k + apb ) a2 = a2 / a1 a3 = a3 / a1 a4 = a4 / a1 p = ( a2 + a3 * x ) * pn1 - a4 * pn2 pn2 = pn1 pn1 = p return p def eval_jacobi_batch(a, b, n, xs): """Evaluates all jacobi polynomials with weights a,b up to degree n. xs is a numpy.array of points. Returns a two-dimensional array of points, where the rows correspond to the Jacobi polynomials and the columns correspond to the points.""" result = numpy.zeros((n+1, len(xs)), xs.dtype) # hack to make sure AD type is propogated through for ii in range(result.shape[1]): result[0, ii] = 1.0 + xs[ii, 0] - xs[ii, 0] xsnew = xs.reshape((-1,)) if n > 0: result[1,:] = 0.5 * ( a - b + ( a + b + 2.0 ) * xsnew ) apb = a + b for k in range(2, n+1): a1 = 2.0 * k * ( k + apb ) * ( 2.0 * k + apb - 2.0 ) a2 = ( 2.0 * k + apb - 1.0 ) * ( a * a - b * b ) a3 = ( 2.0 * k + apb - 2.0 ) \ * ( 2.0 * k + apb - 1.0 ) \ * ( 2.0 * k + apb ) a4 = 2.0 * ( k + a - 1.0 ) * ( k + b - 1.0 ) \ * ( 2.0 * k + apb ) a2 = a2 / a1 a3 = a3 / a1 a4 = a4 / a1 result[k,:] = ( a2 + a3 * xsnew ) * result[k-1,:] \ - a4 * result[k-2,:] return result def eval_jacobi_deriv(a, b, n, x): """Evaluates the first derivative of P_{n}^{a,b} at a point x.""" if n == 0: return 0.0 else: return 0.5 * ( a + b + n + 1 ) * eval_jacobi(a+1, b+1, n-1, x) def eval_jacobi_deriv_batch(a, b, n, xs): """Evaluates the first derivatives of all jacobi polynomials with weights a,b up to degree n. xs is a numpy.array of points. Returns a two-dimensional array of points, where the rows correspond to the Jacobi polynomials and the columns correspond to the points.""" results = numpy.zeros( (n+1, len(xs)), "d" ) if n == 0: return results else: results[1:,:] = eval_jacobi_batch(a+1, b+1, n-1, xs) for j in range(1, n+1): results[j,:] *= 0.5*(a+b+j+1) return results fiat-1.6.0/FIAT/lagrange.py000066400000000000000000000051431255003405100153140ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, polynomial_set, dual_set, functional class LagrangeDualSet( dual_set.DualSet ): """The dual basis for Lagrange elements. This class works for simplices of any dimension. Nodes are point evaluation at equispaced points.""" def __init__( self, ref_el, degree ): entity_ids = {} nodes = [] # make nodes by getting points # need to do this dimension-by-dimension, facet-by-facet top = ref_el.get_topology() cur = 0 for dim in sorted( top ): entity_ids[dim] = {} for entity in sorted( top[dim] ): pts_cur = ref_el.make_points( dim, entity, degree ) nodes_cur = [ functional.PointEvaluation( ref_el, x ) \ for x in pts_cur ] nnodes_cur = len( nodes_cur ) nodes += nodes_cur entity_ids[dim][entity] = list(range(cur, cur+nnodes_cur)) cur += nnodes_cur dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class Lagrange( finite_element.FiniteElement ): """The Lagrange finite element. It is what it is.""" def __init__( self, ref_el, degree ): poly_set = polynomial_set.ONPolynomialSet( ref_el, degree ) dual = LagrangeDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree ) if __name__=="__main__": from . import reference_element # UFC triangle and points T = reference_element.UFCTriangle() pts = T.make_lattice(1) # pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] # FIAT triangle and points # T = reference_element.DefaultTriangle() # pts = [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0)] L = Lagrange(T, 1) Ufs = L.get_nodal_basis() print(pts) for foo, bar in list(Ufs.tabulate( pts, 1 ).items()): print(foo) print(bar) print() fiat-1.6.0/FIAT/makelags.py000066400000000000000000000036141255003405100153210ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import lagrange from . import reference_element import string import numpy lagclass = \ """class Lagrange%s%d: public FiniteElement { public: Lagrange%s%d():FiniteElement(%d,%d,%d,%d,%d,%s) {} virtual ~Lagrange%s%d(){} };""" def array_to_C_string( u ): x = [ str( a ) for a in u ] return "{ %s }" % ( string.join( x, " , " ) ) def matrix_to_array( mat, mat_name ): (num_rows, num_cols) = mat.shape # get C array of data u = numpy.ravel( numpy.transpose( mat ) ) array_name = mat_name return \ """static double %s[] = %s;""" % ( array_name, \ array_to_C_string( u ) ) T = reference_element.DefaultTriangle() shape = "Triangle" for i in range(3, 4): L = lagrange.Lagrange(T, i) nb = L.get_nodal_basis() vdm = nb.get_coeffs() array_name="Lagrange%s%dCoeffs"%(shape, i) print(matrix_to_array( vdm, array_name )) print(lagclass % (shape, i, shape, i,\ nb.get_degree(), \ nb.get_embedded_degree(), \ 2,\ nb.get_num_members(), \ nb.get_num_members(), \ array_name, shape, i)) fiat-1.6.0/FIAT/morley.py000066400000000000000000000050661255003405100150470ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import finite_element, polynomial_set, dual_set, functional class MorleyDualSet( dual_set.DualSet ): """The dual basis for Lagrange elements. This class works for simplices of any dimension. Nodes are point evaluation at equispaced points.""" def __init__( self, ref_el ): entity_ids = {} nodes = [] cur = 0 # make nodes by getting points # need to do this dimension-by-dimension, facet-by-facet top = ref_el.get_topology() verts = ref_el.get_vertices() sd = ref_el.get_spatial_dimension() if sd != 2: raise Exception("Illegal spatial dimension") pd = functional.PointDerivative # vertex point evaluations entity_ids[0] = {} for v in sorted( top[0] ): nodes.append( functional.PointEvaluation( ref_el, verts[v] ) ) entity_ids[0][v] = [cur] cur += 1 # edge dof -- normal at each edge midpoint entity_ids[1] = {} for e in sorted( top[1] ): pt = ref_el.make_points( 1, e, 2 )[0] n = functional.PointNormalDerivative( ref_el, e, pt ) nodes.append( n ) entity_ids[1][e] = [cur] cur += 1 dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class Morley( finite_element.FiniteElement ): """The Morley finite element.""" def __init__( self, ref_el ): poly_set = polynomial_set.ONPolynomialSet( ref_el, 2 ) dual = MorleyDualSet( ref_el ) finite_element.FiniteElement.__init__( self, poly_set, dual, 2 ) if __name__=="__main__": from . import reference_element T = reference_element.DefaultTriangle() U = Morley( T ) Ufs = U.get_nodal_basis() pts = T.make_lattice( 1 ) print(pts) print(list(Ufs.tabulate(pts).values())[0]) fiat-1.6.0/FIAT/nedelec.py000066400000000000000000000307551255003405100151420ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import polynomial_set, expansions, quadrature, dual_set, \ finite_element, functional from functools import reduce import numpy def NedelecSpace2D( ref_el, k ): """Constructs a basis for the 2d H(curl) space of the first kind which is (P_k)^2 + P_k rot( x )""" sd = ref_el.get_spatial_dimension() if sd != 2: raise Exception("NedelecSpace2D requires 2d reference element") vec_Pkp1 = polynomial_set.ONPolynomialSet( ref_el, k+1, (sd,) ) dimPkp1 = expansions.polynomial_dimension( ref_el, k+1 ) dimPk = expansions.polynomial_dimension( ref_el, k ) dimPkm1 = expansions.polynomial_dimension( ref_el, k-1 ) vec_Pk_indices = reduce( lambda a, b: a+b, \ [ list(range(i*dimPkp1, i*dimPkp1+dimPk)) \ for i in range(sd) ] ) vec_Pk_from_Pkp1 = vec_Pkp1.take( vec_Pk_indices ) Pkp1 = polynomial_set.ONPolynomialSet( ref_el, k + 1 ) PkH = Pkp1.take( list(range(dimPkm1, dimPk)) ) Q = quadrature.make_quadrature( ref_el, 2 * k + 2 ) Qpts = numpy.array( Q.get_points() ) Qwts = numpy.array( Q.get_weights() ) zero_index = tuple( [ 0 for i in range(sd) ] ) PkH_at_Qpts = PkH.tabulate( Qpts )[zero_index] Pkp1_at_Qpts = Pkp1.tabulate( Qpts )[zero_index] PkH_crossx_coeffs = numpy.zeros( (PkH.get_num_members(), \ sd, \ Pkp1.get_num_members()), "d" ) def rot_x_foo( a ): if a == 0: return 1, 1.0 elif a == 1: return 0, -1.0 for i in range( PkH.get_num_members() ): for j in range( sd ): (ind, sign) = rot_x_foo( j ) for k in range( Pkp1.get_num_members() ): PkH_crossx_coeffs[i, j, k] = sign * sum( Qwts * PkH_at_Qpts[i,:] * Qpts[:, ind] * Pkp1_at_Qpts[k,:] ) # for l in range( len( Qpts ) ): # PkH_crossx_coeffs[i,j,k] += Qwts[ l ] \ # * PkH_at_Qpts[i,l] \ # * Qpts[l][ind] \ # * Pkp1_at_Qpts[k,l] \ # * sign PkHcrossx = polynomial_set.PolynomialSet( ref_el, \ k + 1, \ k + 1, \ vec_Pkp1.get_expansion_set(), \ PkH_crossx_coeffs, \ vec_Pkp1.get_dmats() ) return polynomial_set.polynomial_set_union_normalized( vec_Pk_from_Pkp1, \ PkHcrossx ) def NedelecSpace3D( ref_el, k ): """Constructs a nodal basis for the 3d first-kind Nedelec space""" sd = ref_el.get_spatial_dimension() if sd != 3: raise Exception("NedelecSpace3D requires 3d reference element") vec_Pkp1 = polynomial_set.ONPolynomialSet( ref_el, k + 1, \ (sd,) ) dimPkp1 = expansions.polynomial_dimension( ref_el, k + 1 ) dimPk = expansions.polynomial_dimension( ref_el, k ) if k > 0: dimPkm1 = expansions.polynomial_dimension( ref_el, k - 1 ) else: dimPkm1 = 0 vec_Pk_indices = reduce( lambda a, b: a + b, \ [ list(range( i * dimPkp1, i * dimPkp1+dimPk)) \ for i in range(sd) ] ) vec_Pk = vec_Pkp1.take( vec_Pk_indices ) vec_Pke_indices = reduce( lambda a, b : a + b, \ [ list(range(i*dimPkp1+dimPkm1, i*dimPkp1+dimPk)) \ for i in range(sd) ] ) vec_Pke = vec_Pkp1.take( vec_Pke_indices ) Pkp1 = polynomial_set.ONPolynomialSet( ref_el, k + 1 ) Q = quadrature.make_quadrature( ref_el, 2 * ( k + 1 ) ) Qpts = numpy.array(Q.get_points()) Qwts = numpy.array(Q.get_weights()) zero_index = tuple( [ 0 for i in range(sd) ] ) PkCrossXcoeffs = numpy.zeros( (vec_Pke.get_num_members(), \ sd, \ Pkp1.get_num_members()), "d" ) Pke_qpts = vec_Pke.tabulate( Qpts )[zero_index] Pkp1_at_Qpts = Pkp1.tabulate( Qpts )[ zero_index ] for i in range( vec_Pke.get_num_members() ): for j in range( sd ): # vector components qwts_cur_bf_val = ( Qpts[:, (j+2)%3]*Pke_qpts[i, (j+1)%3,:] \ - Qpts[:, (j+1)%3] * Pke_qpts[i, (j+2)%3,:] ) * Qwts PkCrossXcoeffs[i, j,:] = numpy.dot( Pkp1_at_Qpts, qwts_cur_bf_val ) # for k in range( Pkp1.get_num_members() ): # PkCrossXcoeffs[i,j,k] = sum( Qwts * cur_bf_val * Pkp1_at_Qpts[k,:] ) # for l in range( len( Qpts ) ): # cur_bf_val = Qpts[l][(j+2)%3] \ # * Pke_qpts[i,(j+1)%3,l] \ # - Qpts[l][(j+1)%3] \ # * Pke_qpts[i,(j+2)%3,l] # PkCrossXcoeffs[i,j,k] += Qwts[l] \ # * cur_bf_val \ # * Pkp1_at_Qpts[k,l] PkCrossX = polynomial_set.PolynomialSet( ref_el, \ k + 1, \ k + 1, \ vec_Pkp1.get_expansion_set(), \ PkCrossXcoeffs, \ vec_Pkp1.get_dmats() ) return polynomial_set.polynomial_set_union_normalized( vec_Pk, \ PkCrossX ) class NedelecDual2D( dual_set.DualSet ): """Dual basis for first-kind Nedelec in 2d """ def __init__( self, ref_el, degree ): sd = ref_el.get_spatial_dimension() if sd != 2: raise Exception("Nedelec2D only works on triangles") nodes = [] t = ref_el.get_topology() num_edges = len( t[1] ) # edge tangents for i in range( num_edges ): pts_cur = ref_el.make_points( 1, i, degree + 2 ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointEdgeTangentEvaluation( ref_el, \ i, pt_cur ) nodes.append( f ) # internal moments if degree > 0: Q = quadrature.make_quadrature( ref_el, 2 * ( degree + 1 ) ) qpts = Q.get_points() Pkm1 = polynomial_set.ONPolynomialSet( ref_el, degree - 1 ) zero_index = tuple( [ 0 for i in range( sd ) ] ) Pkm1_at_qpts = Pkm1.tabulate( qpts )[ zero_index ] for d in range( sd ): for i in range( Pkm1_at_qpts.shape[0] ): phi_cur = Pkm1_at_qpts[i,:] l_cur = functional.IntegralMoment( ref_el, Q, \ phi_cur, (d,) ) nodes.append( l_cur ) entity_ids = {} # set to empty for i in range( sd + 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] cur = 0 # edges num_edge_pts = len( ref_el.make_points( 1, 0, degree + 2 ) ) for i in range( len( t[1] ) ): entity_ids[1][i] = list(range( cur, cur + num_edge_pts)) cur += num_edge_pts # moments against P_{degree-1} internally, if degree > 0 if degree > 0: num_internal_dof = sd * Pkm1_at_qpts.shape[0] entity_ids[2][0] = list(range( cur, cur + num_internal_dof)) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class NedelecDual3D( dual_set.DualSet ): """Dual basis for first-kind Nedelec in 3d """ def __init__( self, ref_el, degree ): sd = ref_el.get_spatial_dimension() if sd != 3: raise Exception("NedelecDual3D only works on tetrahedra") nodes = [] t = ref_el.get_topology() # how many edges num_edges = len( t[1] ) for i in range( num_edges ): # points to specify P_k on each edge pts_cur = ref_el.make_points( 1, i, degree + 2 ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointEdgeTangentEvaluation( ref_el, \ i, pt_cur ) nodes.append( f ) if degree > 0: # face tangents num_faces = len( t[2] ) for i in range( num_faces ): # loop over faces pts_cur = ref_el.make_points( 2, i, degree + 2 ) for j in range( len( pts_cur ) ): # loop over points pt_cur = pts_cur[j] for k in range(2): # loop over tangents f = functional.PointFaceTangentEvaluation( ref_el, \ i, k, \ pt_cur ) nodes.append( f ) if degree > 1: # internal moments Q = quadrature.make_quadrature( ref_el, 2 * ( degree + 1 ) ) qpts = Q.get_points() Pkm2 = polynomial_set.ONPolynomialSet( ref_el, degree - 2 ) zero_index = tuple( [ 0 for i in range( sd ) ] ) Pkm2_at_qpts = Pkm2.tabulate( qpts )[ zero_index ] for d in range( sd ): for i in range( Pkm2_at_qpts.shape[0] ): phi_cur = Pkm2_at_qpts[i,:] f = functional.IntegralMoment( ref_el, Q, \ phi_cur, (d,) ) nodes.append( f ) entity_ids = {} # set to empty for i in range( sd + 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] cur = 0 # edge dof num_pts_per_edge = len( ref_el.make_points( 1, 0, degree + 2 ) ) for i in range( len( t[1] ) ): entity_ids[1][i] = list(range( cur, cur + num_pts_per_edge)) cur += num_pts_per_edge # face dof if degree > 0: num_pts_per_face = len( ref_el.make_points( 2, 0, degree + 2 ) ) for i in range( len( t[2] ) ): entity_ids[2][i] = list(range( cur, cur + 2 * num_pts_per_face)) cur += 2 * num_pts_per_face if degree > 1: num_internal_dof = Pkm2_at_qpts.shape[0] * sd entity_ids[3][0] = list(range( cur, cur + num_internal_dof)) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class Nedelec( finite_element.FiniteElement ): """Nedelec finite element""" def __init__( self, ref_el, q ): degree = q - 1 if ref_el.get_spatial_dimension() == 3: poly_set = NedelecSpace3D( ref_el, degree ) dual = NedelecDual3D( ref_el, degree ) elif ref_el.get_spatial_dimension() == 2: poly_set = NedelecSpace2D( ref_el, degree ) dual = NedelecDual2D( ref_el, degree) else: raise Exception("Not implemented") finite_element.FiniteElement.__init__( self, poly_set, dual, degree, mapping="covariant piola") if __name__ == "__main__": from . import reference_element T = reference_element.DefaultTriangle( ) sd = T.get_spatial_dimension() for k in range( 1 ): N = Nedelec( T, k ) Nfs = N.get_nodal_basis() pts = T.make_lattice( 1 ) vals = Nfs.tabulate( pts, 1 ) for foo in sorted( vals ): print(foo) print(vals[foo]) fiat-1.6.0/FIAT/nedelec_second_kind.py000066400000000000000000000212031255003405100174660ustar00rootroot00000000000000# Copyright (C) 2010-2012 Marie E. Rognes # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . import numpy from .finite_element import FiniteElement from .dual_set import DualSet from .polynomial_set import ONPolynomialSet from .functional import PointEdgeTangentEvaluation as Tangent from .functional import FrobeniusIntegralMoment as IntegralMoment from .raviart_thomas import RaviartThomas from .quadrature import make_quadrature, UFCTetrahedronFaceQuadratureRule from .reference_element import UFCTriangle, UFCTetrahedron class NedelecSecondKindDual(DualSet): """ This class represents the dual basis for the Nedelec H(curl) elements of the second kind. The degrees of freedom (L) for the elements of the k'th degree are d = 2: vertices: None edges: L(f) = f (x_i) * t for (k+1) points x_i on each edge cell: L(f) = \int f * g * dx for g in RT_{k-1} d = 3: vertices: None edges: L(f) = f(x_i) * t for (k+1) points x_i on each edge faces: L(f) = \int_F f * g * ds for g in RT_{k-1}(F) for each face F cell: L(f) = \int f * g * dx for g in RT_{k-2} Higher spatial dimensions are not yet implemented. (For d = 1, these elements coincide with the CG_k elements.) """ def __init__ (self, cell, degree): # Define degrees of freedom (dofs, ids) = self.generate_degrees_of_freedom(cell, degree) # Call init of super-class DualSet.__init__(self, dofs, cell, ids) def generate_degrees_of_freedom(self, cell, degree): "Generate dofs and geometry-to-dof maps (ids)." dofs = [] ids = {} # Extract spatial dimension and topology d = cell.get_spatial_dimension() assert (d in (2, 3)), "Second kind Nedelecs only implemented in 2/3D." topology = cell.get_topology() # Zero vertex-based degrees of freedom (d+1 of these) ids[0] = dict(list(zip(list(range(d+1)), ([] for i in range(d+1))))) # (d+1) degrees of freedom per entity of codimension 1 (edges) (edge_dofs, edge_ids) = self._generate_edge_dofs(cell, degree, 0) dofs.extend(edge_dofs) ids[1] = edge_ids # Include face degrees of freedom if 3D if d == 3: (face_dofs, face_ids) = self._generate_face_dofs(cell, degree, len(dofs)) dofs.extend(face_dofs) ids[2] = face_ids # Varying degrees of freedom (possibly zero) per cell (cell_dofs, cell_ids) = self._generate_cell_dofs(cell, degree, len(dofs)) dofs.extend(cell_dofs) ids[d] = cell_ids return (dofs, ids) def _generate_edge_dofs(self, cell, degree, offset): """Generate degrees of freedoms (dofs) for entities of codimension 1 (edges).""" # (degree+1) tangential component point evaluation degrees of # freedom per entity of codimension 1 (edges) dofs = [] ids = {} for edge in range(len(cell.get_topology()[1])): # Create points for evaluation of tangential components points = cell.make_points(1, edge, degree + 2) # A tangential component evaluation for each point dofs += [Tangent(cell, edge, point) for point in points] # Associate these dofs with this edge i = len(points)*edge ids[edge] = list(range(offset + i, offset + i + len(points))) return (dofs, ids) def _generate_face_dofs(self, cell, degree, offset): """Generate degrees of freedoms (dofs) for faces.""" # Initialize empty dofs and identifiers (ids) dofs = [] ids = dict(list(zip(list(range(4)), ([] for i in range(4))))) # Return empty info if not applicable d = cell.get_spatial_dimension() if (degree < 2): return (dofs, ids) msg = "2nd kind Nedelec face dofs only available with UFC convention" assert isinstance(cell, UFCTetrahedron), msg # Iterate over the faces of the tet num_faces = len(cell.get_topology()[2]) for face in range(num_faces): # Construct quadrature scheme for this face m = 2*(degree + 1) Q_face = UFCTetrahedronFaceQuadratureRule(face, m) quad_points = Q_face.get_points() # Construct Raviart-Thomas of (degree - 1) on the # reference face reference_face = Q_face.reference_rule().ref_el RT = RaviartThomas(reference_face, degree - 1) num_rts = RT.space_dimension() # Evaluate RT basis functions at reference quadrature # points ref_quad_points = Q_face.reference_rule().get_points() num_quad_points = len(ref_quad_points) Phi = RT.get_nodal_basis() Phis = Phi.tabulate(ref_quad_points)[(0, 0)] # Note: Phis has dimensions: # num_basis_functions x num_components x num_quad_points # Map Phis -> phis (reference values to physical values) J = Q_face.jacobian() scale = 1.0/numpy.sqrt(numpy.linalg.det(J.transpose()*J)) phis = numpy.ndarray((d, num_quad_points)) for i in range(num_rts): for q in range(num_quad_points): phi_i_q = scale*J*numpy.matrix(Phis[i,:, q]).transpose() for j in range(d): phis[j, q] = phi_i_q[j] # Construct degrees of freedom as integral moments on # this cell, using the special face quadrature # weighted against the values of the (physical) # Raviart--Thomas'es on the face dofs += [IntegralMoment(cell, Q_face, phis)] # Assign identifiers (num RTs per face + previous edge dofs) ids[face] = list(range(offset + num_rts*face, offset + num_rts*(face+1))) return (dofs, ids) def _generate_cell_dofs(self, cell, degree, offset): """Generate degrees of freedoms (dofs) for entities of codimension d (cells).""" # Return empty info if not applicable d = cell.get_spatial_dimension() if (d == 2 and degree < 2) or (d == 3 and degree < 3): return ([], {0: []}) # Create quadrature points Q = make_quadrature(cell, 2*(degree+1)) qs = Q.get_points() # Create Raviart-Thomas nodal basis RT = RaviartThomas(cell, degree + 1 - d) phi = RT.get_nodal_basis() # Evaluate Raviart-Thomas basis at quadrature points phi_at_qs = phi.tabulate(qs)[(0,)*d] # Use (Frobenius) integral moments against RTs as dofs dofs = [IntegralMoment(cell, Q, phi_at_qs[i,:]) for i in range(len(phi_at_qs))] # Associate these dofs with the interior ids = {0: list(range(offset, offset + len(dofs)))} return (dofs, ids) class NedelecSecondKind(FiniteElement): """ The H(curl) Nedelec elements of the second kind on triangles and tetrahedra: the polynomial space described by the full polynomials of degree k, with a suitable set of degrees of freedom to ensure H(curl) conformity. """ def __init__(self, cell, degree): # Check degree assert(degree >= 1), "Second kind Nedelecs start at 1!" # Get dimension d = cell.get_spatial_dimension() # Construct polynomial basis for d-vector fields Ps = ONPolynomialSet(cell, degree, (d, )) # Construct dual space Ls = NedelecSecondKindDual(cell, degree) # Set mapping mapping = "covariant piola" # Call init of super-class FiniteElement.__init__(self, Ps, Ls, degree, mapping=mapping) if __name__=="__main__": for k in range(1, 4): T = UFCTriangle() N2curl = NedelecSecondKind(T, k) for k in range(1, 4): T = UFCTetrahedron() N2curl = NedelecSecondKind(T, k) Nfs = N2curl.get_nodal_basis() pts = T.make_lattice( 1 ) vals = Nfs.tabulate( pts, 1 ) fiat-1.6.0/FIAT/newdubiner.py000066400000000000000000000160321255003405100156750ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . import numpy def jrc(a, b, n, num_type): an = num_type((2*n+1+a+b)*(2*n+2+a+b)) \ / num_type(2*(n+1)*(n+1+a+b)) bn = num_type((a*a-b*b) * (2*n+1+a+b)) \ / num_type(2*(n+1)*(2*n+a+b)*(n+1+a+b)) cn = num_type((n+a)*(n+b)*(2*n+2+a+b)) \ / num_type((n+1)*(n+1+a+b)*(2*n+a+b)) return an, bn, cn def lattice_iter(start, finish, depth): """Generator iterating over the depth-dimensional lattice of integers between start and (finish-1). This works on simplices in 1d, 2d, 3d, and beyond""" if depth == 0: return elif depth == 1: for ii in range(start, finish): yield [ii] else: for ii in range(start, finish): for jj in lattice_iter(start, finish-ii, depth - 1): yield [ii] + jj def make_lattice(n, vs, numtype): hs = numpy.array([(vs[i] - vs[0]) / numtype(n) for i in range(1, len(vs))] ) result = [] m = len(hs) for indices in lattice_iter(0, n+1, m): res_cur = vs[0].copy() for i in range(len(indices)): res_cur += indices[i] * hs[m-i-1] result.append(res_cur) return numpy.array(result) def make_triangle_lattice(n, numtype): vs = numpy.array([(numtype(-1), numtype(-1)), (numtype(1), numtype(-1)), (numtype(-1), numtype(1))]) return make_lattice(n, vs, numtype) def make_tetrahedron_lattice(n, numtype): vs = numpy.array([(numtype(-1), numtype(-1), numtype(-1)), (numtype(1), numtype(-1), numtype(-1)), (numtype(-1), numtype(1), numtype(-1)), (numtype(-1), numtype(-1), numtype(1)) ]) return make_lattice(n, vs, numtype) def make_lattice_dim(D, n, numtype): if D == 2: return make_triangle_lattice(n, numtype) elif D == 3: return make_tetrahedron_lattice(n, numtype) def tabulate_triangle(n, pts, numtype): return _tabulate_triangle_single(n, numpy.array(pts).T, numtype) def _tabulate_triangle_single(n, pts, numtype): if len(pts) == 0: return numpy.array([], numtype) def idx(p, q): return (p+q)*(p+q+1)//2 + q results = (n+1)*(n+2)//2 * [None] results[0] = numtype(1) \ + pts[0] - pts[0] \ + pts[1] - pts[1] if n == 0: return results x = pts[0] y = pts[1] one = numtype(1) two = numtype(2) three = numtype(3) # foo = one + two*x + y f1 = (one+two*x+y)/two f2 = (one - y) / two f3 = f2**2 results[idx(1, 0), :] = f1 for p in range(1, n): a = (two * p + 1) / (1 + p) # b = p / (p + one) results[idx(p+1, 0)] = a * f1 * results[idx(p, 0), :] \ - p/(one+p) * f3 * results[idx(p-1, 0), :] for p in range(n): results[idx(p, 1)] = (one + two*p+(three+two*p)*y) / two \ * results[idx(p, 0)] for p in range(n-1): for q in range(1, n-p): (a1, a2, a3) = jrc(2*p+1, 0, q, numtype) results[idx(p, q+1)] = \ (a1 * y + a2) * results[idx(p, q)] \ - a3 * results[idx(p, q-1)] return results def tabulate_tetrahedron(n, pts, numtype): return _tabulate_tetrahedron_single(n, numpy.array(pts).T, numtype) def _tabulate_tetrahedron_single(n, pts, numtype): def idx(p, q, r): return (p+q+r)*(p+q+r+1)*(p+q+r+2)//6 + (q+r)*(q+r+1)//2 + r results = (n+1)*(n+2)*(n+3)//6 * [None] results[0] = 1.0 \ + pts[0] - pts[0] \ + pts[1] - pts[1] \ + pts[2] - pts[2] if n == 0: return results x = pts[0] y = pts[1] z = pts[2] one = numtype(1) two = numtype(2) three = numtype(3) factor1 = (two + two*x + y + z) / two factor2 = ((y+z)/two)**2 factor3 = (one + two * y + z) / two factor4 = (1 - z) / two factor5 = factor4 ** 2 results[idx(1, 0, 0)] = factor1 for p in range(1, n): a1 = (two * p + one) / (p + one) a2 = p / (p + one) results[idx(p+1, 0, 0)] = a1 * factor1 * results[idx(p, 0, 0)] \ - a2 * factor2 * results[idx(p-1, 0, 0)] for p in range(0, n): results[idx(p, 1, 0)] = results[idx(p, 0, 0)] \ * (p * (one + y) + (two + three * y + z) / two) for p in range(0, n-1): for q in range(1, n-p): (aq, bq, cq) = jrc(2*p+1, 0, q, numtype) qmcoeff = aq * factor3 + bq * factor4 qm1coeff = cq * factor5 results[idx(p, q+1, 0)] = qmcoeff * results[idx(p, q, 0)] \ - qm1coeff * results[idx(p, q-1, 0)] for p in range(n): for q in range(n-p): results[idx(p, q, 1)] = results[idx(p, q, 0)] \ * (one + p + q + (two + q + p) * z) for p in range(n-1): for q in range(0, n-p-1): for r in range(1, n-p-q): ar, br, cr = jrc(2*p+2*q+2, 0, r, numtype) results[idx(p, q, r+1)] = \ (ar * z + br) * results[idx(p, q, r)] \ - cr * results[idx(p, q, r-1)] return results def tabulate_tetrahedron_derivatives(n, pts, numtype): D = 3 order = 1 return tabulate_jet(D, n, pts, order, numtype) def tabulate(D, n, pts, numtype): return _tabulate_single(D, n, numpy.array(pts).T, numtype) def _tabulate_single(D, n, pts, numtype): if D == 2: return _tabulate_triangle_single(n, pts, numtype) elif D == 3: return _tabulate_tetrahedron_single(n, pts, numtype) def tabulate_jet(D, n, pts, order, numtype): from .expansions import _tabulate_dpts # Wrap the tabulator to allow for nondefault numtypes def tabulator_wrap(n, X): return _tabulate_single(D, n, X, numtype) data1 = _tabulate_dpts(tabulator_wrap, D, n, order, pts) # Put data in the required data structure, i.e., # k-tuples which contain the value, and the k-1 derivatives # (gradient, Hessian, ...) m = data1[0].shape[0] n = data1[0].shape[1] data2 = [[tuple([data1[r][i][j] for r in range(order+1)]) for j in range(n)] for i in range(m)] return data2 if __name__ == "__main__": import gmpy latticeK = 2 D = 3 pts = make_tetrahedron_lattice(latticeK, gmpy.mpq) vals = tabulate_tetrahedron_derivatives(D, pts, gmpy.mpq) print(vals) fiat-1.6.0/FIAT/polynomial_set.py000066400000000000000000000277451255003405100166060ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # polynomial sets # basic interface: # -- defined over some reference element # -- need to be able to tabulate (jets) # -- type of entry: could by scalar, numpy array, or object-value # (such as symmetric tensors, as long as they can be converted <--> # with 1d arrays) # Don't need the "Polynomial" class we had before, provided that # we have an interface for defining sets of functionals (moments against # an entire set of polynomials) from . import expansions import numpy from .functional import index_iterator def mis(m, n): """returns all m-tuples of nonnegative integers that sum up to n.""" if m == 1: return [(n,)] elif n == 0: return [tuple([0] * m)] else: return [tuple([n - i] + list(foo)) for i in range(n + 1) for foo in mis(m - 1, i) ] # We order coeffs by C_{i,j,k} # where i is the index into the polynomial set, # j may be an empty tuple (scalar polynomials) # or else a vector/tensor # k is the expansion function # so if I have all bfs at a given point x in an array bf, # then dot(coeffs, bf) gives the array of bfs class PolynomialSet: """Implements a set of polynomials as linear combinations of an expansion set over a reference element. ref_el: the reference element degree: an order labeling the space embedded degree: the degree of polynomial expansion basis that must be used to evaluate this space coeffs: A numpy array containing the coefficients of the expansion basis for each member of the set. Coeffs is ordered by coeffs[i,j,k] where i is the label of the member, k is the label of the expansion function, and j is a (possibly empty) tuple giving the index for a vector- or tensor-valued function. """ def __init__(self, ref_el, degree, embedded_degree, expansion_set, coeffs, dmats ): self.ref_el = ref_el self.num_members = coeffs.shape[0] self.degree = degree self.embedded_degree = embedded_degree self.expansion_set = expansion_set self.coeffs = coeffs self.dmats = dmats return def tabulate_new(self, pts): return numpy.dot(self.coeffs, self.expansion_set.tabulate(self.embedded_degree, pts)) def tabulate(self, pts, jet_order=0): """Returns the values of the polynomial set.""" result = {} base_vals = self.expansion_set.tabulate(self.embedded_degree, pts) for i in range(jet_order + 1): alphas = mis(self.ref_el.get_spatial_dimension(), i) for alpha in alphas: D = form_matrix_product(self.dmats, alpha) result[alpha] = numpy.dot(self.coeffs, numpy.dot(numpy.transpose(D), base_vals)) return result def get_expansion_set(self): return self.expansion_set def get_coeffs(self): return self.coeffs def get_num_members(self): return self.num_members def get_degree(self): return self.degree def get_embedded_degree(self): return self.embedded_degree def get_dmats(self): return self.dmats def get_reference_element(self): return self.ref_el def get_shape(self): """Returns the shape of phi(x), where () corresponds to scalar (2,) a vector of length 2, etc""" return self.coeffs.shape[1:-1] def take(self, items): """Extracts subset of polynomials given by items.""" new_coeffs = numpy.take(self.get_coeffs(), items, 0) return PolynomialSet(self.ref_el, self.degree, self.embedded_degree, self.expansion_set, new_coeffs, self.dmats) def to_sympy(self): import sys sys.path.append("..") #import FIAT_S import sympy #syms = FIAT_S.polynomials. \ # make_syms(self.get_reference_element().get_spatial_dimension()) #ds_nosub = FIAT_S.polynomials.dubs(self.get_embedded_degree(), syms) T1 = reference_element.DefaultReferenceElement() T2 = self.get_reference_element() A, b = reference_element.make_affine_mapping( T2.get_vertices(), T1.get_vertices() ) if len(self.coeffs.shape) == 2: return [sympy.Polynomial( sum([self.coeffs[i, j] * ds[j] for j in range(self.coeffs.shape[1])])) for i in range(self.coeffs.shape[0])] class ONPolynomialSet(PolynomialSet): """Constructs an orthonormal basis out of expansion set by having an identity matrix of coefficients. Can be used to specify ON bases for vector- and tensor-valued sets as well.""" def __init__(self, ref_el, degree, shape=tuple()): if shape == tuple(): num_components = 1 else: flat_shape = numpy.ravel(shape) num_components = numpy.prod(flat_shape) num_exp_functions = expansions.polynomial_dimension(ref_el, degree) num_members = num_components * num_exp_functions embedded_degree = degree expansion_set = expansions.get_expansion_set(ref_el) sd = ref_el.get_spatial_dimension() # set up coefficients coeffs_shape = tuple([num_members] + list(shape) + [num_exp_functions]) coeffs = numpy.zeros(coeffs_shape, "d") # use functional's index_iterator function cur_bf = 0 if shape == tuple(): coeffs = numpy.eye(num_members) else: for idx in index_iterator(shape): n = expansions.polynomial_dimension(ref_el, embedded_degree) for exp_bf in range(n): cur_idx = tuple([cur_bf] + list(idx) + [exp_bf]) coeffs[cur_idx] = 1.0 cur_bf += 1 # construct dmats if degree == 0: dmats = [numpy.array([[0.0]], "d") for i in range(sd) ] else: pts = ref_el.make_points(sd, 0, degree + sd + 1) v = numpy.transpose(expansion_set.tabulate(degree, pts)) vinv = numpy.linalg.inv(v) dv = expansion_set.tabulate_derivatives(degree, pts) dtildes = [[[a[1][i] for a in dvrow] for dvrow in dv] for i in range(sd) ] dmats = [numpy.dot(vinv, numpy.transpose(dtilde)) for dtilde in dtildes ] PolynomialSet.__init__(self, ref_el, degree, embedded_degree, expansion_set, coeffs, dmats ) def project(f, U, Q): """Computes the expansion coefficients of f in terms of the members of a polynomial set U. Numerical integration is performed by quadrature rule Q.""" pts = Q.get_points() wts = Q.get_weights() f_at_qps = [f(x) for x in pts] U_at_qps = U.tabulate(pts) coeffs = numpy.array([sum(wts * f_at_qps * phi) for phi in U_at_qps ]) return coeffs def form_matrix_product(mats, alpha): """forms product over mats[i]**alpha[i]""" m = mats[0].shape[0] result = numpy.eye(m) for i in range(len(alpha)): for j in range(alpha[i]): result = numpy.dot(mats[i], result) return result def polynomial_set_union_normalized(A, B): """Given polynomial sets A and B, constructs a new polynomial set whose span is the same as that of span(A) union span(B). It may not contain any of the same members of the set, as we construct a span via SVD.""" new_coeffs = numpy.array(list(A.coeffs) + list(B.coeffs)) func_shape = new_coeffs.shape[1:] if len(func_shape) == 1: (u, sig, vt) = numpy.linalg.svd(new_coeffs) num_sv = len([s for s in sig if abs(s) > 1.e-10]) coeffs = vt[:num_sv] else: new_shape0 = new_coeffs.shape[0] new_shape1 = numpy.prod(func_shape) newshape = (new_shape0, new_shape1) nc = numpy.reshape(new_coeffs, newshape) (u, sig, vt) = numpy.linalg.svd(nc, 1) num_sv = len([s for s in sig if abs(s) > 1.e-10]) coeffs = numpy.reshape(vt[:num_sv], tuple([num_sv] + list(func_shape)) ) return PolynomialSet(A.get_reference_element(), A.get_degree(), A.get_embedded_degree(), A.get_expansion_set(), coeffs, A.get_dmats()) class ONSymTensorPolynomialSet(PolynomialSet): """ Constructs an orthonormal basis for symmetric-tensor-valued polynomials on a reference element. """ def __init__(self, ref_el, degree, size = None): sd = ref_el.get_spatial_dimension() if size == None: size = sd shape = (size, size) num_exp_functions = expansions.polynomial_dimension(ref_el, degree) num_components = size * (size + 1) // 2 num_members = num_components * num_exp_functions embedded_degree = degree expansion_set = expansions.get_expansion_set(ref_el) # set up coefficients for symmetric tensors coeffs_shape = tuple([num_members] + list(shape) + [num_exp_functions]) coeffs = numpy.zeros(coeffs_shape, "d") cur_bf = 0 for [i, j] in index_iterator(shape): n = expansions.polynomial_dimension(ref_el, embedded_degree) if i == j: for exp_bf in range(n): cur_idx = tuple([cur_bf] + [i, j] + [exp_bf]) coeffs[cur_idx] = 1.0 cur_bf += 1 elif i < j: for exp_bf in range(n): cur_idx = tuple([cur_bf] + [i, j] + [exp_bf]) coeffs[cur_idx] = 1.0 cur_idx = tuple([cur_bf] + [j, i] + [exp_bf]) coeffs[cur_idx] = 1.0 cur_bf += 1 # construct dmats. this is the same as ONPolynomialSet. pts = ref_el.make_points(sd, 0, degree + sd + 1) v = numpy.transpose(expansion_set.tabulate(degree, pts)) vinv = numpy.linalg.inv(v) dv = expansion_set.tabulate_derivatives(degree, pts) dtildes = [[[a[1][i] for a in dvrow] for dvrow in dv] for i in range(sd)] dmats = [numpy.dot(vinv, numpy.transpose(dtilde)) for dtilde in dtildes] PolynomialSet.__init__(self, ref_el, degree, embedded_degree, expansion_set, coeffs, dmats ) if __name__ == "__main__": from . import reference_element T = reference_element.UFCTriangle() U = ONPolynomialSet(T, 2) print(U.coeffs[0:6, 0:6]) pts = T.make_lattice(3) jet = U.tabulate(pts, 1) for alpha in sorted(jet): print(alpha) print(jet[alpha]) # print U.get_shape() fiat-1.6.0/FIAT/quadrature.py000066400000000000000000000242271255003405100157150ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # # Modified by Marie E. Rognes (meg@simula.no), 2012 from . import reference_element, expansions, jacobi import math import numpy from .factorial import factorial class QuadratureRule: """General class that models integration over a reference element as the weighted sum of a function evaluated at a set of points.""" def __init__( self, ref_el, pts, wts ): self.ref_el = ref_el self.pts = pts self.wts = wts return def get_points( self ): return numpy.array(self.pts) def get_weights( self ): return numpy.array(self.wts) def integrate( self, f ): return sum( [ w * f(x) for (x, w) in zip(self.pts, self.wts) ] ) class GaussJacobiQuadratureLineRule( QuadratureRule ): """Gauss-Jacobi quadature rule determined by Jacobi weights a and b using m roots of m:th order Jacobi polynomial.""" # def __init__( self , ref_el , a , b , m ): def __init__( self, ref_el, m ): # this gives roots on the default (-1,1) reference element # (xs_ref,ws_ref) = compute_gauss_jacobi_rule( a , b , m ) (xs_ref, ws_ref) = compute_gauss_jacobi_rule( 0., 0., m ) Ref1 = reference_element.DefaultLine() A, b = reference_element.make_affine_mapping( Ref1.get_vertices(), \ ref_el.get_vertices() ) mapping = lambda x: numpy.dot( A, x ) + b scale = numpy.linalg.det( A ) xs = tuple( [ tuple( mapping( x_ref )[0] ) for x_ref in xs_ref ] ) ws = tuple( [ scale * w for w in ws_ref ] ) QuadratureRule.__init__( self, ref_el, xs, ws ) return class CollapsedQuadratureTriangleRule( QuadratureRule ): """Implements the collapsed quadrature rules defined in Karniadakis & Sherwin by mapping products of Gauss-Jacobi rules from the square to the triangle.""" def __init__( self, ref_el, m ): ptx, wx = compute_gauss_jacobi_rule(0., 0., m) pty, wy = compute_gauss_jacobi_rule(1., 0., m) # map ptx , pty pts_ref = [ expansions.xi_triangle( (x, y) ) \ for x in ptx for y in pty ] Ref1 = reference_element.DefaultTriangle() A, b = reference_element.make_affine_mapping( Ref1.get_vertices(), \ ref_el.get_vertices() ) mapping = lambda x: numpy.dot( A, x ) + b scale = numpy.linalg.det( A ) pts = tuple( [ tuple( mapping( x ) ) for x in pts_ref ] ) wts = [ 0.5 * scale * w1 * w2 for w1 in wx for w2 in wy ] QuadratureRule.__init__( self, ref_el, tuple( pts ), tuple( wts ) ) return class CollapsedQuadratureTetrahedronRule( QuadratureRule ): """Implements the collapsed quadrature rules defined in Karniadakis & Sherwin by mapping products of Gauss-Jacobi rules from the cube to the tetrahedron.""" def __init__( self, ref_el, m ): ptx, wx = compute_gauss_jacobi_rule(0., 0., m) pty, wy = compute_gauss_jacobi_rule(1., 0., m) ptz, wz = compute_gauss_jacobi_rule(2., 0., m) # map ptx , pty pts_ref = [ expansions.xi_tetrahedron( (x, y, z ) ) \ for x in ptx for y in pty for z in ptz ] Ref1 = reference_element.DefaultTetrahedron() A, b = reference_element.make_affine_mapping( Ref1.get_vertices(), \ ref_el.get_vertices() ) mapping = lambda x: numpy.dot( A, x ) + b scale = numpy.linalg.det( A ) pts = tuple( [ tuple( mapping( x ) ) for x in pts_ref ] ) wts = [ scale * 0.125 * w1 * w2 * w3 \ for w1 in wx for w2 in wy for w3 in wz ] QuadratureRule.__init__( self, ref_el, tuple( pts ), tuple( wts ) ) return class UFCTetrahedronFaceQuadratureRule(QuadratureRule): """Highly specialized quadrature rule for the face of a tetrahedron, mapped from a reference triangle, used for higher order Nedelecs""" def __init__(self, face_number, degree): # Create quadrature rule on reference triangle reference_triangle = reference_element.UFCTriangle() reference_rule = make_quadrature(reference_triangle, degree) ref_points = reference_rule.get_points() ref_weights = reference_rule.get_weights() # Get geometry information about the face of interest reference_tet = reference_element.UFCTetrahedron() face = reference_tet.get_topology()[2][face_number] vertices = reference_tet.get_vertices_of_subcomplex(face) # Use tet to map points and weights on the appropriate face vertices = [numpy.array(list(vertex)) for vertex in vertices] x0 = vertices[0] J = numpy.matrix([vertices[1] - x0, vertices[2] - x0]).transpose() x0 = numpy.matrix(x0).transpose() # This is just a very numpyfied way of writing J*p + x0: F = lambda p: \ numpy.array(J*numpy.matrix(p).transpose() + x0).flatten() points = numpy.array([F(p) for p in ref_points]) # Map weights: multiply reference weights by sqrt(|J^T J|) detJTJ = numpy.linalg.det(J.transpose()*J) weights = numpy.sqrt(detJTJ)*ref_weights # Initialize super class with new points and weights QuadratureRule.__init__(self, reference_tet, points, weights) self._reference_rule = reference_rule self._J = J def reference_rule(self): return self._reference_rule def jacobian(self): return self._J def make_quadrature( ref_el, m ): """Returns the collapsed quadrature rule using m points per direction on the given reference element.""" msg = "Expecting at least one (not %d) quadrature point per direction" % m assert (m > 0), msg if ref_el.get_shape() == reference_element.LINE: return GaussJacobiQuadratureLineRule( ref_el, m ) elif ref_el.get_shape() == reference_element.TRIANGLE: return CollapsedQuadratureTriangleRule( ref_el, m ) elif ref_el.get_shape() == reference_element.TETRAHEDRON: return CollapsedQuadratureTetrahedronRule( ref_el, m ) # rule to get Gauss-Jacobi points def compute_gauss_jacobi_points( a, b, m ): """Computes the m roots of P_{m}^{a,b} on [-1,1] by Newton's method. The initial guesses are the Chebyshev points. Algorithm implemented in Python from the pseudocode given by Karniadakis and Sherwin""" x = [] eps = 1.e-8 max_iter = 100 for k in range(0, m): r = -math.cos(( 2.0*k + 1.0) * math.pi / ( 2.0 * m ) ) if k > 0: r = 0.5 * ( r + x[k-1] ) j = 0 delta = 2 * eps while j < max_iter: s = 0 for i in range(0, k): s = s + 1.0 / ( r - x[i] ) f = jacobi.eval_jacobi(a, b, m, r) fp = jacobi.eval_jacobi_deriv(a, b, m, r) delta = f / (fp - f * s) r = r - delta if math.fabs(delta) < eps: break else: j = j + 1 x.append(r) return x def compute_gauss_jacobi_rule( a, b, m ): xs = compute_gauss_jacobi_points( a, b, m ) a1 = math.pow(2, a+b+1) a2 = gamma(a + m + 1) a3 = gamma(b + m + 1) a4 = gamma(a + b + m + 1) a5 = factorial(m) a6 = a1 * a2 * a3 / a4 / a5 ws = [ a6 / (1.0 - x**2.0) / jacobi.eval_jacobi_deriv(a, b, m, x)**2.0 \ for x in xs ] return xs, ws # A C implementation for ln_gamma function taken from Numerical # recipes in C: The art of scientific # computing, 2nd edition, Press, Teukolsky, Vetterling, Flannery, Cambridge # University press, page 214 # translated into Python by Robert Kirby # See originally Abramowitz and Stegun's Handbook of Mathematical Functions. def ln_gamma( xx ): cof = [76.18009172947146,\ -86.50532032941677, \ 24.01409824083091, \ -1.231739572450155, \ 0.1208650973866179e-2, \ -0.5395239384953e-5 ] y = xx x = xx tmp = x + 5.5 tmp -= (x + 0.5) * math.log(tmp) ser = 1.000000000190015 for j in range(0, 6): y = y + 1 ser += cof[j] / y return -tmp + math.log( 2.5066282746310005*ser/x ) def gamma( xx ): return math.exp( ln_gamma( xx ) ) if __name__ == "__main__": T = reference_element.DefaultTetrahedron() Q = make_quadrature( T, 6 ) es = expansions.get_expansion_set( T ) qpts = Q.get_points() qwts = Q.get_weights() phis = es.tabulate( 3, qpts ) foo = numpy.array( [ [ sum( [ qwts[k] * phis[i, k] * phis[j, k] \ for k in range( len( qpts ) ) ] ) \ for i in range( phis.shape[0] ) ] \ for j in range( phis.shape[0] ) ] ) # print qpts # print qwts #print foo cells = [(reference_element.default_simplex(i), reference_element.ufc_simplex(i)) for i in range(1, 4)] order = 1 for def_elem, ufc_elem in cells: print("\n\ndefault element") print(def_elem.get_vertices()) print("ufc element") print(ufc_elem.get_vertices()) qd = make_quadrature(def_elem, order) print("\ndefault points:") print(qd.get_points()) print("default weights:") print(qd.get_weights()) print("sum: ", sum(qd.get_weights())) qu = make_quadrature(ufc_elem, order) print("\nufc points:") print(qu.get_points()) print("ufc weights:") print(qu.get_weights()) print("sum: ", sum(qu.get_weights())) fiat-1.6.0/FIAT/raviart_thomas.py000066400000000000000000000143541255003405100165630ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import expansions, polynomial_set, quadrature, reference_element, dual_set, \ quadrature, finite_element, functional import numpy from functools import reduce def RTSpace( ref_el, deg ): """Constructs a basis for the the Raviart-Thomas space (P_k)^d + P_k x""" sd = ref_el.get_spatial_dimension() vec_Pkp1 = polynomial_set.ONPolynomialSet( ref_el, deg+1, (sd,) ) dimPkp1 = expansions.polynomial_dimension( ref_el, deg+1 ) dimPk = expansions.polynomial_dimension( ref_el, deg ) dimPkm1 = expansions.polynomial_dimension( ref_el, deg-1 ) vec_Pk_indices = reduce( lambda a, b: a+b, \ [ list(range(i*dimPkp1, i*dimPkp1+dimPk)) \ for i in range(sd) ] ) vec_Pk_from_Pkp1 = vec_Pkp1.take( vec_Pk_indices ) Pkp1 = polynomial_set.ONPolynomialSet( ref_el, deg + 1 ) PkH = Pkp1.take( list(range(dimPkm1, dimPk)) ) Q = quadrature.make_quadrature( ref_el, 2 * deg + 2 ) # have to work on this through "tabulate" interface # first, tabulate PkH at quadrature points Qpts = numpy.array( Q.get_points() ) Qwts = numpy.array( Q.get_weights() ) zero_index = tuple( [ 0 for i in range(sd) ] ) PkH_at_Qpts = PkH.tabulate( Qpts )[zero_index] Pkp1_at_Qpts = Pkp1.tabulate( Qpts )[zero_index] PkHx_coeffs = numpy.zeros( (PkH.get_num_members(), \ sd, \ Pkp1.get_num_members()), "d" ) for i in range( PkH.get_num_members() ): for j in range( sd ): fooij = PkH_at_Qpts[i,:] * Qpts[:, j] * Qwts PkHx_coeffs[i, j,:] = numpy.dot( Pkp1_at_Qpts, fooij ) PkHx = polynomial_set.PolynomialSet( ref_el, \ deg, \ deg + 1, \ vec_Pkp1.get_expansion_set(), \ PkHx_coeffs, \ vec_Pkp1.get_dmats() ) return polynomial_set.polynomial_set_union_normalized( vec_Pk_from_Pkp1, PkHx ) class RTDualSet( dual_set.DualSet ): """Dual basis for Raviart-Thomas elements consisting of point evaluation of normals on facets of codimension 1 and internal moments against polynomials""" def __init__( self, ref_el, degree ): entity_ids = {} nodes = [] sd = ref_el.get_spatial_dimension() t = ref_el.get_topology() # codimension 1 facets for i in range( len( t[sd-1] ) ): pts_cur = ref_el.make_points( sd - 1, i, sd + degree ) for j in range( len( pts_cur ) ): pt_cur = pts_cur[j] f = functional.PointScaledNormalEvaluation( ref_el, i, \ pt_cur ) nodes.append( f ) # internal nodes. Let's just use points at a lattice if degree > 0: cpe = functional.ComponentPointEvaluation pts = ref_el.make_points( sd, 0, degree + sd ) for d in range( sd ): for i in range( len( pts ) ): l_cur = cpe( ref_el, d, (sd,), pts[i] ) nodes.append( l_cur ) # Q = quadrature.make_quadrature( ref_el , 2 * ( degree + 1 ) ) # qpts = Q.get_points() # Pkm1 = polynomial_set.ONPolynomialSet( ref_el , degree - 1 ) # zero_index = tuple( [ 0 for i in range( sd ) ] ) # Pkm1_at_qpts = Pkm1.tabulate( qpts )[ zero_index ] # for d in range( sd ): # for i in range( Pkm1_at_qpts.shape[0] ): # phi_cur = Pkm1_at_qpts[i,:] # l_cur = functional.IntegralMoment( ref_el , Q , \ # phi_cur , (d,) , (sd,) ) # nodes.append( l_cur ) # sets vertices (and in 3d, edges) to have no nodes for i in range( sd - 1 ): entity_ids[i] = {} for j in range( len( t[i] ) ): entity_ids[i][j] = [] cur = 0 # set codimension 1 (edges 2d, faces 3d) dof pts_facet_0 = ref_el.make_points( sd - 1, 0, sd + degree ) pts_per_facet = len( pts_facet_0 ) entity_ids[sd-1] = {} for i in range( len( t[sd-1] ) ): entity_ids[sd-1][i] = list(range( cur, cur + pts_per_facet)) cur += pts_per_facet # internal nodes, if applicable entity_ids[sd] = {0: []} if degree > 0: num_internal_nodes = expansions.polynomial_dimension( ref_el, \ degree - 1 ) entity_ids[sd][0] = list(range( cur, cur + num_internal_nodes * sd)) dual_set.DualSet.__init__( self, nodes, ref_el, entity_ids ) class RaviartThomas( finite_element.FiniteElement ): """The Raviart-Thomas finite element""" def __init__( self, ref_el, q ): degree = q - 1 poly_set = RTSpace( ref_el, degree ) dual = RTDualSet( ref_el, degree ) finite_element.FiniteElement.__init__( self, poly_set, dual, degree, mapping="contravariant piola") if __name__=="__main__": T = reference_element.UFCTriangle() sd = T.get_spatial_dimension() for k in range(6): RT = RaviartThomas( T, k ) # RTfs = RT.get_nodal_basis() # pts = T.make_lattice( 1 ) # print pts # zero_index = tuple( [ 0 for i in range(sd) ] ) # # RTvals = RTfs.tabulate( pts )[zero_index] # print RTvals fiat-1.6.0/FIAT/reference_element.py000066400000000000000000000470651255003405100172140ustar00rootroot00000000000000# Copyright (C) 2008 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . """ Abstract class and particular implementations of finite element reference simplex geometry/topology. Provides an abstract base class and particular implementations for the reference simplex geometry and topology. The rest of FIAT is abstracted over this module so that different reference element geometry (e.g. a vertex at (0,0) versus at (-1,-1)) and orderings of entities have a single point of entry. Currently implemented are UFC and Default Line, Triangle and Tetrahedron. """ import numpy LINE = 1 TRIANGLE = 2 TETRAHEDRON = 3 def linalg_subspace_intersection( A, B ): """Computes the intersection of the subspaces spanned by the columns of 2-dimensional arrays A,B using the algorithm found in Golub and van Loan (3rd ed) p. 604. A should be in R^{m,p} and B should be in R^{m,q}. Returns an orthonormal basis for the intersection of the spaces, stored in the columns of the result.""" # check that vectors are in same space if A.shape[0] != B.shape[0]: raise Exception("Dimension error") #A,B are matrices of column vectors # compute the intersection of span(A) and span(B) # Compute the principal vectors/angles between the subspaces, G&vL # p.604 (qa, ra) = numpy.linalg.qr( A ) (qb, rb) = numpy.linalg.qr( B ) C = numpy.dot( numpy.transpose( qa ), qb ) (y, c, zt) = numpy.linalg.svd( C ) U = numpy.dot( qa, y ) V = numpy.dot( qb, numpy.transpose( zt ) ) rank_c = len( [ s for s in c if numpy.abs( 1.0 - s ) < 1.e-10 ] ) return U[:, :rank_c] def lattice_iter( start, finish, depth ): """Generator iterating over the depth-dimensional lattice of integers between start and (finish-1). This works on simplices in 1d, 2d, 3d, and beyond""" if depth == 0: return elif depth == 1: for ii in range( start, finish ): yield [ii] else: for ii in range( start, finish ): for jj in lattice_iter( start, finish-ii, depth - 1 ): yield [ii] + jj class ReferenceElement: """Abstract class for a reference element simplex. Provides accessors for geometry (vertex coordinates) as well as topology (orderings of vertices that make up edges, facecs, etc.""" def __init__( self, shape, vertices, topology ): """The constructor takes a shape code, the physical vertices expressed as a list of tuples of numbers, and the topology of a simplex. The topology is stored as a dictionary of dictionaries t[i][j] where i is the spatial dimension and j is the index of the facet of that dimension. The result is a list of the vertices comprising the facet. """ self.shape = shape self.vertices = vertices self.topology = topology def get_shape( self ): """Returns the code for the element's shape.""" return self.shape def get_vertices( self ): """Returns an iteratble of the element's vertices, each stored as a tuple.""" return self.vertices def get_spatial_dimension( self ): """Returns the spatial dimension in which the element lives.""" return len( self.vertices[ 0 ] ) def get_topology( self ): """Returns a dictionary encoding the topology of the element. The dictionary's keys are the spatial dimensions (0,1,...) and each value is a dictionary mapping """ return self.topology def get_vertices_of_subcomplex( self, t ): """Returns the tuple of vertex coordinates associated with the labels contained in the iterable t.""" return tuple( [ self.vertices[ ti ] for ti in t ] ) def compute_normal( self, facet_i ): """Returns the unit normal vector to facet i of codimension 1.""" # first, let's compute the span of the simplex # This is trivial if we have a d-simplex in R^d. # Not so otherwise. vert_vecs = [ numpy.array( v ) \ for v in self.vertices ] vert_vecs_foo = numpy.array( [ vert_vecs[i] - vert_vecs[0] \ for i in range(1, len(vert_vecs) ) ] ) (u, s, vt) = numpy.linalg.svd( vert_vecs_foo ) rank = len( [ si for si in s if si > 1.e-10 ] ) # this is the set of vectors that span the simplex spanu = u[:, :rank] t = self.get_topology( ) sd = self.get_spatial_dimension() vert_coords_of_facet = \ self.get_vertices_of_subcomplex( t[sd-1][facet_i] ) # now I find everything normal to the facet. vcf = [ numpy.array( foo ) \ for foo in vert_coords_of_facet ] facet_span = numpy.array( [ vcf[i] - vcf[0] \ for i in range(1, len(vcf) ) ] ) (uf, sf, vft) = numpy.linalg.svd( facet_span ) # now get the null space from vft rankfacet = len( [ si for si in sf if si > 1.e-10 ] ) facet_normal_space = numpy.transpose( vft[rankfacet:,:] ) # now, I have to compute the intersection of # facet_span with facet_normal_space foo = linalg_subspace_intersection( facet_normal_space, spanu ) num_cols = foo.shape[1] if num_cols != 1: raise Exception("barf in normal computation") # now need to get the correct sign # get a vector in the direction nfoo = foo[:, 0] # what is the vertex not in the facet? verts_set = set( t[sd][0] ) verts_facet = set( t[sd-1][facet_i] ) verts_diff = verts_set.difference( verts_facet ) if len( verts_diff ) != 1: raise Exception("barf in normal computation: getting sign") vert_off = verts_diff.pop() vert_on = verts_facet.pop() # get a vector from the off vertex to the facet v_to_facet = numpy.array( self.vertices[vert_on] ) \ - numpy.array( self.vertices[ vert_off ] ) if numpy.dot( v_to_facet, nfoo ) > 0.0: return nfoo else: return -nfoo def compute_tangents( self, dim, i ): """computes tangents in any dimension based on differences between vertices and the first vertex of the i:th facet of dimension dim. Returns a (possibly empty) list. These tangents are *NOT* normalized to have unit length.""" t = self.get_topology() vs = list(map( numpy.array, \ self.get_vertices_of_subcomplex( t[dim][i] ) )) ts = [ v - vs[0] for v in vs[1:] ] return ts def compute_normalized_tangents( self, dim, i ): """computes tangents in any dimension based on differences between vertices and the first vertex of the i:th facet of dimension dim. Returns a (possibly empty) list. These tangents are normalized to have unit length.""" ts = self.compute_tangents( dim, i ) return [ t / numpy.linalg.norm( t ) for t in ts ] def compute_edge_tangent( self, edge_i ): """Computes the nonnormalized tangent to a 1-dimensional facet. returns a single vector.""" t = self.get_topology() (v0, v1) = self.get_vertices_of_subcomplex( t[1][edge_i] ) return numpy.array( v1 ) - numpy.array( v0 ) def compute_normalized_edge_tangent( self, edge_i ): """Computes the unit tangent vector to a 1-dimensional facet""" v = self.compute_edge_tangent( edge_i ) return v / numpy.linalg.norm( v ) def compute_face_tangents( self, face_i ): """Computes the two tangents to a face. Only implemented for a tetrahedron.""" if self.get_spatial_dimension() != 3: raise Exception("can't get face tangents yet") t = self.get_topology() (v0, v1, v2) = list(map( numpy.array, \ self.get_vertices_of_subcomplex( t[2][face_i] ) )) return (v1-v0, v2-v0) def make_lattice( self , n , interior = 0): """Constructs a lattice of points on the simplex. For example, the 1:st order lattice will be just the vertices. The optional argument interior specifies how many points from the boundary to omit. For example, on a line with n = 2, and interior = 0, this function will return the vertices and midpoint, but with interior = 1, it will only return the midpoint.""" verts = self.get_vertices() nverts = len( verts ) vs = [ numpy.array( v ) for v in verts ] hs = [ (vs[ i ] - vs[ 0 ]) / n for i in range(1, nverts) ] result = [] m = len( hs ) for indices in lattice_iter( interior, n + 1 - interior, m ): res_cur = vs[0].copy() for i in range(len(indices)): res_cur += indices[i] * hs[m-i-1] result.append( tuple( res_cur ) ) return result def make_points( self, dim, entity_id, order ): """Constructs a lattice of points on the entity_id:th facet of dimension dim. Order indicates how many points to include in each direction.""" if dim == 0: return ( self.get_vertices()[entity_id], ) elif dim > self.get_spatial_dimension(): raise Exception("illegal dimension") elif dim == self.get_spatial_dimension(): return self.make_lattice( order, 1 ) else: base_el = default_simplex( dim ) base_verts = base_el.get_vertices() facet_verts = \ self.get_vertices_of_subcomplex( \ self.get_topology()[dim][entity_id] ) (A, b) = make_affine_mapping( base_verts, facet_verts ) f = lambda x: (numpy.dot( A, x ) + b) base_pts = base_el.make_lattice( order, 1 ) image_pts = tuple( [ tuple( f( x ) ) for x in base_pts ] ) return image_pts def volume( self ): """Computes the volumne of the simplex in the appropriate dimensional measure.""" return volume( self.get_vertices() ) def volume_of_subcomplex( self, dim, facet_no ): vids = self.topology[dim][facet_no] return volume( self.get_vertices_of_subcomplex( vids ) ) def compute_scaled_normal( self, facet_i ): """Returns the unit normal to facet_i of scaled by the volume of that facet.""" t = self.get_topology() sd = self.get_spatial_dimension() facet_verts_ids = t[sd-1][facet_i] facet_verts_coords = self.get_vertices_of_subcomplex( facet_verts_ids ) v = volume( facet_verts_coords ) return self.compute_normal( facet_i ) * v class DefaultLine( ReferenceElement ): """This is the reference line with vertices (-1.0,) and (1.0,).""" def __init__( self ): verts = ( (-1.0,), (1.0,) ) edges = { 0 : ( 0, 1 ) } topology = { 0 : { 0 : (0,) , 1: (1,) } , \ 1 : edges } ReferenceElement.__init__( self, LINE, verts, topology ) class UFCInterval( ReferenceElement ): """This is the reference interval with vertices (0.0,) and (1.0,).""" def __init__( self ): verts = ( (0.0,), (1.0,) ) edges = { 0 : ( 0, 1 ) } topology = { 0 : { 0 : (0,) , 1 : (1,) } , \ 1 : edges } ReferenceElement.__init__( self, LINE, verts, topology ) class DefaultTriangle( ReferenceElement ): """This is the reference triangle with vertices (-1.0,-1.0), (1.0,-1.0), and (-1.0,1.0).""" def __init__( self ): verts = ((-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0)) edges = { 0 : ( 1, 2 ) , \ 1 : ( 2, 0 ) , \ 2 : ( 0, 1 ) } faces = { 0 : ( 0, 1, 2 ) } topology = { 0 : { 0 : (0,) , 1 : (1,) , 2 : (2,) } , \ 1 : edges , 2 : faces } ReferenceElement.__init__( self, TRIANGLE, verts, topology ) class UFCTriangle( ReferenceElement ): """This is the reference triangle with vertices (0.0,0.0), (1.0,0.0), and (0.0,1.0).""" def __init__( self ): verts = ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0)) edges = { 0 : ( 1, 2 ) , 1 : ( 0, 2 ) , 2 : ( 0, 1 ) } faces = { 0 : ( 0, 1, 2 ) } topology = { 0 : { 0 : (0,) , 1 : (1,) , 2 : (2,) } , \ 1 : edges , 2 : faces } ReferenceElement.__init__( self, TRIANGLE, verts, topology ) def compute_normal(self, i): "UFC consistent normal" t = self.compute_tangents(1, i)[0] n = numpy.array((t[1], -t[0])) return n/numpy.linalg.norm(n) class IntrepidTriangle( ReferenceElement ): """This is the Intrepid triangle with vertices (0,0),(1,0),(0,1)""" def __init__( self ): verts = ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0)) edges = { 0 : ( 0, 1 ) , \ 1 : ( 1, 2 ) , \ 2 : ( 2, 0 ) } faces = { 0 : ( 0, 1, 2 ) } topology = { 0 : { 0 : (0,) , 1 : (1,) , 2 : (2,) } , \ 1 : edges , 2 : faces } ReferenceElement.__init__( self, TRIANGLE, verts, topology ) class DefaultTetrahedron( ReferenceElement ): """This is the reference tetrahedron with vertices (-1,-1,-1), (1,-1,-1),(-1,1,-1), and (-1,-1,1).""" def __init__( self ): verts = ((-1.0, -1.0, -1.0), (1.0, -1.0, -1.0),\ (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0)) vs = { 0 : ( 0, ) , \ 1 : ( 1, ) , \ 2 : ( 2, ) , \ 3 : ( 3, ) } edges = { 0: ( 1, 2 ) , \ 1: ( 2, 0 ) , \ 2: ( 0, 1 ) , \ 3: ( 0, 3 ) , \ 4: ( 1, 3 ) , \ 5: ( 2, 3 ) } faces = { 0 : ( 1, 3, 2 ) , \ 1 : ( 2, 3, 0 ) , \ 2 : ( 3, 1, 0 ) , \ 3 : ( 0, 1, 2 ) } tets = { 0 : ( 0, 1, 2, 3 ) } topology = { 0: vs , 1 : edges , 2 : faces , 3 : tets } ReferenceElement.__init__( self, TETRAHEDRON, verts, topology ) class IntrepidTetrahedron( ReferenceElement ): """This is the reference tetrahedron with vertices (0,0,0), (1,0,0),(0,1,0), and (0,0,1) used in the Intrepid project.""" def __init__( self ): verts = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) vs = { 0 : ( 0, ) , \ 1 : ( 1, ) , \ 2 : ( 2, ) , \ 3 : ( 3, ) } edges = { 0 : (0, 1) , \ 1 : (1, 2) , \ 2 : (2, 0) , \ 3 : (0, 3) , \ 4 : (1, 3) , \ 5 : (2, 3) } faces = { 0 : (0, 1, 3) , \ 1 : (1, 2, 3) , \ 2 : (0, 3, 2) , \ 3 : (0, 2, 1) } tets = { 0 : ( 0, 1, 2, 3 ) } topology = { 0: vs , 1 : edges , 2 : faces , 3 : tets } ReferenceElement.__init__( self, TETRAHEDRON, verts, topology ) class UFCTetrahedron( ReferenceElement ): """This is the reference tetrahedron with vertices (0,0,0), (1,0,0),(0,1,0), and (0,0,1).""" def __init__( self ): verts = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) vs = { 0 : ( 0, ) , \ 1 : ( 1, ) , \ 2 : ( 2, ) , \ 3 : ( 3, ) } edges = { 0 : ( 2, 3 ) , \ 1 : ( 1, 3 ) , \ 2 : ( 1, 2 ) , \ 3 : ( 0, 3 ) , \ 4 : ( 0, 2 ) , \ 5 : ( 0, 1 ) } faces = { 0 : ( 1, 2, 3 ) , \ 1 : ( 0, 2, 3 ) , \ 2 : ( 0, 1, 3 ) , \ 3 : ( 0, 1, 2 ) } tets = { 0 : ( 0, 1, 2, 3 ) } topology = { 0: vs , 1 : edges , 2 : faces , 3 : tets } ReferenceElement.__init__( self, TETRAHEDRON, verts, topology ) def compute_normal(self, i): "UFC consistent normals." t = self.compute_tangents(2, i) n = numpy.cross(t[0], t[1]) return -2.0*n/numpy.linalg.norm(n) def make_affine_mapping( xs, ys ): """Constructs (A,b) such that x --> A * x + b is the affine mapping from the simplex defined by xs to the simplex defined by ys.""" dim_x = len( xs[0] ) dim_y = len( ys[0] ) if len( xs ) != len( ys ): raise Exception("") # find A in R^{dim_y,dim_x}, b in R^{dim_y} such that # A xs[i] + b = ys[i] for all i mat = numpy.zeros( (dim_x*dim_y+dim_y, dim_x*dim_y+dim_y), "d" ) rhs = numpy.zeros( (dim_x*dim_y+dim_y,), "d" ) # loop over points for i in range( len( xs ) ): # loop over components of each A * point + b for j in range( dim_y ): row_cur = i*dim_y+j col_start = dim_x * j col_finish = col_start + dim_x mat[row_cur, col_start:col_finish] = numpy.array( xs[i] ) rhs[row_cur] = ys[i][j] # need to get terms related to b mat[row_cur, dim_y*dim_x+j] = 1.0 sol = numpy.linalg.solve( mat, rhs ) A = numpy.reshape( sol[:dim_x*dim_y], (dim_y, dim_x) ) b = sol[dim_x*dim_y:] return A, b def default_simplex( spatial_dim ): """Factory function that maps spatial dimension to an instance of the default reference simplex of that dimension.""" if spatial_dim == 1: return DefaultLine() elif spatial_dim == 2: return DefaultTriangle() elif spatial_dim == 3: return DefaultTetrahedron() def ufc_simplex( spatial_dim ): """Factory function that maps spatial dimension to an instance of the UFC reference simplex of that dimension.""" if spatial_dim == 1: return UFCInterval() elif spatial_dim == 2: return UFCTriangle() elif spatial_dim == 3: return UFCTetrahedron() else: raise RuntimeError("Don't know how to create UFC simplex for dimension %s" % str(spatial_dim)) def volume( verts ): """Constructs the volume of the simplex spanned by verts""" from .factorial import factorial # use fact that volume of UFC reference element is 1/n! sd = len( verts ) - 1 ufcel = ufc_simplex( sd ) ufcverts = ufcel.get_vertices() A, b = make_affine_mapping( ufcverts, verts ) # can't just take determinant since, e.g. the face of # a tet being mapped to a 2d triangle doesn't have a # square matrix (u, s, vt) = numpy.linalg.svd( A ) # this is the determinant of the "square part" of the matrix # (ie the part that maps the restriction of the higher-dimensional # stuff to UFC element p = numpy.prod( [ si for si in s if (si) > 1.e-10 ] ) return p / factorial( sd ) if __name__ == "__main__": # U = UFCTetrahedron() # print U.make_points( 1 , 1 , 3 ) # for i in range(len(U.vertices)): # print U.compute_normal( i ) V = DefaultTetrahedron() sd = V.get_spatial_dimension() # print make_affine_mapping(V.get_vertices(),U.get_vertices()) for i in range( len( V.vertices ) ): print(V.compute_normal( i )) print(V.compute_scaled_normal( i )) print(volume( V.get_vertices_of_subcomplex( V.topology[sd-1][i] ) )) print() fiat-1.6.0/FIAT/regge.py000066400000000000000000000202251255003405100146230ustar00rootroot00000000000000# Copyright (C) 2015-2017 Lizao Li # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . import numpy from .finite_element import FiniteElement from .dual_set import DualSet from .polynomial_set import ONSymTensorPolynomialSet from .functional import PointwiseInnerProductEvaluation as InnerProduct from .functional import index_iterator from .reference_element import UFCTriangle, UFCTetrahedron class ReggeDual(DualSet): """ """ def __init__ (self, cell, degree): (dofs, ids) = self.generate_degrees_of_freedom(cell, degree) DualSet.__init__(self, dofs, cell, ids) def generate_degrees_of_freedom(self, cell, degree): """ Suppose f is a k-face of the reference n-cell. Let t1,...,tk be a basis for the tangent space of f as n-vectors. Given a symmetric 2-tensor field u on Rn. One set of dofs for Regge(r) on f is the moment of each of the (k+1)k/2 scalar functions [u(t1,t1),u(t1,t2),...,u(t1,tk), u(t2,t2), u(t2,t3),...,..., u(tk,tk)] aginst scalar polynomials of degrees (r-k+1). Here this is implemented as pointwise evaluations of those scalar functions. Below is an implementation for dimension 2--3. In dimension 1, Regge(r)=DG(r). It is awkward in the current FEniCS interface to implement the element uniformly for all dimensions due to its edge, facet=trig, cell style. """ dofs = [] ids = {} top = cell.get_topology() d = cell.get_spatial_dimension() if (d < 2) or (d > 3): raise("Regge elements only implemented for dimension 2--3.") # No vertex dof ids[0] = dict(list(zip(list(range(d+1)), ([] for i in range(d+1))))) # edge dofs (_dofs, _ids) = self._generate_edge_dofs(cell, degree, 0) dofs.extend(_dofs) ids[1] = _ids # facet dofs for 3D if d == 3: (_dofs, _ids) = self._generate_facet_dofs(cell, degree, len(dofs)) dofs.extend(_dofs) ids[2] = _ids # Cell dofs (_dofs, _ids) = self._generate_cell_dofs(cell, degree, len(dofs)) dofs.extend(_dofs) ids[d] = _ids return (dofs, ids) def _generate_edge_dofs(self, cell, degree, offset): """Generate dofs on edges.""" dofs = [] ids = {} for s in range(len(cell.get_topology()[1])): # Points to evaluate the inner product pts = cell.make_points(1, s, degree + 2) # Evalute squared length of the tagent vector along an edge t = cell.compute_edge_tangent(s) # Fill dofs dofs += [InnerProduct(cell, t, t, p) for p in pts] # Fill ids i = len(pts) * s ids[s] = list(range(offset + i, offset + i + len(pts))) return (dofs, ids) def _generate_facet_dofs(self, cell, degree, offset): """Generate dofs on facets in 3D.""" # Return empty if there is no such dofs dofs = [] d = cell.get_spatial_dimension() ids = dict(list(zip(list(range(4)), ([] for i in range(4))))) if degree == 0: return (dofs, ids) # Compute dofs for s in range(len(cell.get_topology()[2])): # Points to evaluate the inner product pts = cell.make_points(2, s, degree + 2) # Let t1 and t2 be the two tangent vectors along a triangle # we evaluate u(t1,t1), u(t1,t2), u(t2,t2) at each point. (t1, t2) = cell.compute_face_tangents(s) # Fill dofs for p in pts: dofs += [InnerProduct(cell, t1, t1, p), InnerProduct(cell, t1, t2, p), InnerProduct(cell, t2, t2, p)] # Fill ids i = len(pts) * s * 3 ids[s] = list(range(offset + i, offset + i + len(pts) * 3)) return (dofs, ids) def _generate_cell_dofs(self, cell, degree, offset): """Generate dofs for cells.""" # Return empty if there is no such dofs dofs = [] d = cell.get_spatial_dimension() if (d == 2 and degree == 0) or (d == 3 and degree <= 1): return ([], {0: []}) # Compute dofs. There is only one cell. So no need to loop here~ # Points to evaluate the inner product pts = cell.make_points(d, 0, degree + 2) # Let {e1,..,ek} be the Euclidean basis. We evaluate inner products # u(e1,e1), u(e1,e2), u(e1,e3), u(e2,e2), u(e2,e3),..., u(ek,ek) # at each point. e = numpy.eye(d) # Fill dofs for p in pts: dofs += [InnerProduct(cell, e[i], e[j], p) for [i,j] in index_iterator((d, d)) if i <= j] # Fill ids ids = {0 : list(range(offset, offset + len(pts) * d * (d + 1) // 2))} return (dofs, ids) class Regge(FiniteElement): """ The Regge elements on triangles and tetrahedra: the polynomial space described by the full polynomials of degree k with degrees of freedom to ensure its pullback as a metric to each interior facet and edge is single-valued. """ def __init__(self, cell, degree): # Check degree assert(degree >= 0), "Regge start at degree 0!" # Get dimension d = cell.get_spatial_dimension() # Construct polynomial basis for d-vector fields Ps = ONSymTensorPolynomialSet(cell, degree) # Construct dual space Ls = ReggeDual(cell, degree) # Set mapping mapping = "pullback as metric" # Call init of super-class FiniteElement.__init__(self, Ps, Ls, degree, mapping=mapping) if __name__=="__main__": print("Test 0: Regge degree 0 in 2D.") T = UFCTriangle() R = Regge(T, 0) print("-----") pts = numpy.array([[0.0, 0.0]]) ts = numpy.array([[0.0, 1.0], [1.0, 0.0], [-1.0, 1.0]]) vals = R.tabulate(0, pts)[(0, 0)] for i in range(R.space_dimension()): print("Basis #{}:".format(i)) for j in range(len(pts)): tut = [t.dot(vals[i, :, :, j].dot(t)) for t in ts] print("u(t,t) for edge tagents t at {} are: {}".format( pts[j], tut)) print("-----") print("Expected result: a single 1 for each basis and zeros for others.") print("") print("Test 1: Regge degree 0 in 3D.") T = UFCTetrahedron() R = Regge(T, 0) print("-----") pts = numpy.array([[0.0, 0.0, 0.0]]) ts = numpy.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]) vals = R.tabulate(0, pts)[(0, 0, 0)] for i in range(R.space_dimension()): print("Basis #{}:".format(i)) for j in range(len(pts)): tut = [t.dot(vals[i, :, :, j].dot(t)) for t in ts] print("u(t,t) for edge tagents t at {} are: {}".format( pts[j], tut)) print("-----") print("Expected result: a single 1 for each basis and zeros for others.") print("") print("Test 2: association of dofs to mesh entities.") print("------") for k in range(0, 3): print("Degree {} in 2D:".format(k)) T = UFCTriangle() R = Regge(T, k) print(R.entity_dofs()) print("") for k in range(0, 3): print("Degree {} in 3D:".format(k)) T = UFCTetrahedron() R = Regge(T, k) print(R.entity_dofs()) print("") fiat-1.6.0/FIAT/tabarg.py000066400000000000000000000030141255003405100147670ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import argyris, reference_element degree = 5 lattice_size = 10 * degree T = reference_element.DefaultTriangle() U = argyris.QuinticArgyris(T) pts = T.make_lattice( lattice_size ) bfvals = U.get_nodal_basis().tabulate_new( pts ) u0 = bfvals[0] fout = open("arg0.dat", "w") for i in range(len(pts)): fout.write("%s %s %s\n" % (pts[i][0], pts[i][1], u0[i])) fout.close() u1 = bfvals[1] fout = open("arg1.dat", "w") for i in range(len(pts)): fout.write("%s %s %s\n" % (pts[i][0], pts[i][1], u1[i])) fout.close() u2 = bfvals[3] fout = open("arg2.dat", "w") for i in range(len(pts)): fout.write("%s %s %s\n" % (pts[i][0], pts[i][1], u2[i])) fout.close() u3 = bfvals[18] fout = open("arg3.dat", "w") for i in range(len(pts)): fout.write("%s %s %s\n" % (pts[i][0], pts[i][1], u3[i])) fout.close() fiat-1.6.0/FIAT/tablag.py000066400000000000000000000020751255003405100147670ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import shapes, Lagrange shape = 3 degree = 3 lattice_size = 10 * degree U = Lagrange.Lagrange(shape, degree) pts = shapes.make_lattice(shape, lattice_size) us = U.function_space().tabulate(pts) fout = open("foo.dat", "w") u0 = us[0] for i in range(len(pts)): fout.write("%s %s %s %s" % (pts[i][0], pts[i][1], pts[i][2], u0[i])) fout.close() fiat-1.6.0/FIAT/trace.py000066400000000000000000000227141255003405100146350ustar00rootroot00000000000000# Copyright (C) 2012-2015 Marie E. Rognes and David A. Ham # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from __future__ import print_function import numpy from FIAT.discontinuous_lagrange import DiscontinuousLagrange from FIAT.reference_element import ufc_simplex from FIAT.functional import PointEvaluation from FIAT.polynomial_set import mis # Tolerance for geometry identifications epsilon = 1.e-8 def extract_unique_facet(coordinates, tolerance=epsilon): """Determine whether a set of points, each point described by its barycentric coordinates ('coordinates'), are all on one of the facets and return this facet and whether search has been successful. """ facets = [] for c in coordinates: on_facet = set([i for (i, l) in enumerate(c) if abs(l) < tolerance]) facets += [on_facet] unique_facet = facets[0] for e in facets: unique_facet = unique_facet & e # Handle coordinates not on facets somewhat gracefully if (len(unique_facet) != 1): return (None, False) # If we have a unique facet, return it and success return (unique_facet.pop(), True) def barycentric_coordinates(points, vertices): """Compute barycentric coordinates for a set of points ('points'), relative to a simplex defined by a set of vertices ('vertices'). """ # Form map matrix last = numpy.asarray(vertices[-1]) T = numpy.matrix([numpy.array(v) - last for v in vertices[:-1]]).T detT = numpy.linalg.det(T) invT = numpy.linalg.inv(T) # Compute barycentric coordinates for all points coords = [] for p in points: y = numpy.asarray(p) - last lam = invT.dot(y.T) lam = [lam[(0, i)] for i in range(len(y))] lam += [1.0 - sum(lam)] coords.append(lam) return coords def map_from_reference_facet(point, vertices): """ Input: vertices: the vertices defining the physical facet point: the reference point to be mapped to the facet """ # Compute barycentric coordinates of point relative to reference facet: reference_simplex = ufc_simplex(len(vertices)-1) reference_vertices = reference_simplex.get_vertices() coords = barycentric_coordinates([point,], reference_vertices)[0] # Evaluate physical coordinate of point using barycentric coordinates point = sum(vertices[j]*coords[j] for j in range(len(coords))) return tuple(point) def map_to_reference_facet(points, vertices, facet): """Given a set of points in n D and a set of vertices describing a facet of a simplex in n D (where the given points lie on this facet) map the points to the reference simplex of dimension (n-1). """ # Compute barycentric coordinates of points with respect to # the full physical simplex all_coords = barycentric_coordinates(points, vertices) # Extract vertices of reference facet simplex reference_facet_simplex = ufc_simplex(len(vertices)-2) ref_vertices = reference_facet_simplex.get_vertices() reference_points = [] for (i, coords) in enumerate(all_coords): # Extract correct subset of barycentric coordinates since we # know which facet we are on new_coords = [coords[j] for j in range(len(coords)) if (j != facet)] # Evaluate reference coordinate of point using revised # barycentric coordinates reference_pt = sum(numpy.asarray(ref_vertices[j])*new_coords[j] for j in range(len(new_coords))) reference_points += [reference_pt] return reference_points class DiscontinuousLagrangeTrace(object): "" def __init__(self, cell, k): tdim = cell.get_spatial_dimension() assert (tdim == 2 or tdim == 3) # Store input cell and polynomial degree (k) self.cell = cell self.k = k # Create DG_k space on the facet(s) of the cell self.facet = ufc_simplex(tdim - 1) self.DG = DiscontinuousLagrange(self.facet, k) # Count number of facets for given cell. Assumption: we are on # simplices self.num_facets = tdim + 1 # Construct entity ids. Initialize all to empty, will fill # later. self.entity_ids = {} topology = cell.get_topology() for dim, entities in topology.items(): self.entity_ids[dim] = {} for entity in entities: self.entity_ids[dim][entity] = {} # For each facet, we have dim(DG_k on that facet) number of dofs n = self.DG.space_dimension() for i in range(self.num_facets): self.entity_ids[tdim-1][i] = range(i*n, (i+1)*n) def degree(self): return self.k def value_shape(self): return () def space_dimension(self): """The space dimension of the trace space corresponds to the DG space dimesion on each facet times the number of facets.""" return self.DG.space_dimension()*self.num_facets def entity_dofs(self): return self.entity_ids def mapping(self): return ["affine" for i in range(self.space_dimension())] def dual_basis(self): # First create the points points = [] # For each facet, map the subcomplex DG_k dofs from the lower # dimensional reference element onto the facet and add to list # of points DG_k_dual_basis = self.DG.dual_basis() t_dim = self.cell.get_spatial_dimension() facets2indices = self.cell.get_topology()[t_dim - 1] # Iterate over the facets and add points on each facet for (facet, indices) in facets2indices.items(): vertices = self.cell.get_vertices_of_subcomplex(indices) vertices = numpy.array(vertices) for dof in DG_k_dual_basis: # PointEvaluation only carries one point point = list(dof.get_point_dict().keys())[0] pt = map_from_reference_facet([point,], vertices) points.append(pt) # One degree of freedom per point: nodes = [PointEvaluation(self.cell, x) for x in points] return nodes def tabulate(self, order, points): """Return tabulated values of derivatives up to given order of basis functions at given points.""" # Standard derivatives don't make sense, but return zero # because mixed elements compute all derivatives at once if (order > 0): values = {} sdim = self.space_dimension() alphas = mis(self.cell.get_spatial_dimension(), order) for alpha in alphas: values[alpha] = numpy.zeros(shape=(sdim, len(points))) return values # Identify which facet (if any) these points are on: vertices = self.cell.vertices coordinates = barycentric_coordinates(points, vertices) (unique_facet, success) = extract_unique_facet(coordinates) # All other basis functions evaluate to zero, so create an # array of the right size sdim = self.space_dimension() values = numpy.zeros(shape=(sdim, len(points))) # ... and plug in the non-zero values in just the right place # if we found a unique facet if success: # Map point to "reference facet" (facet -> interval etc) new_points = map_to_reference_facet(points, vertices, unique_facet) # Call self.DG.tabulate(order, new_points) to compute the # values of the points for the degrees of freedom on this facet non_zeros = list(self.DG.tabulate(order, new_points).values())[0] m = non_zeros.shape[0] dg_dim = self.DG.space_dimension() values[dg_dim*unique_facet:dg_dim*unique_facet+m, :] = non_zeros # Return expected dictionary tdim = self.cell.get_spatial_dimension() key = tuple(0 for i in range(tdim)) return {key: values} # These functions are only needed for evaluatebasis and # evaluatebasisderivatives, disable those, and we should be in # business. def get_coeffs(self): """Return the expansion coefficients for the basis of the finite element.""" msg = "Not implemented: shouldn't be implemented." raise Exception(msg) def get_num_members(self, arg): msg = "Not implemented: shouldn't be implemented." raise Exception(msg) def dmats(self): msg = "Not implemented." raise Exception(msg) def __str__(self): return "DiscontinuousLagrangeTrace(%s, %s)" % (self.cell, self.k) if __name__ == "__main__": print("\n2D ----------------") T = ufc_simplex(2) element = DiscontinuousLagrangeTrace(T, 1) pts = [(0.0, 1.0), (1.0, 0.0)] print("values = ", element.tabulate(0, pts)) print("\n3D ----------------") T = ufc_simplex(3) element = DiscontinuousLagrangeTrace(T, 1) pts = [(0.1, 0.0, 0.0), (0.0, 1.0, 0.0)] print("values = ", element.tabulate(0, pts)) fiat-1.6.0/FIAT/transform_hermite.py000066400000000000000000000043731255003405100172700ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import hermite, reference_element import numpy # Let's set up the reference triangle and another one Khat = reference_element.UFCTriangle() newverts = ((-1.0, 0.0), (1.0, 0.0), (0.0, 1.0)) newtop = Khat.get_topology() K = reference_element.ReferenceElement( reference_element.TRIANGLE, \ newverts, \ newtop ) # Construct the affine mapping between them A, b = reference_element.make_affine_mapping( K.get_vertices(), Khat.get_vertices() ) # build the Hermite element on the two triangles Hhat = hermite.CubicHermite( Khat ) H = hermite.CubicHermite( K ) # get some points on each triangle pts_hat = Khat.make_lattice( 6 ) pts = K.make_lattice( 6 ) # as a sanity check on the affine mapping, make sure # pts map to pts_hat for i in range( len( pts ) ): if not numpy.allclose( pts_hat[i], numpy.dot(A, pts[i]) + b): print("barf") # Tabulate the Hermite basis on each triangle Hhat_tabulated = Hhat.get_nodal_basis().tabulate_new( pts_hat ) H_tabulated = H.get_nodal_basis().tabulate_new( pts ) # transform: M = numpy.zeros( (10, 10), "d" ) Ainv = numpy.linalg.inv( A ) # entries for point values are easy M[0, 0] = 1.0 M[3, 3] = 1.0 M[6, 6] = 1.0 M[9, 9] = 1.0 M[1:3, 1:3] = numpy.transpose( Ainv ) M[4:6, 4:6] = numpy.transpose( Ainv ) M[7:9, 7:9] = numpy.transpose( Ainv ) # entries for rest are Jacobian print(numpy.max( numpy.abs( H_tabulated - numpy.dot( numpy.transpose( M ), Hhat_tabulated ) ) )) fiat-1.6.0/FIAT/transform_morley.py000066400000000000000000000055151255003405100171410ustar00rootroot00000000000000# Copyright (C) 2008-2012 Robert C. Kirby (Texas Tech University) # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . from . import morley, reference_element import numpy # Let's set up the reference triangle and another one Khat = reference_element.UFCTriangle() newverts = ((-1.0, 0.0), (42.0, -0.5), (0.0, 1.0)) newtop = Khat.get_topology() K = reference_element.ReferenceElement( reference_element.TRIANGLE, \ newverts, \ newtop ) # Construct the affine mapping between them A, b = reference_element.make_affine_mapping( K.get_vertices(), Khat.get_vertices() ) # build the Morley element on the two triangles Mhat = morley.Morley( Khat ) M = morley.Morley( K ) # get some points on each triangle pts_hat = Khat.make_lattice( 4, 1 ) pts = K.make_lattice( 4, 1 ) # as a sanity check on the affine mapping, make sure # pts map to pts_hat for i in range( len( pts ) ): if not numpy.allclose( pts_hat[i], numpy.dot(A, pts[i]) + b): print("barf") # Tabulate the Morley basis on each triangle Mhat_tabulated = Mhat.get_nodal_basis().tabulate_new( pts_hat ) M_tabulated = M.get_nodal_basis().tabulate_new( pts ) Ainv = numpy.linalg.inv( A ) AinvT = numpy.transpose( Ainv ) D = numpy.zeros( (6, 9), "d" ) E = numpy.zeros( (9, 6), "d" ) D[0, 0] = 1.0 D[1, 1] = 1.0 D[2, 2] = 1.0 for i in range(3): n = K.compute_normal(i) t = K.compute_normalized_edge_tangent(i) nhat = Khat.compute_normal(i) l = K.volume_of_subcomplex(1, i) nt = numpy.transpose( [ n, t ] ) [f, g] = numpy.dot( nhat, numpy.dot( AinvT, nt ) ) / l D[3+i, 3+i] = f D[3+i, 6+i] = g for d in D.tolist(): print(d) print() for i in range(3): E[i, i] = 1.0 for i in range(3): E[3+i, 3+i] = K.volume_of_subcomplex(1, i) for i in range(3): evids = K.topology[1][i] elen = K.volume_of_subcomplex( 1, i ) E[6+i, evids[1]] = 1.0 E[6+i, evids[0]] = -1.0 print(E) print() transform = numpy.dot( D, E ) ttrans = numpy.transpose( transform ) for row in ttrans: print(row) print() print("max error") print(numpy.max( numpy.abs( numpy.dot( numpy.transpose( transform ), Mhat_tabulated ) - M_tabulated ) )) fiat-1.6.0/MANIFEST000066400000000000000000000010601255003405100135620ustar00rootroot00000000000000setup.py FIAT/BDFM.py FIAT/BDM.py FIAT/CrouzeixRaviart.py FIAT/DiscontinuousLagrange.py FIAT/Lagrange.py FIAT/Nedelec.py FIAT/P0.py FIAT/PhiK.py FIAT/RaviartThomas.py FIAT/__init__.py FIAT/constrainedspaces.py FIAT/divfree.py FIAT/dualbasis.py FIAT/expansions.py FIAT/factorial.py FIAT/functional.py FIAT/functionalset.py FIAT/gamma.py FIAT/jacobi.py FIAT/newquad.py FIAT/numbering.py FIAT/polynomial.py FIAT/quadrature.py FIAT/shapes.py FIAT/test.py FIAT/testBDFM.py FIAT/testBDM.py FIAT/testRT.py FIAT/testfunctional.py FIAT/testned.py FIAT/xpermutations.py fiat-1.6.0/README000066400000000000000000000027021255003405100133150ustar00rootroot00000000000000======================================== FIAT: FInite element Automatic Tabulator ======================================== The FInite element Automatic Tabulator FIAT supports generation of arbitrary order instances of the Lagrange elements on lines, triangles, and tetrahedra. It is also capable of generating arbitrary order instances of Jacobi-type quadrature rules on the same element shapes. Further, H(div) and H(curl) conforming finite element spaces such as the families of Raviart-Thomas, Brezzi-Douglas-Marini and Nedelec are supported on triangles and tetrahedra. Upcoming versions will also support Hermite and nonconforming elements. For more information, visit http://www.fenicsproject.org License ======= This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . Dependencies ============ #. Python, version 2.7 or later #. The Python modules NumPy and SymPy fiat-1.6.0/doc/000077500000000000000000000000001255003405100132015ustar00rootroot00000000000000fiat-1.6.0/doc/fenicsmanual.cls000066400000000000000000000061161255003405100163550ustar00rootroot00000000000000% Copyright (C) 2005 Anders Logg. % Licensed under the GNU GPL Version 2. % % First added: 2004-09-03 % Last changed: 2005-09-30 % % LaTeX document class for FEniCS manuals. %--- Set up class ---- \ProvidesClass{fenicsmanual}[2005/09/03 FEniCS manual] \NeedsTeXFormat{LaTeX2e} \LoadClass[12pt,twoside]{book} %--- Load packages --- \RequirePackage{graphicx} \RequirePackage{psfrag} \RequirePackage{fancyhdr} \RequirePackage{fancybox} \RequirePackage{fancyvrb} \RequirePackage{sectsty} \RequirePackage{amsmath} \RequirePackage{amssymb} \RequirePackage{makeidx} \RequirePackage{url} \RequirePackage[latin1]{inputenc} \RequirePackage[colorlinks]{hyperref} %--- Misc options --- \setlength{\parindent}{0pt} \setlength{\parskip}{12pt} \allsectionsfont{\sffamily} \makeindex %--- Remove header and footer from blank pages --- \let\origdoublepage\cleardoublepage \newcommand{\clearemptydoublepage}{% \clearpage {\pagestyle{empty}\origdoublepage}% } \let\cleardoublepage\clearemptydoublepage %--- Print index at end of document --- \AtEndDocument{\cleardoublepage\printindex} %--- Variables --- \newcommand{\@fenicstitle}{} \newcommand{\fenicstitle}[1]{\renewcommand{\@fenicstitle}{#1}} \newcommand{\@fenicsauthor}{} \newcommand{\fenicsauthor}[1]{\renewcommand{\@fenicsauthor}{#1}} \newcommand{\@fenicsimage}{\vspace{8cm}} \newcommand{\fenicsimage}[1]{\renewcommand{\@fenicsimage}{ \begin{center} \includegraphics[height=8cm]{#1} \end{center}}} \newcommand{\@fenicspackage}{} \newcommand{\@fenicspackagett}{} \newcommand{\fenicspackage}[2]{\renewcommand{\@fenicspackage}{#1}\renewcommand{\@fenicspackagett}{#2}} \newcommand{\package}{\@fenicspackage} \newcommand{\packagett}{\@fenicspackagett} %--- Commands --- \renewcommand{\maketitle}{ \lhead{\textsf{\textbf{\@fenicstitle}}} \rhead{\textsf{\@fenicsauthor}} \pagestyle{fancy} \renewcommand{\footrulewidth}{2pt} \renewcommand{\headrulewidth}{2pt} \thispagestyle{empty} \Large\textsf{\textbf{\@fenicstitle}} \\ \vspace{-0.5cm} \hrule height 2pt \hfill\large\textsf{\today} \vspace{3cm} \@fenicsimage \vfill\large\textsf{\textbf{\@fenicsauthor}} \\ \hrule height 2pt \hfill\large\texttt{www.fenics.org} \newpage \null\vfill \normalsize Visit \texttt{http://www.fenics.org/} for the latest version of this manual. \\ Send comments and suggestions to \texttt{\@fenicspackagett{}-dev@fenics.org}. \thispagestyle{empty} \cleardoublepage \tableofcontents} \newcommand{\fenics}{\textbf{\textsf{\normalsize{FE}\Large{ni}\normalsize{CS}}}} \newcommand{\dolfin}{\textbf{\textsf{DOLFIN}}} \newcommand{\ffc}{\textbf{\textsf{FFC}}} \newcommand{\fiat}{\textbf{\textsf{FIAT}}} \newcommand{\fixme}[1]{\ \\ \begin{tabular}{||p{\textwidth}||}\hline\rm\textbf{FIXME:}\rm #1 \\ \hline\end{tabular} \\} \newcommand{\devnote}[1]{$\blacktriangleright$ \emph{Developer's note:} #1} %--- Environments --- \DefineVerbatimEnvironment{code}{Verbatim}{commandchars=\\\{\},frame=single,rulecolor=\color{blue}} %--- Macros --- \newcommand{\dx}{\, \mathrm{d}x} \newcommand{\dX}{\, \mathrm{d}X} \newcommand{\R}{\mathbb{R}} fiat-1.6.0/doc/manual.tex000066400000000000000000000330721255003405100152050ustar00rootroot00000000000000\documentclass{fenicsmanual} \usepackage{graphicx} \usepackage{amssymb} \usepackage{amsmath} \usepackage{url} \textwidth = 6.5in \textheight = 9in \oddsidemargin = 0in \evensidemargin = 0in \topmargin = 0.0 in \headheight = 0.0 in \headsep = 0.0 in \parskip = 0.2in \parindent = 0.0in \newtheorem{theorem}{Theorem} \newtheorem{lemma}[theorem]{Lemma} \newtheorem{corollary}[theorem]{Corollary} \newtheorem{definition}{Definition} \newtheorem{remark}{Remark} \newtheorem{example}{Example} \newcommand{\tuple}[2]{<\!#1,#2\!>} \newcommand{\meet}{\wedge} \newcommand{\bigmeet}{\bigwedge} \def\proof{\par{\it Proof}. \ignorespaces} \def\endproof{\vbox{\hrule height0.6pt\hbox{% \vrule height1.3ex width0.6pt\hskip0.8ex \vrule width0.6pt}\hrule height0.6pt }} \newcommand{\N}{{\sf N\hspace*{-1.0ex}\rule{0.15ex}{1.3ex}\hspace*{1.0ex}}} \title{FIAT 0.2.4 Users' Manual} \author{Robert C. Kirby} \begin{document} \maketitle \chapter{Introduction} FIAT (FInite element Automatic Tabulator) is a Python package for defining and evaluating a wide range of different finite element basis functions for numerical partial differential equations. It is intended to make ``difficult'' elements such as high-order Brezzi-Douglas-Marini~\cite{} elements usable by providing abstractions so that they may be implemented succinctly and hence treated as a black box. FIAT is intended for use at two different levels. For one, it is designed to provide a standard API for finite element bases so that programmers may use whatever elements they need in their code. At a lower level, it provides necessary infrastructure to rapidly deploy new kinds of finite elements without expensive symbolic computation or tedious algebraic manipulation. It is my goal that a large number of people use FIAT without ever knowing it. Thanks to several ongoing projects such as Sundance~\cite{}, FFC~\cite{}, and PETSc~\cite{}, it is becoming possible to to define finite element methods using mathematical notation in some high-level or domain-specific language. The primary shortcoming of these projects is their lack of support for general elements. It is one thing to ``provide hooks'' for general elements, but absent a tool such as FIAT, these hooks remain mainly empty. As these projects mature, I hope to expose users of the finite element method to the exotic world of potentially high-degree finite element on unstructured grids using the best elements in $H^1$, $H(\mathrm{div})$, and $H(\mathrm{curl})$. In this brief (and still developing) guide, I will first present the high-level API for users who wish to instantiate a finite element on a reference domain and evaluate its basis functions and derivatives at some quadrature points. Then, I will explain some of the underlying infrastructure so as to demonstrate how to add new elements. \chapter{Installation} FIAT uses the standard Python \texttt{distutils} tools. From the top directory, one executes \texttt{python setup.py install}. This will put FIAT into the \texttt{site-packages} directory. Super-user permission (such as \texttt{su} or \texttt{sudo}) may be required to write to this directory. For more configuration options, one may type \texttt{python setup.py --help} or consult the online Python documentation at \texttt{http://docs.python.org/inst/inst.html} FIAT requires the commonly used \verb.Numeric. package. \chapter{Using FIAT: A tutorial with Lagrange elements} \section{Importing FIAT} FIAT is organized as a package in Python, consisting of several modules. In order to get some of the packages, we use the line \begin{verbatim} from FIAT import Lagrange, quadrature, shapes \end{verbatim} This loads several modules for the Lagrange elements, quadrature rules, and the simplicial element shapes which FIAT implements. The roles each of these plays will become clear shortly. \section{Important note} Throughout, FIAT defines the reference elements based on the interval $(-1,1)$ rather than the more common $(0,1)$. So, the one-dimensional reference element is $(-1,1)$, the three vertices of the reference triangle are $(-1,-1),(1,-1),(1,-1)$, and the four vertices of the reference tetrahedron are $(-1,-1,-1),(1,-1,-1),(-1,1,-1),(-1,-1,1)$. \section{Instantiating elements} FIAT uses a lightweight object-oriented infrastructure to define finite elements. The \verb.Lagrange. module contains a class \verb.Lagrange. modeling the Lagrange finite element family. This class is a subclass of some \verb.FiniteElement. class contained in another module (\verb.polynomial. to be precise). So, having imported the \verb.Lagrange. module, we can create the Lagrange element of degree \verb.2. on triangles by \begin{verbatim} shape = shapes.TRIANGLE degree = 2 U = Lagrange.Lagrange( shape , degree ) \end{verbatim} Here, \verb/shapes.TRIANGLE/ is an integer code indicating the two dimensional simplex. \verb.shapes. also defines \verb.LINE. and \verb.TETRAHEDRON.. Most of the upper-level interface to FIAT is dimensionally abstracted over element shape. The class \verb.FiniteElement. supports three methods, modeled on the abstract definition of Ciarlet. These methods are \verb.domain_shape()., \verb.function_space()., and \verb.dual_basis().. The first of these returns the code for the shape and the second returns the nodes of the finite element (including information related to topological association of nodes with mesh entities, needed for creating degree of freedom orderings). \section{Quadrature rules} FIAT implements arbitrary-order collapsed quadrature, as discussed in Karniadakis and Sherwin~\cite{}, for the simplex of dimension one, two, or three. The simplest way to get a quadrature rule is through the function \verb.make_quadrature(shape,m)., which takes a shape code and an integer indicating the number of points per direction. For building element matrices using quadratics, we will typically need a second or third order integration rule, so we can get such a rule by \begin{verbatim} >>> Q = quadrature.make_quadrature( shape , 2 ) \end{verbatim} This uses two points in each direction on the reference square, then maps them to the reference triangle. We may get a \verb/Numeric.array/ of the quadrature weights with the method \verb/Q.get_weights()/ and a list of tuples storing the quadrature points with the method \verb/Q.get_points()/. \section{Tabulation} FIAT provides functions for tabulating the element basis functions and their derivatives. To get the \verb.FunctionSpace. object, we do \begin{verbatim} >>> Ufs = U.function_space() \end{verbatim} To get the values of each basis function at each of the quadrature points, we use the \verb.tabulate(). method \begin{verbatim} >>> Ufs.tabulate( Q.get_points() ) array([[ 0.22176167, -0.12319761, -0.11479229, -0.06377178], [-0.11479229, -0.06377178, 0.22176167, -0.12319761], [-0.10696938, 0.18696938, -0.10696938, 0.18696938], [ 0.11074286, 0.19356495, 0.41329796, 0.72239423], [ 0.41329796, 0.72239423, 0.11074286, 0.19356495], [ 0.47595918, 0.08404082, 0.47595918, 0.08404082]]) \end{verbatim} This returns a two-dimensional \verb/Numeric.array/ with rows for each basis function and columns for each input point. Also, finite element codes require tabulation of the basis functions' derivatives. Each \verb/FunctionSpace/ object also provides a method \verb/tabulate_jet(i,xs)/ that returns a list of Python dictionaries. The \verb.i.th entry of the list is a dictionary storing the values of all \verb.i.th order derivatives. Each dictionary maps a multiindex (a tuple of length \verb.i.) to the table of the associated partial derivatives of the basis functions at those points. For example, \begin{verbatim} >>> Ufs_jet = Ufs.tabulate_jet( 1 , Q.get_points() ) \end{verbatim} tabulates the zeroth and first partial derivatives of the function space at the quadrature points. Then, \begin{verbatim} >>> Ufs_jet[0] {(0, 0): array([[ 0.22176167, -0.12319761, -0.11479229, -0.06377178], [-0.11479229, -0.06377178, 0.22176167, -0.12319761], [-0.10696938, 0.18696938, -0.10696938, 0.18696938], [ 0.11074286, 0.19356495, 0.41329796, 0.72239423], [ 0.41329796, 0.72239423, 0.11074286, 0.19356495], [ 0.47595918, 0.08404082, 0.47595918, 0.08404082]])} \end{verbatim} gives us a dictionary mapping the only zeroth-order partial derivative to the values of the basis functions at the quadrature points. More interestingly, we may get the first derivatives in the x- and y- directions with \begin{verbatim} >>> Ufs_jet[1][(1,0)] array([[-0.83278049, -0.06003983, 0.14288254, 0.34993778], [-0.14288254, -0.34993778, 0.83278049, 0.06003983], [ 0. , 0. , 0. , 0. ], [ 0.31010205, 1.28989795, 0.31010205, 1.28989795], [-0.31010205, -1.28989795, -0.31010205, -1.28989795], [ 0.97566304, 0.40997761, -0.97566304, -0.40997761]]) >>> Ufs_jet[1][(0,1)] array([[ -8.32780492e-01, -6.00398310e-02, 1.42882543e-01, 3.49937780e-01], [ 7.39494156e-17, 4.29608279e-17, 4.38075188e-17, 7.47961065e-17], [ -1.89897949e-01, 7.89897949e-01, -1.89897949e-01, 7.89897949e-01], [ 3.57117457e-01, 1.50062220e-01, 1.33278049e+00, 5.60039831e-01], [ 1.02267844e+00, -7.29858118e-01, 4.70154051e-02, -1.13983573e+00], [ -3.57117457e-01, -1.50062220e-01, -1.33278049e+00, -5.60039831e-01]]) \end{verbatim} \chapter{Lower-level API} Not only does FIAT provide a high-level library interface for users to evaluate existing finite element bases, but it also provides lower-level tools. Here, we survey these tools module-by-module. \section{shapes.py} FIAT currenly only supports simplicial reference elements, but does so in a fairly dimensionally-independent way (up to tetrahedra). \section{jacobi.py} This is a low-level module that tabulates the Jacobi polynomials and their derivatives, and also provides Gauss-Jacobi points. This module will seldom if ever be imported directly by users. For more information, consult the documentation strings and source code. \section{expansions.py} FIAT relies on orthonormal polynomial bases. These are constructed by mapping appropriate Jacobi polynomials from the reference cube to the reference simplex, as described in the reference of Karniadakis and Sherwin~\cite{}. The module \texttt{expansions.py} implements these orthonormal expansions. This is also a low-level module that will infrequently be used directly, but it forms the backbone for the module \texttt{polynomial.py} \section{quadrature.py} FIAT makes heavy use of numerical quadrature, both internally and in the user interface. Internally, many function spaces or degrees of freedom are defined in terms of integral quantities having certain behavior. Keeping with the theme of arbitrary order approximations, FIAT provides arbitrary order quadrature rules on the reference simplices. These are constructed by mapping Gauss-Jacobi rules from the reference cube. While these rules are suboptimal in terms of order of accuracy achieved for a given number of points, they may be generated mechanically in a simpler way than symmetric quadrature rules. In the future, we hope to have the best symmetric existing rules integrated into FIAT. Unless one is modifying the quadrature rules available, all of the functionality of \texttt{quadrature.py} may be accessed through the single function \verb.make_quadrature.. This function takes the code for a shape and the number of points in each coordinate direction and returns a quadrature rule. Internally, there is a lightweight class hierarchy rooted at an abstract \texttt{QuadratureRule} class, where the quadrature rules for different shapes are actually different classes. However, the dynamic typing of Python relieves the user from these considerations. The interface to an instance consists in the following methods \begin{itemize} \item \verb.get_points()., which returns a list of the quadrature points, each stored as a tuple. For dimensional uniformity, one-dimensional quadrature rules are stored as lists of 1-tuples rather than as lists of numbers. \item \verb.get_weights()., which returns a \texttt{Numeric.array} of quadrature weights. \item \verb.integrate(f)., which takes a callable object \texttt{f} and returns the (approximate) integral over the domain \item Also, the \verb.__call__. method is overloaded so that a quadrature rule may be applied to a callable object. This is syntactic sugar on top of the \texttt{integrate} method. \end{itemize} \section{polynomial.py} The \texttt{polynomial} module provides the bulk of the classes needed to represent polynomial bases and finite element spaces. The class \texttt{PolynomialBase} provides a high-level access to the orthonormal expansion bases; it is typically not instantiated directly in an application, but all other kinds of polynomial bases are constructed as linear combinations of the members of a \texttt{PolynomialBase} instance. The module provides classes for scalar and vector-valued polynomial sets, as well as an interface to individual polynomials and finite element spaces. \subsection{\texttt{PolynomialBase}} \subsection{\texttt{PolynomialSet}} The \texttt{PolynomialSet} function is a factory function interface into the hierarchy \chapter{Wish list and open problems} While FIAT is highly functional as a tool for tabulating basis functions at quadrature points, there are a lot of interesting things to do. In case anybody wants to help out, I have chosen to describe some of these issues here. \section{Stable/fast VDM inversion} \section{Symmetric quadrature rules} \section{Declarative top-level language} \section{Integration with SMART-type tools} \end{document} fiat-1.6.0/release.conf000066400000000000000000000001641255003405100147240ustar00rootroot00000000000000# Configuration file for fenics-release PACKAGE="fiat" BRANCH="master" FILES="setup.py ChangeLog FIAT/__init__.py" fiat-1.6.0/setup.py000077500000000000000000000012361255003405100141530ustar00rootroot00000000000000#!/usr/bin/env python import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info < (2, 7): print("Python 2.7 or higher required, please upgrade.") sys.exit(1) version = re.findall('__version__ = "(.*)"', open('FIAT/__init__.py', 'r').read())[0] setup(name="FIAT", version=version, description="FInite element Automatic Tabulator", author="Robert C. Kirby", author_email="robert.c.kirby@gmail.com", url="http://www.math.ttu.edu/~kirby", license="LGPL v3 or later", packages=["FIAT"], install_requires=["sympy"]) fiat-1.6.0/test/000077500000000000000000000000001255003405100134135ustar00rootroot00000000000000fiat-1.6.0/test/test.py000066400000000000000000000254101255003405100147460ustar00rootroot00000000000000# Copyright (C) 2010 Anders Logg # # This file is part of FIAT. # # FIAT is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FIAT 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with FIAT. If not, see . # # First added: 2010-01-31 # Last changed: 2014-06-30 import nose import sys import json import numpy from FIAT import supported_elements, make_quadrature, ufc_simplex, \ newdubiner, expansions, reference_element, polynomial_set # Parameters tolerance = 1e-8 class NumpyEncoder(json.JSONEncoder): def default(self, obj): # If numpy array, convert it to a list and store it in a dict. if isinstance(obj, numpy.ndarray): data = obj.tolist() return dict(__ndarray__=data, dtype=str(obj.dtype), shape=obj.shape) # Let the base class default method raise the TypeError return json.JSONEncoder(self, obj) def json_numpy_obj_hook(dct): # If dict and have '__ndarray__' as a key, convert it back to ndarray. if isinstance(dct, dict) and '__ndarray__' in dct: return numpy.asarray(dct['__ndarray__']).reshape(dct['shape']) return dct def test_polynomials(): def create_data(): ps = polynomial_set.ONPolynomialSet( ref_el=reference_element.DefaultTetrahedron(), degree=3 ) return ps.dmats # Try reading reference values filename = "reference-polynomials.json" try: reference = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference = create_data() # Store the data for the future json.dump(reference, open(filename, "w"), cls=NumpyEncoder) dmats = create_data() for dmat, reference_dmat in zip(dmats, reference): assert (abs(dmat - reference_dmat) < tolerance).all() return def test_polynomials_1D(): def create_data(): ps = polynomial_set.ONPolynomialSet( ref_el=reference_element.DefaultLine(), degree=3 ) return ps.dmats # Try reading reference values filename = "reference-polynomials_1D.json" try: reference = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference = create_data() # Store the data for the future json.dump(reference, open(filename, "w"), cls=NumpyEncoder) dmats = create_data() for dmat, reference_dmat in zip(dmats, reference): assert (abs(dmat - reference_dmat) < tolerance).all() return def test_expansions(): def create_data(): E = reference_element.DefaultTriangle() k = 3 pts = E.make_lattice(k) Phis = expansions.get_expansion_set(E) phis = Phis.tabulate(k, pts) dphis = Phis.tabulate_derivatives(k, pts) return phis, dphis # Try reading reference values filename = "reference-expansions.json" try: reference = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference = create_data() # Convert reference to list of int json.dump(reference, open(filename, "w"), cls=NumpyEncoder) table_phi, table_dphi = create_data() reference_table_phi, reference_table_dphi = reference # Test raw point data diff = numpy.array(table_phi) - numpy.array(reference_table_phi) assert (abs(diff) < tolerance).all() # Test derivative values for entry, reference_entry in zip(table_dphi, reference_table_dphi): for point, reference_point in zip(entry, reference_entry): value, gradient = point[0], point[1] reference_value, reference_gradient = \ reference_point[0], reference_point[1] assert abs(value - reference_value) < tolerance diff = numpy.array(gradient) - numpy.array(reference_gradient) assert (abs(diff) < tolerance).all() return def test_expansions_jet(): def create_data(): latticeK = 2 n = 1 order = 2 E = reference_element.DefaultTetrahedron() pts = E.make_lattice(latticeK) F = expansions.TetrahedronExpansionSet(E) return F.tabulate_jet(n, pts, order) filename = "reference-expansions-jet.json" try: reference_jet = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference_jet = create_data() # Store the data for the future json.dump(reference_jet, open(filename, "w"), cls=NumpyEncoder) # Test jet data data = create_data() reference_data = reference_jet for datum, reference_datum in zip(data, reference_data): diff = numpy.array(datum) - numpy.array(reference_datum) assert (abs(diff) < tolerance).all() return def test_newdubiner(): def create_data(): latticeK = 2 D = 3 pts = newdubiner.make_tetrahedron_lattice(latticeK, float) return newdubiner.tabulate_tetrahedron_derivatives(D, pts, float) # Try reading reference values filename = "reference-newdubiner.json" try: reference = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference = create_data() # Convert reference to list of int json.dump(reference, open(filename, "w"), cls=NumpyEncoder) # Actually perform the test table = create_data() for data, reference_data in zip(table, reference): for point, reference_point in zip(data, reference_data): for k in range(2): diff = numpy.array(point[k]) - numpy.array(reference_point[k]) assert (abs(diff) < tolerance).all() return def test_newdubiner_jet(): def create_data(): latticeK = 2 D = 3 n = 1 order = 2 pts = newdubiner.make_tetrahedron_lattice(latticeK, float) return newdubiner.tabulate_jet(D, n, pts, order, float) filename = "reference-newdubiner-jet.json" try: reference_jet = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference_jet = create_data() # Store the data for the future json.dump(reference_jet, open(filename, "w"), cls=NumpyEncoder) table_jet = create_data() for datum, reference_datum in zip(table_jet, reference_jet): for entry, reference_entry in zip(datum, reference_datum): for k in range(3): diff = numpy.array(entry[k]) - numpy.array(reference_entry[k]) assert (abs(diff) < tolerance).all() return def test_quadrature(): num_points = 3 max_derivative = 3 # Combinations of (family, dim, degree) to test test_cases = ( ("Lagrange", 2, 1), ("Lagrange", 2, 2), ("Lagrange", 2, 3), ("Lagrange", 3, 1), ("Lagrange", 3, 2), ("Lagrange", 3, 3), ("Discontinuous Lagrange", 2, 0), ("Discontinuous Lagrange", 2, 1), ("Discontinuous Lagrange", 2, 2), ("Discontinuous Lagrange", 3, 0), ("Discontinuous Lagrange", 3, 1), ("Discontinuous Lagrange", 3, 2), ("Brezzi-Douglas-Marini", 2, 1), ("Brezzi-Douglas-Marini", 2, 2), ("Brezzi-Douglas-Marini", 2, 3), ("Brezzi-Douglas-Marini", 3, 1), ("Brezzi-Douglas-Marini", 3, 2), ("Brezzi-Douglas-Marini", 3, 3), ("Brezzi-Douglas-Fortin-Marini", 2, 2), ("Raviart-Thomas", 2, 1), ("Raviart-Thomas", 2, 2), ("Raviart-Thomas", 2, 3), ("Raviart-Thomas", 3, 1), ("Raviart-Thomas", 3, 2), ("Raviart-Thomas", 3, 3), ("Discontinuous Raviart-Thomas", 2, 1), ("Discontinuous Raviart-Thomas", 2, 2), ("Discontinuous Raviart-Thomas", 2, 3), ("Discontinuous Raviart-Thomas", 3, 1), ("Discontinuous Raviart-Thomas", 3, 2), ("Discontinuous Raviart-Thomas", 3, 3), ("Nedelec 1st kind H(curl)", 2, 1), ("Nedelec 1st kind H(curl)", 2, 2), ("Nedelec 1st kind H(curl)", 2, 3), ("Nedelec 1st kind H(curl)", 3, 1), ("Nedelec 1st kind H(curl)", 3, 2), ("Nedelec 1st kind H(curl)", 3, 3), ("Nedelec 2nd kind H(curl)", 2, 1), ("Nedelec 2nd kind H(curl)", 2, 2), ("Nedelec 2nd kind H(curl)", 2, 3), ("Nedelec 2nd kind H(curl)", 3, 1), ("Nedelec 2nd kind H(curl)", 3, 2), ("Nedelec 2nd kind H(curl)", 3, 3), ("Crouzeix-Raviart", 2, 1), ("Crouzeix-Raviart", 3, 1), ("Regge", 2, 0), ("Regge", 2, 1), ("Regge", 2, 2), ("Regge", 3, 0), ("Regge", 3, 1), ("Regge", 3, 2) ) def create_data(family, dim, degree): '''Create the reference data. ''' # Get domain and element class domain = ufc_simplex(dim) ElementClass = supported_elements[family] # Create element| element = ElementClass(domain, degree) # Create quadrature points quad_rule = make_quadrature(domain, num_points) points = quad_rule.get_points() # Tabulate at quadrature points table = element.tabulate(max_derivative, points) return table def _perform_test(family, dim, degree, reference_table): '''Test against reference data. ''' table = create_data(family, dim, degree) # Check against reference for dtuple in reference_table: assert eval(dtuple) in table assert table[eval(dtuple)].shape == reference_table[dtuple].shape diff = table[eval(dtuple)] - reference_table[dtuple] assert (abs(diff) < tolerance).all() return # Try reading reference values filename = "reference.json" try: reference = json.load(open(filename, "r"), object_hook=json_numpy_obj_hook) except IOError: reference = {} for test_case in test_cases: family, dim, degree = test_case ref = dict([(str(k), v) for k, v in create_data(family, dim, degree).items()]) reference[str(test_case)] = ref # Store the data for the future json.dump(reference, open(filename, "w"), cls=NumpyEncoder) for test_case in test_cases: family, dim, degree = test_case yield _perform_test, family, dim, degree, reference[str(test_case)] if __name__ == "__main__": nose.main()