pax_global_header00006660000000000000000000000064134560646620014526gustar00rootroot0000000000000052 comment=c92dcb05ca8285c490169fbe9bbfb3869b950f37 fenics-project-dijitso-c92dcb05ca82/000077500000000000000000000000001345606466200173375ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/.circleci/000077500000000000000000000000001345606466200211725ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/.circleci/config.yml000066400000000000000000000012341345606466200231620ustar00rootroot00000000000000version: 2 jobs: build: docker: - image: circleci/python:3.6 working_directory: ~/dijitso-test steps: - checkout - run: name: Install dependencies # Install with sudo as tests not run as superuser in circleci/python command: | sudo apt-get update && sudo apt-get install python3-mpi4py sudo pip install flake8 pytest numpy --upgrade - run: name: Install dijitso command: pip install . --user - run: name: Run flake8 tests command: python -m flake8 . - run: name: Run unit tests command: python -m pytest ./test/ fenics-project-dijitso-c92dcb05ca82/COPYING000066400000000000000000001045131345606466200203760ustar00rootroot00000000000000 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 . fenics-project-dijitso-c92dcb05ca82/COPYING.LESSER000066400000000000000000000167271345606466200214030ustar00rootroot00000000000000 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. fenics-project-dijitso-c92dcb05ca82/ChangeLog.rst000066400000000000000000000020041345606466200217140ustar00rootroot00000000000000Changelog ========= 2019.2.0.dev0 ------------- - No changes so far. 2019.1.0 (2019-04-19) --------------------- - No changes. 2018.1.0 (2018-06-14) --------------------- - Very minor cleanups 2017.2.0 (2017-12-05) --------------------- - Add support for linking external libraries - Add support for creating a loadable module with __import__ with "lib_loader" parameter (ctypes, module) 2017.1.0.post1 (2017-09-12) --------------------- - Change PyPI package name to fenics-dijitso. 2017.1.0 (2017-05-09) --------------------- - Minor fixes 2016.2.0 (2016-11-30) --------------------- - Introduce commandline script ``dijitso`` with various subcommands to interact with the cache - Improve extraction of source files to reproduce compilation failure during jit - Implement support for linking between jit modules - Add optional dependency on ``subprocess32`` to handle fork safety on infiniband clusters - Remove ``instant`` dependency 2016.1.0 (2016-06-23) --------------------- - Initial implementation fenics-project-dijitso-c92dcb05ca82/MANIFEST.in000066400000000000000000000002131345606466200210710ustar00rootroot00000000000000include COPYING include COPYING.LESSER include ChangeLog recursive-include doc * recursive-include test * global-exclude __pycache__ *.pyc fenics-project-dijitso-c92dcb05ca82/README.rst000066400000000000000000000071031345606466200210270ustar00rootroot00000000000000dijitso ======= *A Python module for distributed just-in-time shared library building* Authors: - Martin Sandve Alnæs (martinal@simula.no) - Garth N. Wells (gnw20@cam.ac.uk) - Johannes Ring (johannr@simula.no) Contributors: - Jan Blechta (blechta@karlin.mff.cuni.cz) Documentation ------------- Documentation can be viewed at http://fenics-dijitso.readthedocs.org/. .. image:: https://readthedocs.org/projects/fenics-dijitso/badge/?version=latest :target: http://fenics.readthedocs.io/projects/dijitso/en/latest/?badge=latest :alt: Documentation Status Automated Testing ----------------- We use Bitbucket Pipelines and Atlassian Bamboo to perform automated testing. .. image:: https://bitbucket-badges.useast.atlassian.io/badge/fenics-project/dijitso.svg :target: https://bitbucket.org/fenics-project/dijitso/addon/pipelines/home :alt: Pipelines Build Status .. image:: http://fenics-bamboo.simula.no:8085/plugins/servlet/wittified/build-status/DIJ-DIDO :target: http://fenics-bamboo.simula.no:8085/browse/DIJ-DIDO/latest :alt: Bamboo Build Status Code Coverage ------------- Code coverage reports can be viewed at https://coveralls.io/bitbucket/fenics-project/dijitso. .. image:: https://coveralls.io/repos/bitbucket/fenics-project/dijitso/badge.svg?branch=master :target: https://coveralls.io/bitbucket/fenics-project/dijitso?branch=master :alt: Coverage Status Motivation ---------- This module was written to improve a core component of the FEniCS framework, namely the just in time compilation of C++ code that is generated from Python modules, but is only called from within a C++ library, and thus do not need wrapping in a nice Python interface. The main approach of dijitso is to use ctypes to import the dynamic shared library directly with no attempt at wrapping it in a Python interface. As long as the compiled code can provide a simple factory function to a class implementing a predefined C++ interface, there is no limit to the complexity of that interface as long as it is only called from C++ code, If you want a Python interface to your generated code, dijitso is probably not the answer. Although dijitso serves a very specific role within the FEniCS project, it does not depend on other FEniCS components. The parallel support depends on the mpi4py interface, although mpi4py is not actually imported within the dijitso module so it would be possible to mock the communicator object with a similar interface. Feature list ------------ - Disk cache system based on user provided signature string (user is responsible of the quality of the signature) - Lazy evaluation of possibly costly code generation through user-provided callback, called only if signature is not found in disk cache - Low overhead invocation of C++ compiler to produce a shared library with no Python wrapping - Portable shared library import using ctypes - Automatic compression of source code in the cache directory saves space - Autodetect which MPI processes share the same physical cache directory (doesn't matter if this is all cores on a node or shared across nodes with network mapped storage) - Automatic avoidance of race conditions in disk cache by only compiling on one process per physical cache directory - Optional MPI based distribution of shared library binary file - Configurable parallel behaviour: - "root": build only on single root node and distribute binary to each physical cache directory with MPI - "node": build on one process per physical cache directory - "process": build on each process, automatic separation of cache directories fenics-project-dijitso-c92dcb05ca82/dijitso/000077500000000000000000000000001345606466200210045ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/dijitso/__init__.py000066400000000000000000000024501345606466200231160ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . from pkg_resources import get_distribution """This is dijitso -- a lightweight distributed just-in-time shared library builder.""" __author__ = "Martin Sandve Alnæs" __version__ = get_distribution('fenics-dijitso').version __all__ = ["validate_params", "jit", "extract_factory_function", "set_log_level"] from dijitso.params import validate_params from dijitso.jit import jit, DijitsoError from dijitso.jit import extract_factory_function from dijitso.log import set_log_level # Import main function, entry point to script from dijitso.__main__ import main fenics-project-dijitso-c92dcb05ca82/dijitso/__main__.py000066400000000000000000000073131345606466200231020ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """This is the commandline interface to dijitso. For usage help, run 'dijitso --help'.""" import sys import argparse from dijitso.params import validate_params import dijitso.cmdline as cmd_namespace def build_commands(cmd_namespace): """Collects functions called cmd_ from given namespace. Returns dict {basename: function}. """ commands = {} cmd_args = {} for name in list(cmd_namespace.keys()): if name.startswith("cmd_"): cmd_name = name.replace("cmd_", "") cmd = cmd_namespace[name] commands[cmd_name] = cmd args_name = "args_" + cmd_name if args_name in cmd_namespace: cmd_args[cmd_name] = cmd_namespace.get(args_name) return commands, cmd_args def add_top_arguments(parser): "Add arguments to top level parser." parser.add_argument("--verbose", "-v", default=False, help="set logging level") parser.add_argument("--cache-dir", "-r", default=None, help="use non-default cache root path") parser.add_argument("--dry-run", "-n", default=False, help="only show what would be done, don't modify filesystem") def extract_params_from_args(args): p = {} p["cache"] = {} if args.cache_dir is not None: p["cache"]["cache_dir"] = args.cache_dir return p def add_common_arguments(parser): "Add arguments to each subparser." pass def add_cmd_arguments(cmd, parser, args): "Add arguments specific to a command." if hasattr(cmd, "add_arguments"): cmd.add_arguments(parser) def build_parsers(commands, args): """Builds a top parser with subparsers for each command.""" top_parser = argparse.ArgumentParser() add_top_arguments(top_parser) subparsers = top_parser.add_subparsers(help="command description", dest="cmd_name") cmd_parsers = {} for cmd_name, cmd in commands.items(): parser = subparsers.add_parser(cmd_name, help=cmd.__doc__) add_common_arguments(parser) if cmd_name in args: args[cmd_name](parser) cmd_parsers[cmd_name] = parser return top_parser, subparsers, cmd_parsers def main(args=None): """This is the commandline tool for the python module dijitso.""" if args is None: args = sys.argv[1:] # Build subparsers for each command commands, cmd_args = build_commands(vars(cmd_namespace)) top_parser, subparsers, cmd_parsers = build_parsers(commands, cmd_args) # Populate args namespace args_ns = argparse.Namespace() top_parser.parse_args(args, namespace=args_ns) # Extract generic params params = extract_params_from_args(args_ns) params = validate_params(params) # Run the chosen command (argparse doesn't allow # getting to this point with an invalid cmd_name) assert args_ns.cmd_name in commands cmd = commands[args_ns.cmd_name] return cmd(args_ns, params) if __name__ == "__main__": sys.exit(main()) fenics-project-dijitso-c92dcb05ca82/dijitso/build.py000066400000000000000000000226341345606466200224640ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """Utilities for building libraries with dijitso.""" import tempfile import os import sys from dijitso.system import get_status_output, lockfree_move_file from dijitso.system import make_dirs, make_executable, store_textfile from dijitso.log import warning, info, debug from dijitso.cache import ensure_dirs, make_lib_dir, make_inc_dir from dijitso.cache import create_fail_dir_path from dijitso.cache import create_lib_filename, create_lib_basename, create_libname from dijitso.cache import create_src_filename, create_src_basename from dijitso.cache import create_inc_filename, create_inc_basename from dijitso.cache import create_log_filename from dijitso.cache import compress_source_code def make_unique(dirs): """Take a sequence of hashable items and return a tuple including each only once. Preserves original ordering. """ udirs = [] found = set() for d in dirs: if d not in found: udirs.append(d) found.add(d) return tuple(udirs) def make_compile_command(src_filename, lib_filename, dependencies, build_params, cache_params): """Piece together the compile command from build params. Returns the command as a list with the command and its arguments. """ # Get dijitso dirs based on cache_params inc_dir = make_inc_dir(cache_params) lib_dir = make_lib_dir(cache_params) # Add dijitso directories to includes, libs, and rpaths include_dirs = make_unique(build_params["include_dirs"] + (inc_dir,)) lib_dirs = make_unique(build_params["lib_dirs"] + (lib_dir,)) rpath_dirs = make_unique(build_params["rpath_dirs"] + (lib_dir,)) # Make all paths absolute include_dirs = [os.path.abspath(d) for d in include_dirs] lib_dirs = [os.path.abspath(d) for d in lib_dirs] rpath_dirs = [os.path.abspath(d) for d in rpath_dirs] # Build options (defaults assume gcc compatibility) cxxflags = list(build_params["cxxflags"]) if build_params["debug"]: cxxflags.extend(build_params["cxxflags_debug"]) else: cxxflags.extend(build_params["cxxflags_opt"]) # Create library names for all dependencies and additional given # libs deplibs = [create_libname(depsig, cache_params) for depsig in dependencies] deplibs.extend(build_params["libs"]) # Get compiler name args = [build_params["cxx"]] # Compiler args args.extend(cxxflags) args.extend("-I" + path for path in include_dirs) # The input source args.append(src_filename) # Linker args args.extend("-L" + path for path in lib_dirs) args.extend("-Wl,-rpath," + path for path in rpath_dirs) args.extend("-l" + lib for lib in deplibs) # OSX specific: if sys.platform == "darwin": full_lib_filename = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"], os.path.basename(lib_filename)) args.append("-Wl,-install_name,%s" % full_lib_filename) # The output library args.append("-o" + lib_filename) return args def temp_dir(cache_params): """Return a uniquely named temp directory. Optionally residing under temp_dir_root from cache_params. """ return tempfile.mkdtemp(dir=cache_params["temp_dir_root"]) def build_shared_library(signature, header, source, dependencies, params): """Build shared library from a source file and store library in cache. """ cache_params = params["cache"] build_params = params["build"] # Create basenames inc_basename = create_inc_basename(signature, cache_params) src_basename = create_src_basename(signature, cache_params) lib_basename = create_lib_basename(signature, cache_params) # Create a temp directory and filenames within it tmpdir = temp_dir(cache_params) temp_inc_filename = os.path.join(tmpdir, inc_basename) temp_src_filename = os.path.join(tmpdir, src_basename) temp_lib_filename = os.path.join(tmpdir, lib_basename) # Store source and header in temp dir if header: store_textfile(temp_inc_filename, header) store_textfile(temp_src_filename, source) # Build final command as list of arguments cmd = make_compile_command(temp_src_filename, temp_lib_filename, dependencies, build_params, cache_params) # Execute command to compile generated source code to dynamic # library status, output = get_status_output(cmd) # Move files to cache on success or a local dir on failure, # using safe lockfree move if status == 0: # Ensure dirnames exist in cache dirs ensure_dirs(cache_params) # Move library first lib_filename = create_lib_filename(signature, cache_params) assert os.path.exists(os.path.dirname(lib_filename)) lockfree_move_file(temp_lib_filename, lib_filename) # Write header only if there is one if header: inc_filename = create_inc_filename(signature, cache_params) assert os.path.exists(os.path.dirname(inc_filename)) lockfree_move_file(temp_inc_filename, inc_filename) else: inc_filename = None # Compress or delete source code based on params temp_src_filename = compress_source_code(temp_src_filename, cache_params) if temp_src_filename: src_filename = create_src_filename(signature, cache_params) if temp_src_filename.endswith(".gz"): src_filename = src_filename + ".gz" assert os.path.exists(os.path.dirname(src_filename)) lockfree_move_file(temp_src_filename, src_filename) else: src_filename = None # Write compiler command and output to log file if cache_params["enable_build_log"]: # Recreate compiler command without the tempdir cmd = make_compile_command(src_basename, lib_basename, dependencies, build_params, cache_params) log_contents = "%s\n\n%s" % (" ".join(cmd), output) log_filename = create_log_filename(signature, cache_params) assert os.path.exists(os.path.dirname(log_filename)) store_textfile(log_filename, log_contents) else: log_filename = None files = set((inc_filename, src_filename, lib_filename, log_filename)) files = files - set((None,)) files = sorted(files) debug("Compilation succeeded. Files written to cache:\n" + "\n".join(files)) err_info = None else: # Create filenames in a local directory to store files for # reproducing failure fail_dir = create_fail_dir_path(signature, cache_params) make_dirs(fail_dir) # Library name is returned below lib_filename = None # Write header only if there is one if header: inc_filename = os.path.join(fail_dir, inc_basename) lockfree_move_file(temp_inc_filename, inc_filename) # Always write source for inspection after compilation failure src_filename = os.path.join(fail_dir, src_basename) lockfree_move_file(temp_src_filename, src_filename) # Write compile command to failure dir, adjusted to use local # source file name so it can be rerun cmd = make_compile_command(src_basename, lib_basename, dependencies, build_params, cache_params) cmds = " ".join(cmd) script = "#!/bin/bash\n# Execute this file to recompile locally\n" + cmds cmd_filename = os.path.join(fail_dir, "recompile.sh") store_textfile(cmd_filename, script) make_executable(cmd_filename) # Write readme file with instructions readme = "Run or source recompile.sh to compile locally and reproduce the build failure.\n" readme_filename = os.path.join(fail_dir, "README") store_textfile(readme_filename, readme) # Write compiler output to failure dir (will refer to temp paths) log_filename = os.path.join(fail_dir, "error.log") store_textfile(log_filename, output) info("------------------- Start compiler output ------------------------") info(output) info("------------------- End compiler output ------------------------") warning("Compilation failed! Sources, command, and " "errors have been written to: %s" % (fail_dir,)) err_info = {'src_filename': src_filename, 'cmd_filename': cmd_filename, 'readme_filename': readme_filename, 'fail_dir': fail_dir, 'log_filename': log_filename} return status, output, lib_filename, err_info fenics-project-dijitso-c92dcb05ca82/dijitso/cache.py000066400000000000000000000405771345606466200224360ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """Utilities for disk cache features of dijitso.""" from glob import glob import os import re import sys import ctypes from dijitso.system import ldd from dijitso.system import make_dirs from dijitso.system import try_delete_file, try_copy_file from dijitso.system import gzip_file, gunzip_file from dijitso.system import read_textfile, store_textfile from dijitso.log import debug, error, warning def extract_files(signature, cache_params, prefix="", path=os.curdir, categories=("inc", "src", "lib", "log")): """Make a copy of files stored under this signature. Target filenames are '/-.*' """ path = os.path.join(path, prefix + signature) make_dirs(path) if "inc" in categories: inc_filename = create_inc_filename(signature, cache_params) try_copy_file(inc_filename, path) if "src" in categories: src_filename = create_src_filename(signature, cache_params) if not os.path.exists(src_filename): src_filename = src_filename + ".gz" if os.path.exists(src_filename): try_copy_file(src_filename, path) if src_filename.endswith(".gz"): gunzip_file(os.path.join(path, os.path.basename(src_filename))) if "lib" in categories: lib_filename = create_lib_filename(signature, cache_params) try_copy_file(lib_filename, path) if "log" in categories: log_filename = create_log_filename(signature, cache_params) try_copy_file(log_filename, path) return path def extract_lib_signatures(cache_params): "Extract signatures from library files in cache." p = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"]) filenames = glob(os.path.join(p, "*")) r = re.compile(create_lib_filename("(.*)", cache_params)) sigs = [] for f in filenames: m = r.match(f) if m: sigs.append(m.group(1)) return sigs def clean_cache(cache_params, dryrun=True, categories=("inc", "src", "lib", "log")): "Delete files from cache." gc = glob_cache(cache_params, categories=categories) for category in gc: for fn in gc[category]: if dryrun: print("rm %s" % (fn,)) else: try_delete_file(fn) def glob_cache(cache_params, categories=("inc", "src", "lib", "log")): """Return dict with contents of cache subdirectories.""" g = {} for foo in categories: p = os.path.join(cache_params["cache_dir"], cache_params[foo + "_dir"]) g[foo] = glob(os.path.join(p, "*")) return g def grep_cache(regex, cache_params, linenumbers=False, countonly=False, signature=None, categories=("inc", "src", "log")): "Search through files in cache for a pattern." allmatches = {} gc = glob_cache(cache_params, categories=categories) for category in categories: for fn in gc.get(category, ()): # Skip non-matches if specific signature is specified if signature is not None and signature not in fn: continue if countonly: matches = 0 else: matches = [] if category == "lib": # If category is "lib", use ldd # TODO: on mac need to use otool libs = ldd(fn) for k, libpath in sorted(libs.items()): if not libpath: continue m = regex.match(libpath) if m: if countonly: matches += 1 else: line = "%s => %s" % (k, libpath) matches.append(line) else: content = read_textfile(fn) lines = content.splitlines() if content else () for i, line in enumerate(lines): m = regex.match(line) if m: if countonly: matches += 1 else: line = line.rstrip("\n\r") if linenumbers: line = (i, line) matches.append(line) if matches: allmatches[fn] = matches return allmatches def extract_function(lines): "Extract function code starting at first line of lines." n = len(lines) # Function starts at line 0 by assumption begin = 0 # Worst case body range body_begin = begin body_end = n # Body starts at first { for i in range(begin, n): if "{" in lines[i]: body_begin = i break # Body ends when {} are balanced back to 0 braces = 0 for i in range(body_begin, n): if "{" in lines[i]: braces += 1 if "}" in lines[i]: braces -= 1 if braces == 0: body_end = i break # Include the last line in range end = body_end + 1 sublines = lines[begin:end] return "".join(sublines) def _create_basename(foo, signature, cache_params): return "".join((cache_params.get(foo + "_prefix", ""), cache_params.get(foo + "_basename", ""), signature, cache_params.get(foo + "_postfix", ""))) def _create_filename(foo, signature, cache_params): basename = _create_basename(foo, signature, cache_params) return os.path.join(cache_params["cache_dir"], cache_params[foo + "_dir"], basename) def create_log_filename(signature, cache_params): "Create log filename based on signature and params." return _create_filename("log", signature, cache_params) def create_inc_basename(signature, cache_params): "Create header filename based on signature and params." return _create_basename("inc", signature, cache_params) def create_inc_filename(signature, cache_params): "Create header filename based on signature and params." return _create_filename("inc", signature, cache_params) def create_src_filename(signature, cache_params): "Create source code filename based on signature and params." return _create_filename("src", signature, cache_params) def create_src_basename(signature, cache_params): "Create source code filename based on signature and params." return _create_basename("src", signature, cache_params) def create_lib_basename(signature, cache_params): "Create library filename based on signature and params." return _create_basename("lib", signature, cache_params) def create_lib_filename(signature, cache_params): "Create library filename based on signature and params." return _create_filename("lib", signature, cache_params) def create_libname(signature, cache_params): """Create library name based on signature and params, without path, prefix 'lib', or extension '.so'.""" return cache_params["lib_basename"] + signature def create_fail_dir_path(signature, cache_params): "Create path name to place files after a module build failure." fail_root = cache_params["fail_dir_root"] or os.curdir fail_dir = os.path.join(fail_root, "jitfailure-" + signature) return os.path.abspath(fail_dir) def make_inc_dir(cache_params): d = os.path.join(cache_params["cache_dir"], cache_params["inc_dir"]) make_dirs(d) return d def make_src_dir(cache_params): d = os.path.join(cache_params["cache_dir"], cache_params["src_dir"]) make_dirs(d) return d def make_lib_dir(cache_params): d = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"]) make_dirs(d) return d def make_log_dir(cache_params): d = os.path.join(cache_params["cache_dir"], cache_params["log_dir"]) make_dirs(d) return d _ensure_dirs_called = {} def ensure_dirs(cache_params): global _ensure_dirs_called # This ensures directories are created only once during a process # for each value that cache_dir takes, in case it changes during # the process lifetime. c = cache_params["cache_dir"] if c not in _ensure_dirs_called: make_inc_dir(cache_params) make_src_dir(cache_params) make_lib_dir(cache_params) make_log_dir(cache_params) _ensure_dirs_called[c] = True def read_library_binary(lib_filename): "Read compiled shared library as binary blob into a numpy byte array." import numpy return numpy.fromfile(lib_filename, dtype=numpy.uint8) def write_library_binary(lib_data, signature, cache_params): "Store compiled shared library from binary blob in numpy byte array to cache." make_lib_dir(cache_params) lib_filename = create_lib_filename(signature, cache_params) lib_data.tofile(lib_filename) # TODO: Set permissions? def analyse_load_error(e, lib_filename, cache_params): # Try to analyse error further for better error message: msg = str(e) r = re.compile("(" + create_lib_basename(".*", cache_params) + ")") m = r.match(msg) if m: # Found libname mentioned in message mlibname = m.group(1) mlibname = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"], mlibname) else: mlibname = lib_filename if lib_filename != mlibname: # Message mentions some other dijitso library, # double check if this other file exists # (if it does, could be paths or rpath issue) if os.path.exists(mlibname): emsg = ("dijitso failed to load library:\n\t%s\n" "but dependency file exists:\n\t%s\nerror is:\n\t%s" % ( lib_filename, mlibname, str(e))) else: emsg = ("dijitso failed to load library:\n\t%s\n" "dependency file missing:\n\t%s\nerror is:\n\t%s" % ( lib_filename, mlibname, str(e))) else: # Message doesn't mention another dijitso library, # double check if library file we tried to load exists # (if it does, could be paths issue) if os.path.exists(lib_filename): emsg = ("dijitso failed to load existing file:\n" "\t%s\nerror is:\n\t%s" % (lib_filename, str(e))) else: emsg = ("dijitso failed to load missing file:\n" "\t%s\nerror is:\n\t%s" % (lib_filename, str(e))) return emsg def load_library(signature, cache_params): """Load existing dynamic library from disk. Returns library module if found, otherwise None. If found, the module is placed in memory cache for later lookup_lib calls. """ lib_filename = create_lib_filename(signature, cache_params) if not os.path.exists(lib_filename): debug("File %s does not exist" % (lib_filename,)) return None debug("Loading %s from %s" % (signature, lib_filename)) if cache_params["lib_loader"] == "ctypes": try: lib = ctypes.cdll.LoadLibrary(lib_filename) except os.error as e: lib = None emsg = analyse_load_error(e, lib_filename, cache_params) warning(emsg) else: debug("Loaded %s from %s" % (signature, lib_filename)) elif cache_params["lib_loader"] == "import": sys.path.append(os.path.dirname(lib_filename)) # Will raise an exception if it does not load correctly lib = __import__(signature) debug("Loaded %s from %s" % (signature, lib_filename)) else: error("Invalid loader: %s" % cache_params["lib_loader"]) if lib is not None: # Disk loading succeeded, register loaded library in memory # cache for next time _lib_cache[signature] = lib return lib # A cache is always something to be careful about. This one stores # references to loaded jit-compiled libraries, which will stay in # memory unless manually unloaded anyway and should not cause any # trouble. _lib_cache = {} def lookup_lib(lib_signature, cache_params): """Lookup library in memory cache then in disk cache. Returns library module if found, otherwise None. """ # Look for already loaded library in memory cache lib = _lib_cache.get(lib_signature) if lib is None: # Cache miss in memory, try looking on disk lib = load_library(lib_signature, cache_params) else: debug("Fetched %s from memory cache" % (lib_signature,)) # Return library or None return lib def read_src(signature, cache_params): """Lookup source code in disk cache and return file contents or None.""" filename = create_src_filename(signature, cache_params) return read_textfile(filename) def read_inc(signature, cache_params): """Lookup header file in disk cache and return file contents or None.""" filename = create_inc_filename(signature, cache_params) return read_textfile(filename) def read_log(signature, cache_params): """Lookup log file in disk cache and return file contents or None.""" filename = create_log_filename(signature, cache_params) return read_textfile(filename) def store_src(signature, content, cache_params): "Store source code in file within dijitso directories." make_src_dir(cache_params) filename = create_src_filename(signature, cache_params) store_textfile(filename, content) return filename def store_inc(signature, content, cache_params): "Store header file within dijitso directories." make_inc_dir(cache_params) filename = create_inc_filename(signature, cache_params) store_textfile(filename, content) return filename def store_log(signature, content, cache_params): "Store log file within dijitso directories." make_log_dir(cache_params) filename = create_log_filename(signature, cache_params) store_textfile(filename, content) return filename def compress_source_code(src_filename, cache_params): """Keep, delete or compress source code based on value of cache parameter 'src_storage'. Can be "keep", "delete", or "compress". """ src_storage = cache_params["src_storage"] if src_storage == "keep": filename = src_filename elif src_storage == "delete": try_delete_file(src_filename) filename = None elif src_storage == "compress": filename = gzip_file(src_filename) try_delete_file(src_filename) else: error("Invalid src_storage parameter. Expecting 'keep', 'delete', or 'compress'.") return filename def get_dijitso_dependencies(libname, cache_params): "Run ldd and filter output to only include dijitso cache entries." libs = ldd(libname) dlibs = {} for k in libs: if k.startswith(cache_params["lib_prefix"]): dlibs[k] = libs[k] return dlibs # TODO: Use this in command-line tools? def check_cache_integrity(cache_params): "Check dijitso cache integrity." libnames = set(glob(cache_params["lib_prefix"] + "*" + cache_params["lib_postfix"])) dmissing = {} for libname in libnames: dlibs = get_dijitso_dependencies(libname, cache_params) # Missing on file system: missing = [k for k in dlibs if k not in libnames] for k in dlibs: if k not in missing: # ldd thinks file is missing but it's there, linker issue? pass if missing: dmissing[libname] = sorted(missing) return dmissing def report_cache_integrity(dmissing, out=warning): "Print cache integrity report." if dmissing: out("%d libraries are missing one or more dependencies:" % len(dmissing)) for k in sorted(dmissing): out("\t%s depends on missing libraries:" % k) for m in dmissing[k]: out("\t\t%s" % m) fenics-project-dijitso-c92dcb05ca82/dijitso/cmdline.py000066400000000000000000000213771345606466200230030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """This file contains the commands available through command-line dijitso-cache. Each function cmd_ becomes a subcommand invoked by:: dijitso-cache cmdname ...args The docstrings in the cmd_ are shown when running:: dijitso-cache cmdname --help The 'args' argument to cmd_* is a Namespace object with the commandline arguments. """ import os import re from dijitso import __version__ from dijitso.cache import glob_cache, grep_cache, clean_cache from dijitso.cache import extract_lib_signatures from dijitso.cache import extract_files, extract_function from dijitso.system import read_textfile def parse_categories(categories): if categories == "all": return ("inc", "src", "lib", "log") return categories.split(",") def args_version(parser): pass def cmd_version(args, params): "print dijitso version" print(__version__) def args_config(parser): parser.add_argument("--key", default="", help="specific key to show (e.g. build.cxxflags)") def cmd_config(args, params): "show configuration" # Show single value if asked for key = args.key if key: name = key value = params for k in key.split("."): value = value[k] # Compiler flags etc are more useful in space separated form: if isinstance(value, tuple): value = " ".join(value) print(" %s: %s" % (name, value)) return 0 # Pick non-empty categories categories = sorted(c for c in params if params[c]) print("Showing default flags for dijitso:") for category in categories: print("%s:" % (category,)) for name in sorted(params[category]): value = params[category][name] # Compiler flags etc are more useful in space separated form: if isinstance(value, tuple): value = " ".join(value) print(" %s: %s" % (name, value)) return 0 def args_show(parser): parser.add_argument("--categories", default="all", help="comma separated list to enable file types (inc,src,lib,log)") parser.add_argument("--no-summary", action="store_true", help="don't show summary") parser.add_argument("--files", action="store_true", help="show file lists") parser.add_argument("--signatures", action="store_true", help="show library signatures") def cmd_show(args, params): "show lists of files in cache" cache_params = params["cache"] summary = not args.no_summary files = args.files signatures = args.signatures categories = parse_categories(args.categories) gc = glob_cache(cache_params, categories=categories) if signatures: sigs = extract_lib_signatures(cache_params) print("\n".join("\t" + s for s in sorted(sigs))) if files: for cat in categories: print("\n".join("\t" + f for f in sorted(gc.get(cat, ())))) if summary: print("dijitso cache summary (number of cached files):") for cat in categories: print("%s: %d" % (cat, len(gc.get(cat, ())))) # TODO: Add summary of file sizes return 0 def args_clean(parser): parser.add_argument("--categories", default="inc,src,lib,log", help="comma separated list to enable file types (inc,src,lib,log)") def cmd_clean(args, params): "remove files from cache" cache_params = params["cache"] dryrun = args.dry_run categories = parse_categories(args.categories) clean_cache(cache_params, dryrun=dryrun, categories=categories) return 0 def args_grep(parser): parser.add_argument("--categories", default="inc,src", help="comma separated list to enable file types (inc,src,lib,log)") parser.add_argument("--pattern", default="", help="line search pattern") parser.add_argument("--regexmode", action="store_true", help="pattern is a regular expression (python style)") parser.add_argument("--linenumbers", action="store_true", help="show linenumbers on matches") parser.add_argument("--countonly", action="store_true", help="show only match line count for each file") parser.add_argument("--filesonly", action="store_true", help="show only filenames with matches") parser.add_argument("--signature", default="", help="look for module with this signature (default all)") def cmd_grep(args, params): "grep content of header and source file(s) in cache" cache_params = params["cache"] # Get command-line arguments pattern = args.pattern signature = args.signature regexmode = args.regexmode linenumbers = args.linenumbers countonly = args.countonly filesonly = args.filesonly categories = parse_categories(args.categories) if not regexmode: pattern = ".*(" + pattern + ").*" regex = re.compile(pattern) allmatches = grep_cache(regex, cache_params, linenumbers=linenumbers, countonly=countonly, signature=signature, categories=categories) if filesonly: print("\n".join(sorted(allmatches))) elif countonly: print("\n".join("%s: %d" % (k, v) for k, v in sorted(allmatches.items()))) else: for fn in sorted(allmatches): print("\nFile '%s' matches:" % (fn,)) if linenumbers: print("\n".join("%5d:\t%s" % line for line in allmatches[fn])) else: print("\n".join("\t" + line for line in allmatches[fn])) return 0 def args_grepfunction(parser): parser.add_argument("--categories", default="src", help="comma separated list to enable file types (inc,src,lib,log)") parser.add_argument("--name", default="", help="function name to search for") parser.add_argument("--signature", default="", help="look for module with this signature (default all)") parser.add_argument("--no-body", action="store_true", help="don't show function bodies") def cmd_grepfunction(args, params): "search for function name in source files in cache" cache_params = params["cache"] name = args.name signature = args.signature categories = parse_categories(args.categories) no_body = args.no_body pattern = r".*(" + name + r")[ ]*\((.*)" regex = re.compile(pattern) allmatches = grep_cache(regex, cache_params, linenumbers=True, countonly=False, signature=signature, categories=categories) for fn in sorted(allmatches): if no_body: # Just print signature lines print("\nFile '%s' matches:" % (fn,)) for i, line in allmatches[fn]: print("%5d: %s" % (i, line)) else: # Print function bodies content = read_textfile(fn) lines = content.splitlines() if content else () for i, line in allmatches[fn]: print("%s:%d" % (fn, i)) assert name in lines[i] print(extract_function(lines[i:])) print() return 0 def args_checkout(parser): parser.add_argument("--categories", default="inc,src,lib,log", help="comma separated list to enable file types (inc,src,lib,log)") parser.add_argument("--signature", help="module signature (required)") def cmd_checkout(args, params): "copy files from cache to a directory" cache_params = params["cache"] signature = args.signature categories = parse_categories(args.categories) prefix = "jitcheckout-" path = os.curdir path = extract_files(signature, cache_params, prefix=prefix, path=path, categories=categories) print("Extracted files to '%s'." % (path,)) return 0 fenics-project-dijitso-c92dcb05ca82/dijitso/jit.py000066400000000000000000000212021345606466200221410ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """This module contains the main jit() function and related utilities.""" import ctypes import numpy from dijitso.log import error from dijitso.params import validate_params from dijitso.str import as_unicode from dijitso.cache import lookup_lib, load_library from dijitso.cache import write_library_binary, read_library_binary from dijitso.build import build_shared_library from dijitso.signatures import hash_params class DijitsoError(RuntimeError): def __init__(self, message, err_info): super(DijitsoError, self).__init__(message) self.err_info = err_info def extract_factory_function(lib, name): """Extract function from loaded library. Assuming signature ``(void *)()``, for anything else use look at ctypes documentation. Returns the factory function or raises error. """ function = getattr(lib, name) function.restype = ctypes.c_void_p return function def jit_signature(name, params): # TODO: Unused? """Compute the signature that jit will use for given name and params.""" # Validation and completion with defaults for missing parameters params = validate_params(params) # Extend provided name of jitable with hash of relevant parameters signature_params = { "generator": params["generator"], "build": params["build"] } signature = "%s_%s" % (name, hash_params(signature_params)) return signature # TODO: send, receive, wait functionality is not currently in use, # decide to use it from dolfin or clean up the code and comments here. def jit(jitable, name, params, generate=None, send=None, receive=None, wait=None): """Just-in-time compile and import of a shared library with a cache mechanism. A signature is computed from the name, params["generator"], and params["build"]. The name should be a unique identifier for the jitable, preferrably produced by a good hash function. The signature is used to identity if the library has already been compiled and cached. A two-level memory and disk cache ensures good performance for repeated lookups within a single program as well as persistence across program runs. If no library has been cached, the passed 'generate' function is called to generate the source code: header, source, dependencies = \ generate(jitable, name, signature, params["generator"]) It is expected to translate the 'jitable' object into C or C++ (default) source code which will subsequently be compiled as a shared library and stored in the disk cache. The returned 'dependencies' should be a tuple of signatures returned from other completed dijitso.jit calls, and are linked to when building. The compiled shared library is then loaded with ctypes and returned. For use in a parallel (MPI) context, three functions send, receive, and wait can be provided. Each process can take on a different role depending on whether generate, or receive, or neither is provided. * Every process that gets a generate function is called a 'builder', and will generate and compile code as described above on a cache miss. If the function send is provided, it will then send the shared library binary file as a binary blob by calling send(numpy_array). * Every process that gets a receive function is called a 'receiver', and will call 'numpy_array = receive()' expecting the binary blob with a compiled binary shared library which will subsequently be written to file in the local disk cache. * The rest of the processes are called 'waiters' and will do nothing. * If provided, all processes will call wait() before attempting to load the freshly compiled library from disk cache. The intention of the above pattern is to be flexible, allowing several different strategies for sharing build results. The user of dijitso can determine groups of processes that share a disk cache, and assign one process per physical disk cache directory to write to that directory, avoiding multiple processes writing to the same files. This forms the basis for three main strategies: * Build on every process. * Build on one process per physical cache directory. * Build on a single global root node and send a copy of the binary to one process per physical cache directory. It is highly recommended to avoid have multiple builder processes sharing a physical cache directory. """ # TODO: Could simplify interface here and roll # (jitable, name, params["generator"]) into a single jitobject? # TODO: send/receive doesn't combine well with generate # triggering additional jit calls for dependencies. # It's possible that dependencies are hard to determine without # generate doing some analysis that we want to avoid. # Drop send/receive? Probably not that useful anyway. # Complete params with hardcoded defaults and config file defaults params = validate_params(params) # 0) Look for library in memory or disk cache # FIXME: use only name as signature for now # TODO: just remove one of signature or name from API? # signature = jit_signature(name, params) name = as_unicode(name) signature = name cache_params = params["cache"] lib = lookup_lib(signature, cache_params) err_info = None if lib is None: # Since we didn't find the library in cache, we must build it. if receive and generate: # We're not supposed to generate if we're receiving error("Please provide only one of generate or receive.") elif generate: # 1) Generate source code header, source, dependencies = generate(jitable, name, signature, params["generator"]) # Ensure we got unicode from generate header = as_unicode(header) source = as_unicode(source) dependencies = [as_unicode(dep) for dep in dependencies] # 2) Compile shared library and 3) store in dijitso # inc/src/lib dir on success # NB! It's important to not raise exception on compilation # failure, such that we can reach wait() together with # other processes if any. status, output, lib_filename, err_info = \ build_shared_library(signature, header, source, dependencies, params) # 4a) Send library over network if we have a send function if send: if status == 0: lib_data = read_library_binary(lib_filename) else: lib_data = numpy.zeros((1,)) send(lib_data) elif receive: # 4b) Get library as binary blob from given receive # function and store in cache lib_data = receive() # Empty if compilation failed status = -1 if lib_data.shape == (1,) else 0 if status == 0: write_library_binary(lib_data, signature, cache_params) else: # Do nothing (we'll be waiting below for other process to # build) if not wait: error("Please provide wait if not providing one of generate or receive.") # 5) Notify waiters that we're done / wait for builder to # notify us if wait: wait() # Finally load library from disk cache (places in memory # cache) # NB! This returns None if the file does not exist, # i.e. if compilation failed on builder process lib = load_library(signature, cache_params) if err_info: # TODO: Parse output to find error(s) for better error messages raise DijitsoError("Dijitso JIT compilation failed, see '%s' for details" % err_info['fail_dir'], err_info) # Return built library and its signature return lib, signature fenics-project-dijitso-c92dcb05ca82/dijitso/log.py000066400000000000000000000040221345606466200221350ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs, Jan Blechta # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . import logging __all__ = ['set_log_level', 'get_logger', 'get_log_handler', 'set_log_handler'] _log = logging.getLogger("dijitso") _loghandler = logging.StreamHandler() _log.addHandler(_loghandler) _log.setLevel(logging.INFO) def get_log_handler(): return _loghandler def get_logger(): return _log def set_log_handler(handler): global _loghandler _log.removeHandler(_loghandler) _loghandler = handler _log.addHandler(_loghandler) def set_log_level(level): """Set verbosity of logging. Argument is int or one of "INFO", "WARNING", "ERROR", or "DEBUG". """ if isinstance(level, str): level = level.upper() assert level in ("INFO", "WARNING", "ERROR", "DEBUG") level = getattr(logging, level) else: assert isinstance(level, int) _log.setLevel(level) # Logging interface for dijitso library def debug(*message): _log.debug(*message) def info(*message): _log.info(*message) def warning(*message): _log.warning(*message) def error(*message): _log.error(*message) text = message[0] % message[1:] raise RuntimeError(text) def dijitso_assert(condition, *message): if not condition: _log.error(*message) text = message[0] % message[1:] raise AssertionError(text) fenics-project-dijitso-c92dcb05ca82/dijitso/mpi.py000066400000000000000000000224271345606466200221520ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """Utilities for mpi features of dijitso.""" import io import os import uuid from glob import glob import numpy from dijitso.log import info, error from dijitso.system import try_delete_file def bcast_uuid(comm): "Create a unique id shared across all processes in comm." guid = numpy.ndarray((1,), dtype=numpy.uint64) if comm.rank == 0: # uuid creates a unique 128 bit id, we just pick the low 64 bits guid[0] = numpy.uint64(uuid.uuid4().int & ((1 << 64) - 1)) comm.Bcast(guid, root=0) return int(guid[0]) def discover_path_access_ranks(comm, path): """Discover which ranks share access to the same directory. This cannot be done by comparing paths, because a path string can represent a local work directory or a network mapped directory, depending on cluster configuration. Current approach is that each process touches a filename with its own rank in their given path. By reading in the filelist from the same path, we'll find which ranks have access to the same directory. To avoid problems with leftover files from previous program crashes, or collisions between simultaneously running programs, we use a random uuid in the filenames written. """ # Create a unique basename for rank files of this program guid = bcast_uuid(comm) # TODO: Run this in an init function and store for program duration? basename = os.path.join(path, "rank.%d." % guid) # Write the rank of this process to a filename filename = basename + str(comm.rank) with io.open(filename, "wb"): pass # Wait for all writes to take place. Don't know how robust this is # with nfs!!! comm.Barrier() # Read filelist noderanks = sorted([int(fn.replace(basename, "")) for fn in glob(basename + "*")]) # Wait for everyone to finish reading filelist comm.Barrier() # Clean up our own rank file. If the process is aborted, # this may fail to happen and leave a dangling file! # However the file takes no space, and the guid ensures # it won't be colliding with other filenames. # TODO: Include a gc command in dijitso to clean up this and other stuff. try_delete_file(filename) return noderanks def gather_global_partitions(comm, partition): """Gather an ordered list of unique partition values within comm.""" global_partitions = numpy.ndarray((comm.size,), dtype=numpy.uint64) local_partition = numpy.ndarray((1,), dtype=numpy.uint64) local_partition[0] = partition comm.Allgather(local_partition, global_partitions) return sorted(set(global_partitions)) def create_subcomm(comm, ranks): "Create a communicator for a set of ranks." group = comm.Get_group() subgroup = group.Incl(ranks) subcomm = comm.Create(subgroup) subgroup.Free() group.Free() return subcomm def create_node_comm(comm, comm_dir): """Create comms for communicating within a node.""" # Find ranks that share this physical comm_dir (physical dir, not same path string) node_ranks = discover_path_access_ranks(comm, comm_dir) # Partition comm into one communicator for each physical comm_dir assert len(node_ranks) >= 1 node_root = min(node_ranks) node_comm = comm.Split(node_root, node_ranks.index(comm.rank)) return node_comm, node_root def create_node_roots_comm(comm, node_root): """Build comm for communicating among the node roots.""" unique_global_node_roots = gather_global_partitions(comm, node_root) roots_comm = create_subcomm(comm, unique_global_node_roots) return roots_comm def create_comms_and_role_root(comm, node_comm, node_root): """Approach: global root builds and sends binary to node roots, everyone waits on their node group.""" copy_comm = create_node_roots_comm(comm, node_root) wait_comm = node_comm if comm.rank == 0: role = "builder" elif node_comm.rank == 0: assert comm.rank == node_root role = "receiver" else: assert comm.rank != node_root role = "waiter" return copy_comm, wait_comm, role def create_comms_and_role_node(comm, node_comm, node_root): """Approach: each node root builds, everyone waits on their node group.""" copy_comm = None wait_comm = node_comm if node_comm.rank == 0: assert comm.rank == node_root role = "builder" else: assert comm.rank != node_root role = "waiter" return copy_comm, wait_comm, role def create_comms_and_role_process(comm, node_comm, node_root): """Approach: each process builds its own module, no communication. To ensure no race conditions in this case independently of cache dir setup, we include an error check on the size of the autodetected node_comm. This should always be 1, or we provide the user with an informative message. TODO: Append program uid and process rank to basedir instead? """ if node_comm.size > 1: error("Asking for per-process building but processes share cache dir." " Please configure dijitso dirs to be distinct per process.") copy_comm = None wait_comm = None assert node_comm.rank == 0 assert comm.rank == node_root role = "builder" return copy_comm, wait_comm, role def create_comms_and_role(comm, comm_dir, buildon): """Determine which role each process should take, and create the right copy_comm and wait_comm for the build strategy. buildon must be one of "root", "node", or "process". Returns (copy_comm, wait_comm, role). """ # Now assign values to the copy_comm, wait_comm, and role, # depending on buildon strategy chosen. If we have no comm, # always return the builder role if comm is None: copy_comm, wait_comm, role = None, None, "builder" else: node_comm, node_root = create_node_comm(comm, comm_dir) if buildon == "root": copy_comm, wait_comm, role = create_comms_and_role_root(comm, node_comm, node_root) elif buildon == "node": copy_comm, wait_comm, role = create_comms_and_role_node(comm, node_comm, node_root) elif buildon == "process": copy_comm, wait_comm, role = create_comms_and_role_process(comm, node_comm, node_root) else: error("Invalid parameter buildon=%s" % (buildon,)) return copy_comm, wait_comm, role def send_binary(comm, lib_data): "Send compiled library as binary blob over MPI." # TODO: Test this in parallel locally. # TODO: Test this in parallel on clusters. # http://mpi4py.scipy.org/docs/usrman/tutorial.html # Check that we are the root root = 0 assert comm.rank == root # Send file size lib_size = numpy.ndarray((1,), dtype=numpy.uint32) lib_size[0] = lib_data.shape[0] info("rank %d: send size with root=%d." % (comm.rank, root)) comm.Bcast(lib_size, root=root) # Send file contents info("rank %d: send data with root=%d." % (comm.rank, root)) comm.Bcast(lib_data, root=root) def receive_binary(comm): "Store shared library received as a binary blob to cache." # Check that we are not the root root = 0 assert comm.rank != root # Receive file size lib_size = numpy.ndarray((1,), dtype=numpy.uint32) info("rank %d: receive size with root=%d." % (comm.rank, root)) comm.Bcast(lib_size, root=root) # Receive file contents lib_data = numpy.ndarray(lib_size[0], dtype=numpy.uint8) info("rank %d: receive data with root=%d." % (comm.rank, root)) comm.Bcast(lib_data, root=root) return lib_data """ def foo(): # TODO: Should call these once (for each comm at least) globally # in dolfin, not on each jit call def get_comm_dir(cache_params): return os.path.join(cache_params["cache_dir"], cache_params["comm_dir"]) comm_dir = get_comm_dir() copy_comm, wait_comm, role = create_comms_and_role(comm, comm_dir, buildon) if wait_comm is not None: def wait(): wait_comm.Barrier() else: wait = None if copy_comm is not None and copy_comm.size > 1: def send(lib_data): send_binary(copy_comm, lib_data) else: send = None def receive(): return receive_binary(copy_comm) """ fenics-project-dijitso-c92dcb05ca82/dijitso/params.py000066400000000000000000000207331345606466200226460ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """Utilities for dijitso parameters.""" from glob import glob import os import sys import copy import numbers import configparser from dijitso.log import info, error, warning from dijitso.str import as_unicode # Warning for fenics backwards compatibility: if (os.environ.get("INSTANT_CACHE_DIR") and not os.environ.get("DIJITSO_CACHE_DIR")): warning("INSTANT_CACHE_DIR is no longer used by dijitso." " To set the cache directory for dijitso," " set DIJITSO_CACHE_DIR.") def discover_config_filename(): basename = ".dijitso.conf" search_paths = [ os.curdir, os.environ.get("DIJITSO_CONF"), os.path.expanduser("~"), "/etc/dijitso", ] for path in search_paths: if path is None: continue names = glob(os.path.join(path, basename)) if names: assert len(names) == 1 return names[0] return None _config_file_contents = None def read_config_file(): "Read config file and cache the contents for the duration of the process." global _config_file_contents if _config_file_contents is None: filename = discover_config_filename() _config_file_contents = {} if filename is not None: info("Using config file '%s'." % (filename,)) parser = configparser.SafeConfigParser() parser.read(filename) for category in parser.sections(): category = as_unicode(category) _config_file_contents[category] = {} for name, value in parser.items(category): name = as_unicode(name) value = as_unicode(value) _config_file_contents[category][name] = value return _config_file_contents def default_cache_params(): if sys.platform in ("win32", "cygwin"): default_lib_postfix = ".dll" else: default_lib_postfix = ".so" p = dict( cache_dir=None, # See validate_params inc_dir="include", src_dir="src", lib_dir="lib", fail_dir_root=None, temp_dir_root=None, comm_dir="comm", log_dir="log", enable_build_log=True, src_storage="compress", src_postfix=".cpp", log_postfix=".txt", inc_postfix=".h", lib_postfix=default_lib_postfix, lib_prefix="lib", lib_basename="dijitso-", lib_loader="ctypes" ) return p def default_cxx_compiler(): "Default C++ compiler" return os.getenv("CXX", "c++") def default_cxx_flags(): "Default C++ flags for all build modes." # Dropped because of some symbol sharing across dependent modules from ffc: # "-fvisibility=hidden", return ("-Wall", "-shared", "-fPIC", "-std=c++11") def default_cxx_debug_flags(): "Default C++ flags for debug=True. Note: FFC always overrides these." return ("-g", "-O0") def default_cxx_release_flags(): "Default C++ flags for debug=False. Note: FFC always overrides these." # These flags deal with handling of nan, inf, underflow, division # by zero, etc. which should be ok for most of our purposes. It # might be better to place them in ffc or make them dependent on # compiler or optional or whatever, just throwing them in here now # to see how it works out. safe_fastmath_parts = ("-fno-math-errno", "-fno-trapping-math", "-ffinite-math-only") return ("-O3",) + safe_fastmath_parts def default_build_params(): p = dict( cxx=default_cxx_compiler(), cxxflags=default_cxx_flags(), cxxflags_debug=default_cxx_debug_flags(), cxxflags_opt=default_cxx_release_flags(), include_dirs=(), lib_dirs=(), rpath_dirs=(), libs=(), debug=False, ) return p def default_generator_params(): return {} def default_params(): p = dict( cache=default_cache_params(), build=default_build_params(), generator=default_generator_params(),) return p _session_defaults = None def session_default_params(): global _session_defaults if _session_defaults is None: _session_defaults = validate_params() return copy.deepcopy(_session_defaults) def as_bool(value): if isinstance(value, bool): return value elif value in ("True", "true", "1"): return True elif value in ("False", "false", "0"): return False else: error("Invalid boolean value %s" % (value,)) def as_str_tuple(p): """Convert p to a tuple of strings, allowing a list or tuple of strings or a single string as input.""" if isinstance(p, str): return (as_unicode(p),) elif isinstance(p, (tuple, list)): if all(isinstance(item, str) for item in p): return tuple(as_unicode(item) for item in p) raise RuntimeError("Expecting a string or list of strings, not %s." % (p,)) def copy_params(params): "Copy two-level dict of params." return {k: v.copy() for k, v in params.items()} def check_params_keys(default, params): "Check that keys in params exist in defaults." for category in params: if category == "generator": continue if category not in default: error("Invalid parameter category '%s'." % category) if params[category] is not None: invalid = set(params[category]) - set(default[category]) if invalid: error("Invalid parameter names %s in category '%s'." % (sorted(invalid), category)) def merge_params(default, params): "Merge two-level param dicts." p = {} for category in default: d = default[category].copy() p[category] = d v = params.get(category) if v is not None: p[category].update(v) return p def validate_params(params): """Validate parameters to dijitso and fill in with defaults where missing.""" # Start with defaults p0 = default_params() p = p0 # Override with config file if any c = read_config_file() if c: check_params_keys(p, c) p = merge_params(p, c) # Override with runtime params if any if params: check_params_keys(p, params) p = merge_params(p, params) # Convert parameter types for category in p: category = as_unicode(category) if category == "generator": continue for name, value in p[category].items(): name = as_unicode(name) v0 = p0[category][name] if isinstance(v0, str): value = as_unicode(value) # Expand paths including "~" to include # full user home directory path if name.endswith("_dir") and "~" in value: value = os.path.expanduser(value) elif isinstance(v0, bool): value = as_bool(value) elif isinstance(v0, numbers.Number): value = type(v0)(value) elif isinstance(v0, tuple): value = as_str_tuple(value) p[category][name] = value # Allow environment variables to override default cache dir # Let dijitso specific dir win the contest cache_dir = os.environ.get("DIJITSO_CACHE_DIR") if not cache_dir: # Place default cache dir in virtualenv or conda prefix # if one of them are active, or under user's home directory home = os.path.expanduser("~") venv = os.environ.get("VIRTUAL_ENV") cenv = os.environ.get("CONDA_PREFIX") if venv == sys.prefix: env = venv elif cenv == sys.prefix: env = cenv else: env = home cache_dir = os.path.join(env, ".cache", "dijitso") p["cache"]["cache_dir"] = as_unicode(cache_dir) return p fenics-project-dijitso-c92dcb05ca82/dijitso/signatures.py000066400000000000000000000032651345606466200235500ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . import hashlib # Arbitrarily chosen hash digest cutoff to keep filename lengths # reasonably small. If this is too short hashes will collide! HASHLENGTH = 12 def hashit(data): "Return hash of anything with a repr implementation." h = hashlib.sha1() h.update(repr(data).encode('utf-8')) return h.hexdigest()[:HASHLENGTH] def canonicalize_params_for_hashing(params): if params: data = () else: assert isinstance(params, dict) keys = sorted(params) assert all(isinstance(key, str) for key in keys) items = [] for k in keys: k = k.encode('utf-8') v = params[k] if isinstance(v, dict): items.append((k, canonicalize_params_for_hashing(v))) else: items.append((k, repr(v).encode('utf-8'))) data = tuple(items) return data def hash_params(params): return hashit(canonicalize_params_for_hashing(params)) fenics-project-dijitso-c92dcb05ca82/dijitso/str.py000066400000000000000000000017001345606466200221640ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2016-2016 Martin Sandve Alnæs # # This file is part of UFL. # # UFL 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. # # UFL 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 UFL. If not, see . """String compatibility utilities.""" def as_unicode(s): "Return s if unicode string, or decode bytes to unicode string using utf-8." if isinstance(s, bytes): return s.decode("utf-8") else: return s fenics-project-dijitso-c92dcb05ca82/dijitso/system.py000066400000000000000000000250211345606466200227020ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . """Utilities for interfacing with the system.""" import os import errno import io import gzip import shutil import stat import uuid import re from glob import glob import tempfile import subprocess from dijitso.log import warning def _get_status_output_subprocess(cmd, input=None, cwd=None, env=None): """Replacement for commands.getstatusoutput which does not work on Windows (or Python 3).""" if isinstance(cmd, str): cmd = cmd.strip().split() pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (output, errout) = pipe.communicate(input=input) assert not errout status = pipe.returncode if isinstance(output, bytes): output = output.decode('utf-8') return (status, output) def _get_status_output_system(cmd): """Replacement for commands.getstatusoutput which does not work on Windows (or Python 3).""" if not isinstance(cmd, str): cmd = " ".join(cmd) # Default return values status = 1 output = "not run" # Execute cmd with redirection to temporary file with tempfile.NamedTemporaryFile(delete=True) as f: cmd += ' > ' + f.name + ' 2>&1' # NOTE: Possibly OFED-fork-safe, tests needed! status = os.system(cmd) output = f.read() if isinstance(output, bytes): output = output.decode('utf-8') return (status, output) # Choose method for calling external programs. Use subprocess by default. _call_method = "SUBPROCESS" _call_method = os.environ.get("DIJITSO_SYSTEM_CALL_METHOD", _call_method) if _call_method == "OS_SYSTEM": get_status_output = _get_status_output_system else: get_status_output = _get_status_output_subprocess def make_executable(filename): "Make script executable by setting user eXecutable bit." permissions = stat.S_IMODE(os.lstat(filename).st_mode) os.chmod(filename, permissions | stat.S_IXUSR) def make_dirs(path): """Creates a directory (tree). Ignores error if the directory already exists. """ try: os.makedirs(path) except os.error as e: if e.errno != errno.EEXIST: raise def rename_file(src, dst): """Rename a file. Ignores error if the destination file exists. """ try: os.rename(src, dst) except os.error as e: # Windows may trigger on existing destination if e.errno not in errno.EEXIST: raise def try_rename_file(src, dst): """Try to rename a file. NB! Ignores error if the SOURCE doesn't exist or the destination already exists. """ try: os.rename(src, dst) except os.error as e: # Windows may trigger on existing destination, # everyone triggers on missing source if e.errno not in (errno.ENOENT, errno.EEXIST): raise def try_copy_file(src, dst): """Try to copy a file. NB! Ignores any error. """ try: shutil.copy(src, dst) except Exception: pass def try_delete_file(filename): """Try to remove a file. Ignores error if filename doesn't exist. """ try: os.remove(filename) except os.error as e: if e.errno != errno.ENOENT: raise def gzip_file(filename): """Gzip a file. New file gets .gz extension added. Does nothing if the .gz file already exists. Original file is never touched. """ # Expecting source file to be there if not os.path.exists(filename): return None # Avoid doing work if file is already there gz_filename = filename + ".gz" if not os.path.exists(gz_filename): # Write gzipped contents to a temp file tmp_filename = filename + "-tmp-" + uuid.uuid4().hex + ".gz" with io.open(filename, "rb") as f_in, gzip.open(tmp_filename, "wb") as f_out: shutil.copyfileobj(f_in, f_out) # Safe move to target filename, other processes may compete here lockfree_move_file(tmp_filename, gz_filename) return gz_filename def gunzip_file(gz_filename): """Gunzip a file.""" assert gz_filename[-3:] == ".gz" filename = gz_filename[:-3] # Write gzipped contents to a temp file tmp_filename = filename + "-tmp-" + uuid.uuid4().hex with gzip.open(gz_filename, "rb") as f_in, io.open(tmp_filename, "wb") as f_out: shutil.copyfileobj(f_in, f_out) # Safe move to target filename, other processes may compete here lockfree_move_file(tmp_filename, filename) try_delete_file(gz_filename) return filename def read_textfile(filename): """Try to read file content, if necessary unzipped from filename.gz, return None if not found.""" if not os.path.exists(filename): filename = filename + ".gz" if not os.path.exists(filename): content = None else: if filename.endswith(".gz"): content = b"" with gzip.open(filename, "rb") as f: content = f.read() content = content.decode("utf-8") else: with io.open(filename, "r", encoding="utf-8") as f: content = f.read() return content def store_textfile(filename, content): """Store content to filename without race conditions. Works by first writing to a unique temp file and then moving to final destination. Handles both bytes and unicode. """ # Generate a unique temporary filename in same directory as the target file ui = uuid.uuid4().hex tmp_filename = "%s.%s" % (filename, ui) # Write the text to a temporary file if isinstance(content, bytes): # content is already bytes, write raw f = io.open(tmp_filename, "wb") else: f = io.open(tmp_filename, "w", encoding="utf8") with f: f.write(content) # Safely move file to target filename lockfree_move_file(tmp_filename, filename) return filename def move_file(srcfilename, dstfilename): """Move or copy a file.""" assert os.path.exists(srcfilename) shutil.move(srcfilename, dstfilename) assert not os.path.exists(srcfilename) assert os.path.exists(dstfilename) def lockfree_move_file(src, dst): """Lockfree and portable nfs safe file move operation. If target filename exists with different content, will move it to filename.old and emit a warning. Taken from textual description at http://stackoverflow.com/questions/11614815/a-safe-atomic-file-copy-operation """ return _lockfree_move_file(src, dst, False) def _lockfree_move_file(src, dst, recurse): if not os.path.exists(src): if recurse: return else: raise RuntimeError("Source file does not exist.") dst_exists = os.path.exists(dst) if dst_exists and recurse: warning("Backup file exists, overwriting.") elif dst_exists: # Destination file exists with io.open(src, "rb") as f: s = f.read() with io.open(dst, "rb") as f: d = f.read() # Uncompress gzipped files, as they contain a timestamp # and will otherwise always differ if (src[-3:] == '.gz'): s = gzip.decompress(s) d = gzip.decompress(d) if s == d: # Files are the same, just delete src instead of moving try_delete_file(src) return # Files differ, backup old file before moving file over it backup = dst + ".old" warning("Moving new file over differing existing file:\n" "src: %s\ndst: %s\nbackup: %s" % (src, dst, backup)) _lockfree_move_file(dst, backup, True) def priv(j): return dst + ".priv." + str(j) def pub(j): return dst + ".pub." + str(j) # Create a universally unique 128 bit integer id ui = uuid.uuid4().int # Move or copy file onto the target filesystem move_file(src, priv(ui)) # Atomic rename to make file visible to competing processes rename_file(priv(ui), pub(ui)) # Find uuids of competing files n = len(pub("*")) - 1 uuids = sorted(int(fn[n:]) for fn in glob(pub("*"))) # Try to delete all files with larger uuids for i in uuids: if i > ui: try_delete_file(pub(i)) for i in uuids: if i < ui: # Our file is the one with a larger uuid try_delete_file(pub(ui)) # Cooperate on handling uuid i ui = i if os.path.exists(dst): # If somebody else beat us to it, delete our file try_delete_file(pub(ui)) else: # Otherwise do an atomic rename to make our file final try_rename_file(pub(ui), dst) if os.path.exists(src): if recurse: # Somebody already generated new dest file which we just backed up pass else: raise RuntimeError("Source file should not exist at this point!") if not os.path.exists(dst): raise RuntimeError("Destination file should exist at this point!") def ldd(libname): """Run the ldd system tool on libname. Returns output as a dict {basename: fullpath} with all dynamic library dependencies and their resolution path. This is a debugging tool and may fail if ldd is not available or behaves differently on this system. """ status, output = get_status_output(["ldd", libname]) libraries = {} for line in output.splitlines(): match = re.match(r'(.*)=>([^(]*)(.*)', line) if match: dlib = match.group(1).strip() dlibpath = match.group(2).strip() address = match.group(3).strip() if address: # Path can be empty for system libs assert dlibpath == "" or os.path.exists(dlibpath) libraries[dlib] = dlibpath else: assert not os.path.exists(dlibpath) libraries[dlib] = None return libraries fenics-project-dijitso-c92dcb05ca82/doc/000077500000000000000000000000001345606466200201045ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/doc/man/000077500000000000000000000000001345606466200206575ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/doc/man/man1/000077500000000000000000000000001345606466200215135ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/doc/man/man1/dijitso.1.gz000066400000000000000000000011451345606466200236620ustar00rootroot00000000000000Wdijitso.1SAn0ZQAԎ8!|ŀ"UriAGi MjggfQwߒ7Q4~\J=+>2NAJY6xf'n/svwϗVuj>Ѩw>cIuǹ]g͡FYh*(mۢ!?zR]' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " epub3 to make an epub3" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/dijitso.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/dijitso.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/dijitso" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/dijitso" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: epub3 epub3: $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 @echo @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." .PHONY: dummy dummy: $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy @echo @echo "Build finished. Dummy builder generates no files." fenics-project-dijitso-c92dcb05ca82/doc/sphinx/README000066400000000000000000000011571345606466200223010ustar00rootroot00000000000000==================== Sphinx documentation ==================== DIJITSO is documented using Sphinx and reStructured text. The documentation is hosted at http://fenics-dijitso.readthedocs.org/. The online documentation is automatically updated upon pushes to the UFL master branch. Building the documentation locally ================================== The HTML documentation can be built locally using:: make html In order for changes in the docstring to be propagated to the html pages, the package must be installed anew. In other words, sphinx reads the docstrings from the installed code, not the source code. fenics-project-dijitso-c92dcb05ca82/doc/sphinx/requirements.txt000066400000000000000000000000161345606466200246760ustar00rootroot00000000000000sphinx==1.7.0 fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/000077500000000000000000000000001345606466200227155ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/conf.py000066400000000000000000000302471345606466200242220ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # dijitso documentation build configuration file, created by # sphinx-quickstart on Mon Jul 25 11:18:03 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import os import pkg_resources import datetime # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'dijitso' this_year = datetime.date.today().year copyright = u'%s, FEniCS Project' % this_year author = u'FEniCS Project' version = pkg_resources.get_distribution("fenics-dijitso").version release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # " v documentation" by default. # # html_title = u'dijitso v2016.02.1' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'dijitsodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'dijitso.tex', u'dijitso Documentation', u'FEniCS Project', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # It false, will not define \strong, \code, itleref, \crossref ... but only # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added # packages. # # latex_keep_old_macro_names = True # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'dijitso', u'dijitso Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'dijitso', u'dijitso Documentation', author, 'dijitso', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. # # epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. # # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. # # epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. # # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. # # epub_tocdepth = 3 # Allow duplicate toc entries. # # epub_tocdup = True # Choose between 'default' and 'includehidden'. # # epub_tocscope = 'default' # Fix unsupported image types using the Pillow. # # epub_fix_images = False # Scale large images. # # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # # epub_show_urls = 'inline' # If false, no index is generated. # # epub_use_index = True def run_apidoc(_): modules = ['dijitso'] # Get location of Sphinx files sphinx_source_dir = os.path.abspath(os.path.dirname(__file__)) repo_dir = os.path.abspath(os.path.join(sphinx_source_dir, os.path.pardir, os.path.pardir, os.path.pardir)) apidoc_dir = os.path.join(sphinx_source_dir, "api-doc") from sphinx.apidoc import main for module in modules: # Generate .rst files ready for autodoc module_dir = os.path.join(repo_dir, module) main(["-f", "-d", "1", "-o", apidoc_dir, module_dir]) def setup(app): app.connect('builder-inited', run_apidoc) fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/index.rst000066400000000000000000000007571345606466200245670ustar00rootroot00000000000000.. title:: dijitso documentation ======= dijitso ======= A Python module for distributed just-in-time shared library building. DIJITSO is part of the FEniCS Project. For more information, visit http://www.fenicsproject.org Documentation ============= .. toctree:: :titlesonly: :maxdepth: 1 installation manual API reference releases [FIXME: These links don't belong here, should go under API reference somehow.] * :ref:`genindex` * :ref:`modindex` fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/installation.rst000066400000000000000000000037651345606466200261630ustar00rootroot00000000000000.. title:: Installation ============ Installation ============ DIJITSO is normally installed as part of an installation of FEniCS. If you are using DIJITSO as part of the FEniCS software suite, it is recommended that you follow the `installation instructions for FEniCS `__. To install DIJITSO itself, read on below for a list of requirements and installation instructions. Requirements and dependencies ============================= DIJITSO requires Python version 2.7 or later and depends on the following Python packages: * NumPy These packages will be automatically installed as part of the installation of DIJITSO, if not already present on your system. Additionally, to run tests the following packages are needed * pytest * mpi4py (for running tests with mpi) Installation instructions ========================= To install DIJITSO, download the source code from the `DIJITSO Bitbucket repository `__, and run the following command: .. code-block:: console pip install . To install to a specific location, add the ``--prefix`` flag to the installation command: .. code-block:: console pip install --prefix= . Environment =========== Instant's behaviour depened on following environment variables: - ``DIJITSO_CACHE_DIR`` This option overrides the placement of the cache directory. By default the cache directory is placed in ``.cache/dijitso`` either below the home directory or below the prefix of the currently active virtualenv or conda environment if any. - ``DIJITSO_SYSTEM_CALL_METHOD`` Choose method for calling external programs (c++ compiler). Available values: - ``SUBPROCESS`` Uses pipes. OFED-fork safe on Python 3. Default. - ``OS_SYSTEM`` Uses temporary files. Probably OFED-fork safe. .. warning:: OFED-fork safe system call method might be required to avoid crashes on OFED-based (InfiniBand) clusters! fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/manual.rst000066400000000000000000000004771345606466200247340ustar00rootroot00000000000000.. title:: User manual =========== User manual =========== The commandline tool 'dijitso' is currently only documented on the commandline, run 'dijitso --help' for details and available subcommands. The python module dijitso is only used internally by ffc, and no manual has been written so far. See API reference. fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases.rst000066400000000000000000000003441345606466200252530ustar00rootroot00000000000000============= Release notes ============= .. toctree:: :maxdepth: 2 releases/next releases/v2019.1.0 releases/v2018.1.0 releases/v2017.1.0.post1 releases/v2017.1.0 releases/v2016.2.0 releases/v2016.1.0 fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/000077500000000000000000000000001345606466200245205ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/next.rst000066400000000000000000000010251345606466200262260ustar00rootroot00000000000000=========================== Changes in the next release =========================== Summary of changes ================== - No changes yet. .. note:: Developers should use this page to track and list changes during development. At the time of release, this page should be published (and renamed) to list the most important changes in the new release. Detailed changes ================ .. note:: At the time of release, make a verbatim copy of the ChangeLog here (and remove this note). fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2016.1.0.rst000066400000000000000000000005241345606466200263260ustar00rootroot00000000000000=========================== Changes in version 2016.1.0 =========================== dijitso 2016.1.0 was released on 2016-06-23. - This is the first version that covers all the immediate needs of the FEniCS Form Compiler (FFC) for just in time compilation of generated code using ctypes to import a simple generated factory function. fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2016.2.0.rst000066400000000000000000000007301345606466200263260ustar00rootroot00000000000000=========================== Changes in version 2016.2.0 =========================== dijitso 2016.2.0 was released on 2016-11-30. - Introduce commandline script 'dijitso' with various subcommands to interact with the cache - Improve extraction of source files to reproduce compilation failure during jit - Implement support for linking between jit modules - Add optional dependency on subprocess32 to handle fork safety on infiniband clusters - Remove instant dependency fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2017.1.0.post1.rst000066400000000000000000000002751345606466200273770ustar00rootroot00000000000000=========================== Changes in version 2017.1.0.post1 =========================== dijitso 2017.1.0.post1 was released on 2017-09-12. - Change PyPI package name to fenics-dijitso. fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2017.1.0.rst000066400000000000000000000002211345606466200263210ustar00rootroot00000000000000=========================== Changes in version 2017.1.0 =========================== dijitso 2017.1.0 was released on 2017-05-09. - Minor fixes fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2017.2.0.rst000066400000000000000000000004321345606466200263260ustar00rootroot00000000000000=========================== Changes in version 2017.2.0 =========================== dijitso 2017.1.0 was released on 2017-12-05. - Add support for linking external libraries - Add support for creating a loadable module with __import__ with "lib_loader" parameter (ctypes, module) fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2018.1.0.rst000066400000000000000000000002321345606466200263240ustar00rootroot00000000000000=========================== Changes in version 2018.1.0 =========================== dijitso 2018.1.0 was released on 2018-06-14. - Very minor cleanups. fenics-project-dijitso-c92dcb05ca82/doc/sphinx/source/releases/v2019.1.0.rst000066400000000000000000000002321345606466200263250ustar00rootroot00000000000000=========================== Changes in version 2019.1.0 =========================== dijitso 2019.1.0 was released on 2019-04-17. - Very minor cleanups. fenics-project-dijitso-c92dcb05ca82/setup.cfg000066400000000000000000000001471345606466200211620ustar00rootroot00000000000000[flake8] max-line-length=100 exclude=.git,__pycache__,doc/sphinx/source/conf.py,build,dist,__init__.py fenics-project-dijitso-c92dcb05ca82/setup.py000077500000000000000000000036031345606466200210560ustar00rootroot00000000000000# -*- coding: utf-8 -*- from setuptools import setup from os.path import join import sys module_name = "dijitso" if sys.version_info < (3, 5): print("Python 3.5 or higher required, please upgrade.") sys.exit(1) # Set version version = "2019.2.0.dev0" url = "https://bitbucket.org/fenics-project/%s/" % module_name tarball = None if 'dev' not in version: tarball = url + "downloads/%s-%s.tar.gz" % (module_name, version) script_names = ("dijitso",) entry_points = {'console_scripts': ['dijitso = dijitso.__main__:main']} scripts = [join("scripts", script) for script in script_names] man_files = [join("doc", "man", "man1", "%s.1.gz" % (script,)) for script in script_names] data_files = [(join("share", "man", "man1"), man_files)] CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: MacOS :: MacOS X Operating System :: Microsoft :: Windows Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Topic :: Scientific/Engineering :: Mathematics Topic :: Software Development :: Libraries :: Python Modules """ requires = ["numpy"] setup(name="fenics-dijitso", version=version, description="Distributed just-in-time building of shared libraries", author="Martin Sandve Alnæs", author_email="martinal@simula.no", url=url, download_url=tarball, classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], # scripts=scripts, # Using entry_points instead entry_points=entry_points, packages=["dijitso"], package_dir={'dijitso': 'dijitso'}, install_requires=requires, data_files=data_files ) fenics-project-dijitso-c92dcb05ca82/test/000077500000000000000000000000001345606466200203165ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/test/.coveragerc000066400000000000000000000000541345606466200224360ustar00rootroot00000000000000[html] directory=htmlcov${MPISIZE}${MYRANK} fenics-project-dijitso-c92dcb05ca82/test/clean.sh000077500000000000000000000001421345606466200217340ustar00rootroot00000000000000#!/bin/bash rm -rf report*.xml htmlcov* output.* *.pyc *~ *.dst .test_* .coverage .dijitso .cache fenics-project-dijitso-c92dcb05ca82/test/conftest.py000066400000000000000000000114071345606466200225200ustar00rootroot00000000000000#!/usr/bin/env py.test # -*- coding: utf-8 -*- import pytest import os import dijitso import ctypes @pytest.fixture() def comm(): try: from mpi4py import MPI c = MPI.COMM_WORLD except ImportError: pytest.skip("Need mpi4py to test with comms.") c = None return c _code_template_params = """\ /** Arguments used to generate this code: %(generator_params)s */ """ _code_template_defines = """\ // Based on https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define DLL_EXPORT extern "C" __attribute__ ((dllexport)) #else #define DLL_EXPORT extern "C" __declspec(dllexport) #endif #else #define DLL_EXPORT extern "C" __attribute__ ((visibility ("default"))) #endif """ _code_template_interface = """\ // This would be '#include ' class %(interfacename)s { public: virtual ~%(interfacename)s() {} virtual int get_test_value() const = 0; }; """ _code_template_class = """\ /// This would be the generated ufc::form code class %(classname)s: public %(interfacename)s { public: int get_test_value() const { return %(testvalue)s; } }; """ _code_template_factory = """\ /// Construct an object of class %(classname)s without any class interface wrapping DLL_EXPORT void * create_%(signature)s() { return new %(classname)s(); } """ _code_template_testhook = """\ #include "testinclude.h" DLL_EXPORT int get_test_value_%(testvalue)d(void * p) { %(interfacename)s * pp = static_cast<%(interfacename)s *>(p); int v = pp->get_test_value(); return v + TESTINCLUDE_MAGIC_VALUE; } """ def mygenerate(jitable, name, signature, generator_params): """.""" code_parts = dict( generator_params=str(generator_params), signature=signature, classname="class_%s" % (jitable,), interfacename="external_interface", testvalue=jitable, ) parts = [ _code_template_params % code_parts, _code_template_defines % code_parts, _code_template_interface % code_parts, _code_template_class % code_parts, _code_template_factory % code_parts, _code_template_testhook % code_parts, ] header = "// Dummy header" source = '\n'.join(parts) dependencies = () return header, source, dependencies _default_dijitso_cache_dir = os.path.join(os.path.dirname(__file__), ".dijitso") _testincludes = os.path.join(os.path.dirname(__file__), "testincludes") def _jit_integer(jitable, comm=None, buildon="node", dijitso_cache_dir=_default_dijitso_cache_dir): "A mock jit routine setup to exercise much of the library." # Setup params cache_params = dict( cache_dir=dijitso_cache_dir, src_storage="compress", ) build_params = dict( debug=True, include_dirs=(_testincludes,), ) generator_params = None params = dict( cache=cache_params, build=build_params, generator=generator_params, ) params = dijitso.validate_params(params) # Compute a name from dijitso.signatures import hashit name = "jit_integer_" + hashit(jitable) # Autodetect subcomms and role based on buildin option and # physical disk access of processes from dijitso.mpi import create_comms_and_role, send_binary, receive_binary from dijitso.system import make_dirs sync_dir = os.path.join(cache_params["cache_dir"], "sync") make_dirs(sync_dir) copy_comm, wait_comm, role = create_comms_and_role(comm, sync_dir, buildon) # Somewhat messy definitions of send/receive/wait... send = None receive = None wait = None if role == "builder": generate = mygenerate if copy_comm is not None: def send(lib_data): assert role == "builder" send_binary(copy_comm, lib_data) elif role == "receiver": generate = None assert copy_comm is not None def receive(): return receive_binary(copy_comm) elif role == "waiter": generate = None if wait_comm is not None: def wait(): wait_comm.barrier() # Jit it! lib, signature = dijitso.jit(jitable, name, params, generate, send, receive, wait) assert lib is not None assert isinstance(signature, str) # Extract the factory function we want from library factory = dijitso.extract_factory_function(lib, "create_" + signature) # ... and the test specific getter function get_test_value = getattr(lib, "get_test_value_%d" % jitable) get_test_value.argtypes = [ctypes.c_void_p] get_test_value.restype = ctypes.c_int # Return both library and factory return lib, factory, get_test_value @pytest.fixture() def jit_integer(): return _jit_integer fenics-project-dijitso-c92dcb05ca82/test/debug_mpi_tests.sh000077500000000000000000000003201345606466200240250ustar00rootroot00000000000000#!/usr/bin/env bash set -e exit : ${PYTHON:=python} while [ $? -eq 0 ] do for p in 8; do echo RUNNING WITH p=$p mpirun -n $p xterm -e gdb -ex r -ex q -args ${PYTHON} -B -m pytest -svl done done fenics-project-dijitso-c92dcb05ca82/test/mpipipe.sh000077500000000000000000000024211345606466200223170ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2015 Martin Alnæs # Copyright (C) 2015 Johannes Ring # # This file is part of DOLFIN. # # DOLFIN 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. # # DOLFIN 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 DOLFIN. If not, see . # This script redirects output from a command to output.MYRANK : ${PYTHON:=python} # See: http://docs.roguewave.com/threadspotter/2012.1/linux/manual_html/apas03.html if [ ! -z $OMPI_COMM_WORLD_RANK ]; then MYRANK=$OMPI_COMM_WORLD_RANK elif [ ! -z $PMI_RANK ]; then MYRANK=$PMI_RANK else MYRANK=`${PYTHON} -c "import dolfin;c=dolfin.mpi_comm_world();r=dolfin.MPI.rank(c);print(r);dolfin.MPI.barrier(c)"` fi OUT=output.$MYRANK echo My rank is $MYRANK, writing to $OUT if [ $MYRANK -eq 0 ]; then $@ | tee $OUT else $@ > $OUT fi fenics-project-dijitso-c92dcb05ca82/test/mpipytest.sh000077500000000000000000000026261345606466200227210ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2015 Martin Alnæs # Copyright (C) 2015 Johannes Ring # # This file is part of DOLFIN. # # DOLFIN 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. # # DOLFIN 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 DOLFIN. If not, see . # This script redirects output from a command to output.MYRANK : ${PYTHON:=python3} # See: http://docs.roguewave.com/threadspotter/2012.1/linux/manual_html/apas03.html if [ ! -z $OMPI_COMM_WORLD_RANK ]; then export MYRANK=$OMPI_COMM_WORLD_RANK elif [ ! -z $PMI_RANK ]; then export MYRANK=$PMI_RANK else export MYRANK=`${PYTHON} -c "import dolfin;c=dolfin.mpi_comm_world();r=dolfin.MPI.rank(c);print(r);dolfin.MPI.barrier(c)"` fi CMD=${PYTHON}' -B -m pytest -svl --cov-report html --cov=dijitso --junitxml report$MYRANK.xml' echo $CMD OUT=output.$MYRANK echo My rank is $MYRANK, writing to $OUT if [ $MYRANK -eq 0 ]; then $CMD | tee $OUT else $CMD > $OUT fi fenics-project-dijitso-c92dcb05ca82/test/pytest.ini000066400000000000000000000000321345606466200223420ustar00rootroot00000000000000[pytest] minversion = 2.4 fenics-project-dijitso-c92dcb05ca82/test/runtests.sh000077500000000000000000000004761345606466200225530ustar00rootroot00000000000000#!/usr/bin/env bash set -e exit : ${PYTHON:=python} echo Running tests in serial: export MYRANK= export MPISIZE= ${PYTHON} -B -m pytest -svl --cov-report html --cov=dijitso --junitxml report$MYRANK.xml for p in 1 4 8 16; do echo Running tests with mpi, n=$p export MPISIZE=$p mpirun -n $p ./mpipytest.sh done fenics-project-dijitso-c92dcb05ca82/test/test_mpi_dijitso.py000066400000000000000000000062411345606466200242440ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . import pytest import shutil import os @pytest.fixture(params=["root", "node", "process"]) def buildon(request): return request.param def test_mpi_jit_strategies(comm, jit_integer, buildon): """Jit a simple code generated by inserting a simple integer. Covers (if the cache is initially empty): - memory cache miss - memory cache hit - compiling - loading - factory function extraction """ # Note: this test was initially copied from # test_core_jit_framework in test_dijitso.py print(buildon, comm.rank) if buildon == "process": # One dir per process dijitso_cache_dir = ".test_dijitso_%d" % (comm.rank,) elif buildon == "node": # Less dirs than processes (gives some waiting for size > 2) dijitso_cache_dir = ".test_dijitso_%d" % (comm.rank % 2,) elif buildon == "root": # Less dirs than processes (gives a combination of copying # (size>1) and waiting (size>2)) dijitso_cache_dir = ".test_dijitso_%d" % (comm.rank % 2,) dijitso_cache_dir = os.path.join(os.path.dirname(__file__), dijitso_cache_dir) shutil.rmtree(dijitso_cache_dir, ignore_errors=True) comm.barrier() # This magic value is defined in testincludes/testinclude.h, # so this is used to confirm that includes work correctly. # Also the fact that the #include "testinclude.h" above compiles. magic_value = 42 stored = {} for repeat in range(2): for jitable in (234, 567): # Note different values than serial test # Each integer produces different code lib, factory, gettr = jit_integer(jitable, comm=comm, buildon=buildon, dijitso_cache_dir=dijitso_cache_dir) # Inspect values for testing assert jitable + magic_value == gettr(factory()) # Memory cache test if repeat == 0: # Make a record of this lib stored[jitable] = lib else: # Check that we fetched the lib from the memory cache assert lib is stored[jitable] # If all went well we clean up, if assertions triggered # above we allow this cleanup to not happen shutil.rmtree(dijitso_cache_dir, ignore_errors=True) comm.barrier() # TODO: Cover various failure situations with tests fenics-project-dijitso-c92dcb05ca82/test/test_mpi_dummy.py000066400000000000000000000014461345606466200237340ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . def test_mpi_dummy(comm): assert comm.rank < comm.size fenics-project-dijitso-c92dcb05ca82/test/test_role_assignment.py000066400000000000000000000045661345606466200251330ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . import pytest from dijitso.system import make_dirs from dijitso.mpi import create_comms_and_role @pytest.fixture() def lib_dir0(comm): # Fake some common and some shared libdirs path = ".test_roles_%d" % (comm.rank,) make_dirs(path) return path @pytest.fixture() def lib_dir2(comm): # Fake some common and some shared libdirs path = ".test_roles_%d_of_2" % (comm.rank % 2,) make_dirs(path) return path def test_role_root(comm, lib_dir2): buildon = "root" copy_comm, wait_comm, role = create_comms_and_role(comm, lib_dir2, buildon) if comm.rank == 0: expected_role = "builder" elif wait_comm.rank == 0: expected_role = "receiver" else: expected_role = "waiter" assert role == expected_role assert copy_comm is not None assert wait_comm is not None if role != "waiter": assert copy_comm.size == min(comm.size, 2) assert (comm.size // 2) <= wait_comm.size <= (comm.size // 2 + 1) def test_role_node(comm, lib_dir2): buildon = "node" copy_comm, wait_comm, role = create_comms_and_role(comm, lib_dir2, buildon) if comm.rank in (0, 1): expected_role = "builder" else: expected_role = "waiter" assert role == expected_role assert copy_comm is None assert wait_comm is not None assert (comm.size // 2) <= wait_comm.size <= (comm.size // 2 + 1) def test_role_process(comm, lib_dir0): buildon = "process" copy_comm, wait_comm, role = create_comms_and_role(comm, lib_dir0, buildon) expected_role = "builder" assert role == expected_role assert copy_comm is None assert wait_comm is None fenics-project-dijitso-c92dcb05ca82/test/test_serial_dijitso.py000066400000000000000000000035561345606466200247440ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . def test_core_jit_framework(jit_integer): """Jit a simple code generated by inserting a simple integer. Covers (if the cache is initially empty): - memory cache miss - memory cache hit - compiling - loading - factory function extraction """ # This magic value is defined in testincludes/testinclude.h, so # this is used to confirm that includes work correctly. Also the # fact that the #include "testinclude.h" above compiles. magic_value = 42 stored = {} for repeat in range(2): for jitable in (123, 456): # Each integer produces different code lib, factory, get_test_value = jit_integer(jitable) # Inspect values for testing assert jitable + magic_value == get_test_value(factory()) # Memory cache test if repeat == 0: # Make a record of this lib stored[jitable] = lib else: # Check that we fetched the lib from the memory cache assert lib is stored[jitable] # TODO: Cover various failure situations with tests fenics-project-dijitso-c92dcb05ca82/test/test_system_utils.py000066400000000000000000000035371345606466200245030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Martin Sandve Alnæs # # This file is part of DIJITSO. # # DIJITSO 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. # # DIJITSO 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 DIJITSO. If not, see . import io import os import uuid from dijitso.system import lockfree_move_file, make_dirs def test_get_status_output(): pass # FIXME def test_lockfree_move_file(): # Running this loop in multiple processes with mpi is perhaps a # decent test? # Fixed directory independent of mpi rank tmpdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".test_lockfree_move_file") make_dirs(tmpdir) # source is different for each process and loop iteration n = 3 u = uuid.uuid4().int srcs = [os.path.join(tmpdir, "test_lockfree_move_file-%d.src-%d" % (u, i)) for i in range(n)] # fixed destination dst = os.path.join(tmpdir, "test_lockfree_move_file.dst") # try_delete_file(dst) # can't do this when testing with mpi! for src in srcs: with io.open(src, "w", encoding="utf-8") as f: f.write("dummy") assert os.path.exists(src) lockfree_move_file(src, dst) assert os.path.exists(dst) assert not os.path.exists(src) with io.open(dst, encoding="utf-8") as f: dummy = f.read() assert dummy == "dummy" fenics-project-dijitso-c92dcb05ca82/test/testincludes/000077500000000000000000000000001345606466200230245ustar00rootroot00000000000000fenics-project-dijitso-c92dcb05ca82/test/testincludes/testinclude.h000066400000000000000000000000431345606466200255150ustar00rootroot00000000000000#define TESTINCLUDE_MAGIC_VALUE 42