pax_global_header00006660000000000000000000000064124227341200014507gustar00rootroot0000000000000052 comment=512f807e23188d94404e69338abd346c1c0ba80c versuchung-1.1/000077500000000000000000000000001242273412000135415ustar00rootroot00000000000000versuchung-1.1/.be/000077500000000000000000000000001242273412000142055ustar00rootroot00000000000000versuchung-1.1/.be/bugs/000077500000000000000000000000001242273412000151455ustar00rootroot00000000000000versuchung-1.1/.be/bugs/48f30ff6-771b-42a9-a546-0f8b777b7ed0/000077500000000000000000000000001242273412000217475ustar00rootroot00000000000000versuchung-1.1/.be/bugs/48f30ff6-771b-42a9-a546-0f8b777b7ed0/values000066400000000000000000000003341242273412000231710ustar00rootroot00000000000000 creator=Christian Dietrich severity=minor status=closed summary=Add symlink to newest experiment of type time=Sat, 21 Jan 2012 15:11:31 +0000 versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/000077500000000000000000000000001242273412000221215ustar00rootroot00000000000000versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/comments/000077500000000000000000000000001242273412000237465ustar00rootroot00000000000000000077500000000000000000000000001242273412000303555ustar00rootroot00000000000000versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/comments/5d638943-ce3c-4778-85e4-6bfb791a2959body000066400000000000000000000000651242273412000312360ustar00rootroot00000000000000versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/comments/5d638943-ce3c-4778-85e4-6bfb791a2959import multiprocessing multiprocessing.cpu_count() values000066400000000000000000000002271242273412000316000ustar00rootroot00000000000000versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/comments/5d638943-ce3c-4778-85e4-6bfb791a2959 Content-type=text/plain Date=Sun, 22 Jan 2012 11:47:38 +0000 From=Christian Dietrich versuchung-1.1/.be/bugs/5778e36b-4de8-4b39-abf9-d8b12e7e9f31/values000066400000000000000000000003431242273412000233430ustar00rootroot00000000000000 creator=Christian Dietrich severity=minor status=closed summary=More metainformation in metadata: CPU Count etc time=Sat, 21 Jan 2012 15:00:06 +0000 versuchung-1.1/.be/bugs/6b2000bb-a458-4f75-9e0e-7b0728dd3064/000077500000000000000000000000001242273412000216405ustar00rootroot00000000000000versuchung-1.1/.be/bugs/6b2000bb-a458-4f75-9e0e-7b0728dd3064/values000066400000000000000000000003101242273412000230540ustar00rootroot00000000000000 creator=Christian Dietrich severity=minor status=closed summary=Factor out event-log time=Sat, 21 Jan 2012 15:16:06 +0000 versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/000077500000000000000000000000001242273412000216665ustar00rootroot00000000000000versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/comments/000077500000000000000000000000001242273412000235135ustar00rootroot00000000000000000077500000000000000000000000001242273412000303205ustar00rootroot00000000000000versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/comments/50c370d2-18fa-4e9c-b7e7-7af8c73577d5body000066400000000000000000000001651242273412000312020ustar00rootroot00000000000000versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/comments/50c370d2-18fa-4e9c-b7e7-7af8c73577d5I want to do something like: inputs = { Dict({'x86': InferenceStats("fooo"), 's390': InferenceStats("barfoo")})} values000066400000000000000000000002271242273412000315430ustar00rootroot00000000000000versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/comments/50c370d2-18fa-4e9c-b7e7-7af8c73577d5 Content-type=text/plain Date=Sat, 21 Jan 2012 10:22:33 +0000 From=Christian Dietrich versuchung-1.1/.be/bugs/7451837d-d39b-49bc-9960-c9ad0da49305/values000066400000000000000000000003041242273412000231050ustar00rootroot00000000000000 creator=Christian Dietrich severity=minor status=open summary=New Datatype: dict time=Sat, 21 Jan 2012 10:22:01 +0000 versuchung-1.1/.be/settings000066400000000000000000000000231242273412000157630ustar00rootroot00000000000000 rcs_name=git versuchung-1.1/.be/version000066400000000000000000000000311242273412000156070ustar00rootroot00000000000000Bugs Everywhere Tree 1 0 versuchung-1.1/.gitignore000066400000000000000000000000431242273412000155260ustar00rootroot00000000000000build/ doc/_build *.pyc *.swp *.swoversuchung-1.1/COPYING000066400000000000000000001045131242273412000146000ustar00rootroot00000000000000 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 . versuchung-1.1/README.md000066400000000000000000000025431242273412000150240ustar00rootroot00000000000000versuchung - a toolbox for experiments ====================================== In some fields of science it is common practice to not publish any experiment descriptions or the raw measurement results of the experiment. This is not only opposed to the idea of science, where results should be reproducible to verify them by a larger audience, but also harmful for other researchers, who want to extend the results in the field. This lack of experiment descriptions and raw data is not necessary a result of mean intention by the original researcher, more a lack of tools for documenting and specifying experiements and the raw data analysis. This is especially true for some fields of computer science. But as these people are experts in using formal descriptions (also known as programming languages) it is surprising that there is no easy-to-use tool for specifying experiments and analyses. Versuchung tries to fill this gap, by providing such a tool, where experiments can be specified with proper input and output parameter declarations, versioned result sets and the possibility to process the result sets further. Documentation ============= For the documentation, please refer to https://vamos.informatik.uni-erlangen.de/versuchung-doc/ Getting the latest version ========================== versuchung is hosted at github: https://github.com/stettberger/versuchung versuchung-1.1/doc/000077500000000000000000000000001242273412000143065ustar00rootroot00000000000000versuchung-1.1/doc/Makefile000066400000000000000000000110011242273412000157370ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' 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 " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @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 " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." 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." 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/versuchung.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/versuchung.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/versuchung" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/versuchung" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 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)." 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." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." 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." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." versuchung-1.1/doc/__init__.py000066400000000000000000000000001242273412000164050ustar00rootroot00000000000000versuchung-1.1/doc/_static/000077500000000000000000000000001242273412000157345ustar00rootroot00000000000000versuchung-1.1/doc/_static/.dir000066400000000000000000000000001242273412000165010ustar00rootroot00000000000000versuchung-1.1/doc/conf.py000066400000000000000000000164301242273412000156110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # versuchung documentation build configuration file, created by # sphinx-quickstart on Fri Jan 13 21:24:21 2012. # # 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. import sys, os from subprocess import * # 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. sys.path.insert(0, os.path.abspath('../src')) # -- 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.todo', 'sphinx.ext.coverage'] try: import sphinx.ext.viewcode extensions.append("sphinx.ext.viewcode") except: print "WARNING: no sphinx.ext.viewcode installed" # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. 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'versuchung' copyright = u'2012-2014, Christian Dietrich' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. p = Popen("git describe --always", stdout=PIPE, stderr=STDOUT, shell=True) (stdout, _) = p.communicate() if p.returncode == 0 and len(stdout) > 0: version = stdout.rstrip() else: version = "0.1" # The full version, including alpha/beta/rc tags. release = version + '-0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #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. exclude_patterns = ['_build'] # 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 = [] # -- 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. If None, it defaults to # " v documentation". #html_title = None # 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 (within the static path) to use as 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'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # 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 # Output file base name for HTML help builder. htmlhelp_basename = 'versuchungdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'versuchung.tex', u'versuchung Documentation', u'Christian Dietrich', '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 # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # 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 = [ ('index', 'versuchung', u'versuchung Documentation', [u'Christian Dietrich'], 1) ] versuchung-1.1/doc/experiment/000077500000000000000000000000001242273412000164665ustar00rootroot00000000000000versuchung-1.1/doc/experiment/index.rst000066400000000000000000000005531242273412000203320ustar00rootroot00000000000000Defining a Experiment ********************* As every experiment *must* inherit from the ``versuchung.experiment.Experiment`` class their attributes and methods are absolutly basic to versuchung. .. autoclass:: versuchung.experiment.Experiment :members: __init__, version, title, name, metadata, i, inputs, o, outputs, filter_metadata, run, execute, __call__ versuchung-1.1/doc/index.rst000066400000000000000000000027731242273412000161600ustar00rootroot00000000000000.. versuchung documentation master file, created by sphinx-quickstart on Fri Jan 13 21:24:21 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Versuchung - a toolbox for experiments ====================================== In some fields of science it is common practice to **not** publish any experiment descriptions or the raw measurement results of the experiment. This is not only opposed to the idea of science, where results should be reproducible to verify them by a larger audience, but also harmful for other researchers, who want to extend the results in the field. This lack of experiment descriptions and raw data is not necessary a result of mean intention by the original researcher, more a lack of tools for documenting and specifying experiements and the raw data analysis. This is especially true for some fields of computer science. But as these people are experts in using formal descriptions (also known as *programming languages*) it is surprising that there is no easy-to-use tool for specifying experiments and analyses. Versuchung tries to fill this gap, by providing such a tool, where experiments can be specified with proper input and output parameter declarations, versioned result sets and the possibility to process the result sets further. Contents: .. toctree:: :maxdepth: 2 intro experiment/index types/index Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` versuchung-1.1/doc/intro.rst000066400000000000000000000077721242273412000162100ustar00rootroot00000000000000Quick Introduction ****************** As a quick start a simple experiment with input and output parameters is show:: #!/usr/bin/python from versuchung.experiment import Experiment from versuchung.types import String from versuchung.files import File class SimpleExperiment(Experiment): inputs = {"input_key": String("default key"), "input_value": String("default value")} outputs = {"output_file": File("output")} def run(self): # Combine the input parameters content = self.inputs.input_key.value \ + ": " + self.inputs.input_value.value # write the result to the output file self.outputs.output_file.value = content + "\n" if __name__ == "__main__": import sys experiment = SimpleExperiment() dirname = experiment(sys.argv) print dirname This experiment is put in a single python script file. It is a complete experiment and a runnable python script with a command line parser to override the default experiment input parameters. Every experiment inherits from the :class:`~versuchung.experiment.Experiment` class to gain the basic structure for parameter handling and running the experiment. After that the member variable :attr:`~versuchung.experiment.Experiment.inputs` defines a :class:`dict` of the input parameters. In this case two such input parameters are defined ``"input_key"`` and ``"input_value"``, which are both of type :class:`~versuchung.types.String` and have a specified default value. This default value is used if no argument is given on the command line. The attribute :attr:`~versuchung.experiment.Experiment.outputs` defines the output parameter ``"output_file"`` which is of type :class:`~versuchung.files.File` with the filename ``"output"``. So in the experiment output there will be a file called *output*. The :meth:`~versuchung.experiment.Experiment.run` method is the heart of every experiment. It is called when all input parameters are gathered and the experiment environment is set up. In this ``SimpleExperiment`` the input parameters are simply concatenated and written to the output file. This ``SimpleExperiment`` can be instantiated without arguments. The resulting object is called with the command line parameters to enable a command line interface. Calling ``python experiment.py --help`` gives:: Usage: experiment.py Options: -h, --help show this help message and exit -d BASE_DIR, --base-dir=BASE_DIR Directory which is used for storing the experiment data -l, --list list all experiment results -v, --verbose increase verbosity (specify multiple times for more) --input_key=INPUT_KEY (default: default key) --input_value=INPUT_VALUE (default: default value) As you can see the two input parameters can be overwritten on the command line. The experiment can be executed by ``python experiment.py`` and print on the console:: SimpleExperiment-aeb298601cdc582b1b0d8260195f6cfd This is the versioned experiment result set. The hash at the end is calculated from the metadata of the experiment (e.g. input parameter values and the experiment version). In the current directory there was a directory created with this name where the results are located. To examine the experiment results and their metadata ``python experiment.py -l`` can be called:: +SimpleExperiment-aeb298601cdc582b1b0d8260195f6cfd | {'date': '2012-01-14 09:46:13.445703', | 'experiment-name': 'SimpleExperiment', | 'experiment-version': 1, | 'input_key': 'default key', | 'input_value': 'default value'} As you can see there is one result set in the current directory. All key parameters for the experiment are stored within the ``metadata`` file in the result directory. The ``output`` file in this result directory contains:: default key: default value versuchung-1.1/doc/types/000077500000000000000000000000001242273412000154525ustar00rootroot00000000000000versuchung-1.1/doc/types/archives.rst000066400000000000000000000006131242273412000200100ustar00rootroot00000000000000Archives and Version Control Systems ************************************ If you have your programs in a git archive, you can use :class:`~versuchung.archives.GitArchive` as input parameter and build the software every time from scratch in order to have a clean enviroment for the experiment. Similar you can use a tar achive for this purpose. .. automodule:: versuchung.archives :members: versuchung-1.1/doc/types/basic_types.rst000066400000000000000000000002221242273412000205050ustar00rootroot00000000000000Basic Parameter Types ********************* .. autoclass:: versuchung.types.String :members: .. autoclass:: versuchung.types.List :members: versuchung-1.1/doc/types/csv.rst000066400000000000000000000003211242273412000167730ustar00rootroot00000000000000CSV Output ********** For easy importing into spreadsheet applications, the versuchung package offers means to export data to CSV. .. autoclass:: versuchung.files.CSV_File :members: path,value,flush,append versuchung-1.1/doc/types/database.rst000066400000000000000000000053501242273412000177530ustar00rootroot00000000000000Database Output *************** Similar to the :doc:`tex`, you can use a real relational database as a backend to hold your data. Databases and tables within those databases can be used output, as well as input parameters. There are different helpers that make it easy to insert data into those databases. When data is inserted into a database the data strictly connected with the run experiment. This makes it at all points clear, where data comes from and where it should go. Please be aware, that this database interface is very very simple. If you need some more sophisticated stuff, please use a real database abstraction layer (e.g. with an object relation manager) like SQLAlchemy. The usage of the database package is straightforward. The usage of a database table as an output is shown as an example:: class SimpleExperiment(Experiment): outputs = {'table1': TableDict(), "table2": Table([("foo", "integer")], db = Database(path="foobar.db"))} def run(self): self.table1["key1"] = "value1" self.table1["bar"] = "foo" self.table2.insert( foo = 23 ) self.table2.insert( {"foo": 23} ) In this example two tables and two sqlite databases are created in the output directory. The first is where table1 is located, it has the implicit default name "sqlite3.db". The contents of the database is: metadata table +--------------------------------------------+--------------------------+ | experiment (text) | metadata (text) | +============================================+==========================+ | SimpleExperiment-db3ec040e20dfc657da... | {'experiment-version': 1,| +--------------------------------------------+--------------------------+ SimpleExperiment__table1 +--------------------------------------------+-------------+----------------+ | experiment (text) | key (text) | value (text) | +============================================+=============+================+ | SimpleExperiment-db3ec040e20dfc657da... | key1 | value1 | +--------------------------------------------+-------------+----------------+ | SimpleExperiment-db3ec040e20dfc657da... | bar | foo | +--------------------------------------------+-------------+----------------+ The ``foobar.db`` is constructed similar. But the SimpleExperiment__table2 there has only one column of type integer. If you have many sqlite files from different experiments. They can easily be merged by using the merge tool:: $ python -m versuchung.database target.db source1.db source2.db Additionally to SQLite3 databases, also a MySQL database can be used. But this feature is not very well tested yet. .. automodule:: versuchung.database :members: versuchung-1.1/doc/types/filesystem.rst000066400000000000000000000003361242273412000203720ustar00rootroot00000000000000Filesystem parameters ********************* .. autoclass:: versuchung.files.File :members: path,flush,copy_contents,value,write .. autoclass:: versuchung.files.Directory :members: path,value,new_file, mirror_directory versuchung-1.1/doc/types/index.rst000066400000000000000000000010401242273412000173060ustar00rootroot00000000000000Experiment Parameters ********************* The most part of versuchung are classes which can be used either as input, as output parameters or as both. They are used for defining strict experiment parameters and determine the experiment results. They are used in :attr:`~versuchung.experiment.Experiment.inputs` and :attr:`~versuchung.experiment.Experiment.outputs` attributes of a :class:`~versuchung.experiment.Experiment`. .. toctree:: :maxdepth: 2 basic_types filesystem csv tex database archives search tools versuchung-1.1/doc/types/search.rst000066400000000000000000000031371242273412000174550ustar00rootroot00000000000000Search Result Sets as Input Parameters ************************************** In large experiment setups it is challenging to keep track of all result sets that are floating around. This is especially true if you want to select result sets according to the metadata as input parameters for other experiments. Imagine you have a set of "InferenceResults", which have the key "arch" in their metadata. You want to select an instance of these result sets as an input parameter. This is possible when using functions as input parameters. If an input parameter is a function, it will be called with the experiment instance as first argument, after all other parameters are parsed (from the command line):: from versuchung.search import * inputs = { "arch": String("x86"), # Here come computed arguments "inference_s390": lambda self:\ search_experiment(InferenceResults, search_path_go_up_till(self.base_directory, "data"), {'arch': "s390"}), "inference": lambda self:\ search_experiment(InferenceResults, search_path_go_up_till(self.base_directory, "data"), {'arch': self.arch.value}), } Here two inputs are computed. inference_s390 is calulated dynamically, but isn't dependent on any other input parameter. The result set is a directory, which is an upper directory to the current one, and is named "data". The inference parameter is similar, but dependent on the "arch" input parameter. .. automodule:: versuchung.search :members: versuchung-1.1/doc/types/tex.rst000066400000000000000000000005521242273412000170060ustar00rootroot00000000000000TeX Output ********** When you are writing a paper or some other text, which uses data that is produced by a experiment, it is very useful to have direct access from your TeX sources to your experiment results. This is especially useful if you want to reproduce your paper with a different version of your programs. .. automodule:: versuchung.tex :members: versuchung-1.1/doc/types/tools.rst000066400000000000000000000003441242273412000173450ustar00rootroot00000000000000Various Handy Tools for Experimentation *************************************** .. automodule:: versuchung.execute :members: shell, shell_failok, CommandFailed, MachineMonitor .. automodule:: versuchung.events :members: versuchung-1.1/setup.py000077500000000000000000000024401242273412000152560ustar00rootroot00000000000000#!/usr/bin/env python from distutils.core import setup from distutils.cmd import Command from distutils.spawn import spawn try: from sphinx.setup_command import BuildDoc cmdclass = {'doc': BuildDoc} except: print "No Sphinx installed (python-sphinx) so no documentation can be build" cmdclass = {} class TestCommand(Command): user_options = [] def run(self): spawn(["make", "-C", "tests"], verbose = 1) def initialize_options(self): pass def finalize_options(self): pass cmdclass["test"] = TestCommand version_info = { 'name': 'versuchung', 'version': '1.1', 'description': 'A toolbox for experiments', 'author': 'Christian Dietrich', 'author_email': 'stettberger@dokucode.de', 'url': 'http://github.de/stettberger/versuchung', 'license': 'GPLv3', 'classifiers': [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.4' ], } setup(packages = ["versuchung"], package_dir = {'versuchung': 'src/versuchung'}, cmdclass = cmdclass, **version_info ) versuchung-1.1/src/000077500000000000000000000000001242273412000143305ustar00rootroot00000000000000versuchung-1.1/src/versuchung/000077500000000000000000000000001242273412000165215ustar00rootroot00000000000000versuchung-1.1/src/versuchung/__init__.py000066400000000000000000000001701242273412000206300ustar00rootroot00000000000000__all__ = ["archives", "experiment", "files", "tex", "types", "tools", "events", "search", 'database'] from . import * versuchung-1.1/src/versuchung/archives.py000066400000000000000000000250541242273412000207050ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from versuchung.types import Type, InputParameter from versuchung.files import Directory, Directory_op_with, File from versuchung.execute import shell import logging import os import sys class TarArchive(Type, InputParameter, Directory_op_with): """Can be used as: **input parameter** The archive will be extracted to a temporary directory. It will be removed after the experiment is over. ``clone_url`` can either be a :class:`string` or any object that has a ``.path`` attribute (like e.g. :class:`~versuchung.filesystems.File`). Of course the referenced file must be a single file. This parameter can be used as argument to the with keyword, to change to the temporary directory:: with self.inputs.tar_archive as path: # Here we have path == os.path.abspath(os.curdir) # Do something in the extracted copy print path """ def __init__(self, filename = None): """The default_filename is either a string to a file. Or a object with a path attribute (e.g. a :class:`~versuchung.files.File`)""" Type.__init__(self) InputParameter.__init__(self) Directory_op_with.__init__(self) self.__filename = filename self.__value = None def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__filename) def inp_extract_cmdline_parser(self, opts, args): self.__filename = self.inp_parser_extract(opts, None) def before_experiment_run(self, parameter_type): if parameter_type == "input" and "path" in dir(self.__filename): self.subobjects["filename"] = self.__filename Type.before_experiment_run(self, parameter_type) self.__filename = self.__filename.path else: Type.before_experiment_run(self, parameter_type) self.__filename = os.path.abspath(self.__filename) def inp_metadata(self): return {self.name: self.__filename} def __setup_value(self): if "path" in dir(self.__filename): self.subobjects["filename"] = self.__filename self.__filename = self.__filename.path self.__filename = os.path.abspath(self.__filename) fn = self.__filename extract_mode = "" if "tar.gz" in fn or "tgz" in fn: extract_mode = "x" if "tar.bz2" in fn or "bzip2" in fn: extract_mode = "j" with self.tmp_directory as d: try: os.mkdir(self.name) except OSError: # ignore errors if the directory should already exist for some reason pass with Directory(self.name) as d2: dirname = os.path.abspath(".") (out, ret) = shell("tar %szvf %s", extract_mode, fn) if ret != 0: raise RuntimeError("Extracting of %s failed" % fn) cd = None for line in out: if (cd == None or len(line) < len(cd)) and line.endswith("/"): cd = line if cd and all([x.startswith(cd) for x in out]): dirname = cd return Directory(os.path.abspath(dirname)) @property def value(self): """Return a :class:`versuchung.files.Directory` instance to the extracted tar archive. If it contains only one directory the instance will point there. Otherwise it will point to a directory containing the contents of the archive""" if not self.__value: self.__value = self.__setup_value() return self.__value @property def path(self): """Return the string to the extract directory (same as .value.path)""" return self.value.path class GitArchive(InputParameter, Type, Directory_op_with): """Can be used as: **input parameter** The git repository given in ``clone_url`` will be cloned to a temporary directory. It will be removed after the experiment is over. If ``shallow == True`` Only the files and not the .git is copied (cloned). This is especially useful for large git repositories like the Linux kernel tree. ``clone_url`` can either be a :class:`string` or any object that has a ``.path`` attribute (like e.g. :class:`TarArchive`). Of course the refenced path must be a directory. This parameter can be used as argument to the with keyword, to change to the temporary directory:: with self.inputs.git_archive as path: # Here we have path == os.path.abspath(os.curdir) # Do something in the extracted copy print path """ def __init__(self, clone_url = None, ref = "refs/heads/master", shallow = False): """clone_url: where to the git archive from This might either be a string or a object with a path attribute ref: which git reference to checkout shallow: do a shallow copy (using git-archive). The git archive will be cloned to self.name (which is the key in the input parameters dict)""" Type.__init__(self) InputParameter.__init__(self) Directory_op_with.__init__(self) self.__clone_url = clone_url self.__ref = ref self.__shallow = shallow self.__value = None self.__hash = None def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, "clone-url", self.__clone_url) self.inp_parser_add(parser, "ref", self.__ref) def inp_extract_cmdline_parser(self, opts, args): self.__clone_url = self.inp_parser_extract(opts, "clone-url") self.__ref = self.inp_parser_extract(opts, "ref") def before_experiment_run(self, parameter_type): if parameter_type == "input" and "path" in dir(self.__clone_url): self.subobjects["clone-url"] = self.__clone_url Type.before_experiment_run(self, parameter_type) self.__clone_url = self.__clone_url.path else: Type.before_experiment_run(self, parameter_type) def checkout_hash(self): """Return the hash of the HEAD commit hash as string""" if not self.__hash: cmd = "git ls-remote %s %s" % (self.__clone_url, self.__ref) (lines, ret) = shell(cmd) if ret != 0 or lines == 0: print "\n".join(lines) sys.exit(-1) self.__hash = lines[0].split("\t")[0] if self.__hash == "": self.__hash = self.__ref return self.__hash def checkout_ref(self): """Return git ref which was checked out""" return self.__ref def checkout_url(self): """Return git url which was checked out""" return self.__clone_url def inp_metadata(self): return {self.name + "-clone-url": str(self.__clone_url), self.name + "-ref": self.__ref, self.name + "-hash": self.checkout_hash()} def __setup_value(self): if "path" in dir(self.__clone_url): self.subobjects["clone-url"] = self.__clone_url self.__clone_url = self.__clone_url.path logging.info("copying git archive %s", self.__clone_url) with self.tmp_directory as d: os.mkdir(self.name) if self.__shallow: cmd = "cd '%s' && git archive --format=tar --remote=%s %s | tar x" args = (self.name, self.__clone_url, self.__ref) else: cmd = "git clone %s %s" args = (self.__clone_url, self.name) (lines, ret) = shell(cmd, *args) if ret != 0: print "\n".join(lines) sys.exit(-1) if not self.__shallow: cmd = "cd %s && git gc && git fetch %s %s && git checkout FETCH_HEAD" args = (self.name, self.__clone_url, self.__ref) (lines, ret) = shell(cmd, *args) if ret != 0: print "\n".join(lines) sys.exit(-1) return Directory(os.path.abspath(self.name)) @property def value(self): """Return a :class:`versuchung.files.Directory` instance to the cloned git directory""" if not self.__value: self.__value = self.__setup_value() return self.__value @property def path(self): """Return the string to the extract directory (same as .value.path)""" return self.value.path class GzipFile(File): def original_filename(self): return self.__original_filename @property def path(self): path = File.path.fget(self) if self.parameter_type == "input" and not os.path.exists(path): shell("gunzip < %s > %s", self.__original_filename, path) return path @property def value(self): path = File.path.fget(self) if self.parameter_type == "input" and not os.path.exists(path): shell("gunzip < %s > %s", self.__original_filename, path) return File.value.fget(self) @value.setter def value(self, value): File.value.fset(self, value) def before_experiment_run(self, parameter_type): self.parameter_type = parameter_type if parameter_type == "input": self.__original_filename = File.path.fget(self) self.subobjects["filename"] = File(self.__original_filename) filename = self.name + "_" + os.path.basename(self.path.rstrip(".gz")) self.set_path(self.tmp_directory.path, filename) File.before_experiment_run(self, parameter_type) def after_experiment_run(self, parameter_type): File.after_experiment_run(self, parameter_type) if parameter_type == "output": shell("gzip -c %s > %s.1", self.path, self.path) shell("mv %s.1 %s", self.path, self.path) versuchung-1.1/src/versuchung/database.py000066400000000000000000000542711242273412000206500ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from versuchung.types import Type, InputParameter, OutputParameter import logging import sqlite3 import os, stat # Import mysql handler try: import MySQLdb import _mysql_exceptions except: pass class Database_Abstract: def values(self, table_name, filter_expr = "where experiment = ?", *args): """Get the contets of a table in the database. It takes addtional to the table name, a filter expression and applies all args to the excute command. An example:: (cols, rows) = database.values("metadata", "") for row in rows: print cols, rows """ cur = self.handle.cursor() cur.execute('select * from ' + table_name + filter_expr, args) cols = [x[0] for x in cur.description] def generator(): while True: row = cur.fetchone() if row == None: cur.close() return yield row index = cols.index("experiment") return cols, generator() class Database_MySQL(InputParameter, OutputParameter, Type, Database_Abstract): """Can be used as **input parameter** and **output parameter** A database backend class for a MySQL database.""" def __init__(self, database = None, host = "localhost", user = None, password = None): InputParameter.__init__(self) OutputParameter.__init__(self) Type.__init__(self) assert database != None, "Please give a database name to database connection" self.__database_name = database self.__database_host = os.environ.get("MYSQL_HOST", None) or host self.__database_user = os.environ.get("MYSQL_USER", None) or user self.__database_password = os.environ.get("MYSQL_PASSWORD", None) or password self.__database_connection = None def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, "database", self.__database_name) self.inp_parser_add(parser, "host", self.__database_host) self.inp_parser_add(parser, "user", self.__database_user) self.inp_parser_add(parser, "password", self.__database_password) def inp_extract_cmdline_parser(self, opts, args): self.__database_name = self.inp_parser_extract(opts, "database") self.__database_host = self.inp_parser_extract(opts, "host") self.__database_user = self.inp_parser_extract(opts, "user") self.__database_password = self.inp_parser_extract(opts, "password") def inp_metadata(self): return {self.name + "-database": self.__database_name, self.name + "-host": self.__database_host} def install_my_cnf(self): """Creates a my.cnf file and sets the environment variable MYSQL_HOME""" directory = self.tmp_directory.new_directory(self.name) path = os.path.join(directory.path, "my.cnf") logging.debug("MYSQL_HOME=%s", path) with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, 0600), 'w') as handle: handle.write("""[client] host=%s user=%s password=%s database=%s """ %(self.__database_host, self.__database_user, self.__database_password, self.__database_name)) # Set the environment variable to the directory the my.cnf is located os.environ["MYSQL_HOME"] = directory.path if os.path.exists(os.path.join(os.environ["HOME"], ".my.cnf")): logging.warning("~/.my.cnf does overwrite versuchung's file") def before_experiment_run(self, parameter_type): Type.before_experiment_run(self, parameter_type) assert parameter_type in ["input", "output"] args = {"db": self.__database_name, "host": self.__database_host} if self.__database_user: args["user"] = self.__database_user if self.__database_password: args["passwd"] = self.__database_password default_file = os.path.join(os.environ["HOME"], ".my.cnf") if os.path.exists(default_file): args["read_default_file"] = default_file self.__database_connection = MySQLdb.connect(**args) if parameter_type == "output": try: self.create_table("metadata", [("experiment", "varchar(256)"), ("metadata", "text")], keys = ["experiment"], conflict_strategy = "REPLACE") except _mysql_exceptions.OperationalError as e: # Metadata table was already generated pass self.execute("REPLACE INTO metadata(experiment, metadata) values(?, ?)", self.dynamic_experiment.experiment_identifier, str(self.dynamic_experiment.metadata)) @property def handle(self): """:return: handle -- MySQLdb database handle""" assert self.__database_connection return self.__database_connection def execute(self, command, *args): """Execute command including the arguments on the sql handle. Question marks in the command are replaces by the ``*args``:: >>> database.execute("SELECT * FROM metadata WHERE experiment = ?", identifer) """ logging.debug("mysql: %s %s", str(command), str(args)) c = self.__database_connection.cursor() c.execute(command.replace("?", "%s"), args) self.__database_connection.commit() return c def create_table(self, name, fields = [("key", "text"), ("value", "text")], keys = None, conflict_strategy = None): """Creates a new table in the database. ``name`` is the name of newly created table. The ``fields`` are a list of columns. A column is a tuple, its first entry is the name, its second entry the column type. If primary is the name of a column this column is marked as the primary key for the table. conflict_strategy is ignored! """ CT = "CREATE TABLE " + name + " (" CT += ", ".join([ "%s %s" % x for x in fields]) if keys: assert set(keys).issubset(set([x[0] for x in fields])) CT += ", UNIQUE(" + (", ".join(keys)) + ")" CT += ")" return self.execute(CT) class Database_SQLite(InputParameter, OutputParameter, Type, Database_Abstract): """Can be used as **input parameter** and **output parameter** A database backend class for sqlite3 database.""" # Static cache of all database connections open in system # Map from path -> tuple(db_handle, use_count) database_connections = {} def __init__(self, path = "sqlite3.db"): InputParameter.__init__(self) OutputParameter.__init__(self) Type.__init__(self) self.__database_path = path self.__database_connection = None def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__database_path) def inp_extract_cmdline_parser(self, opts, args): self.__database_path = self.inp_parser_extract(opts, None) def inp_metadata(self): return {self.name: self.__database_path} def before_experiment_run(self, parameter_type): Type.before_experiment_run(self, parameter_type) assert parameter_type in ["input", "output"] if parameter_type == "input": # Ensure the path does exist if not os.path.exists(self.path): raise RuntimeError("Database not found: %s" % self.path) self.__database_connection = self.__connect(self.path) if parameter_type == "output": try: self.create_table("metadata", [("experiment", "text"), ("metadata", "text")], keys = ["experiment"], conflict_strategy = "REPLACE") except sqlite3.OperationalError as e: # Metadata table was already generated pass self.execute("INSERT INTO metadata(experiment, metadata) values(?, ?)", self.dynamic_experiment.experiment_identifier, str(self.dynamic_experiment.metadata)) def after_experiment_run(self, parameter_type): Type.before_experiment_run(self, parameter_type) assert parameter_type in ["input", "output"] self.__database_connection = None self.__disconnect(self.path) if parameter_type == "output": # Remove execute and write permissions for file new_mode = os.stat(self.path).st_mode & (stat.S_IROTH | stat.S_IRGRP | stat.S_IRUSR) os.chmod(self.path, new_mode) @staticmethod def __connect(path): # Do reference counting on database connections if path in Database_SQLite.database_connections: (db, count) = Database_SQLite.database_connections[path] Database_SQLite.database_connections[path] = (db, count + 1) return db conn = sqlite3.connect(path) Database_SQLite.database_connections[path] = (conn, 1) return conn @staticmethod def __disconnect(path): (db, count) = Database_SQLite.database_connections[path] db.commit() if count == 1: db.close() del Database_SQLite.database_connections[path] return Database_SQLite.database_connections[path] = (db, count - 1) @property def path(self): """:return: string -- path to the sqlite database file""" return os.path.join(self.base_directory, self.__database_path) @property def handle(self): """:return: handle -- sqlite3 database handle""" assert self.__database_connection return self.__database_connection def execute(self, command, *args): """Execute command including the arguments on the sql handle. Question marks in the command are replaces by the ``*args``:: >>> database.execute("SELECT * FROM metadata WHERE experiment = ?", identifer) """ logging.debug("sqlite: %s %s", str(command), str(args)) return self.__database_connection.execute(command, args) def create_table(self, name, fields = [("key", "text"), ("value", "text")], keys = None, conflict_strategy = "REPLACE"): """Creates a new table in the database. ``name`` is the name of newly created table. The ``fields`` are a list of columns. A column is a tuple, its first entry is the name, its second entry the column type. If primary is the name of a column this column is marked as the primary key for the table.""" CT = "CREATE TABLE " + name + " (" CT += ", ".join([ "%s %s" % x for x in fields]) if keys: assert set(keys).issubset(set([x[0] for x in fields])) CT += ", UNIQUE(" + (", ".join(keys)) + ")" CT += " ON CONFLICT " + conflict_strategy CT += ")" return self.execute(CT) def Database( database_type = "sqlite", *args, **kwargs): """This is a just a wrapper around the supported database abstraction classes. Every other argument and paramater than ``database_type`` is forwared directly to those classes. Supported database_type abstractions are at the moment: - ``sqlite`` -- :class:`~versuchung.database.Database_SQLite` - ``mysql`` -- :class:`~versuchung.database.Database_MySQL` """ if database_type == "sqlite": if not "path" in kwargs: kwargs["path"] = "sqlite3.db" return Database_SQLite(*args, **kwargs) if database_type == "mysql": return Database_MySQL(*args, **kwargs) assert False, "Database type %s is not implemented yet" % database_type class Table(InputParameter, OutputParameter, Type): """Can be used as **input parameter** and **output parameter** A versuchung table is a table that is aware of experiments. It stores for each dataset the experiment it originates from. The field list consists either of plain strings, then the column type is text. If it's a tuple the first entry is the name and the second its type:: >>> [("foo", "integer"), "barfoo"] This will result in two columns, one with type integer and one with type text. If a db is given this one is used instead of a default sqlite database named ``sqlite3.db`` To make a set of field the index keys (UNIQUE), give it as a list of string as keys argument. The conflict_strategy gives the SQL strategy what to do on conflict. If you want to merge databases from multiple experiments without triggering a conflict if the given key set is equal (i.e., if you want the same values in the columns given as keys to be treated different when coming from different experiments), add ``experiment`` to the key set. """ def __init__(self, fields, keys = None, db = None, conflict_strategy = "FAIL" ): self.read_only = True InputParameter.__init__(self) OutputParameter.__init__(self) Type.__init__(self) self.__keys = keys self.__fields = self.__field_typify(["experiment"] + fields) self.__conflict_strategy = conflict_strategy if not db: self.__db = Database() else: self.__db = db def __field_typify(self, fields): real_fields = [] for f in fields: if type(f) in [tuple, list]: real_fields.append(tuple(f)) else: # the default field type is text assert type(f) == str real_fields.append(tuple([f, 'text'])) return real_fields def before_experiment_run(self, parameter_type): # Add database object as an self.subobjects["database"] = self.__db Type.before_experiment_run(self, parameter_type) if parameter_type == "output": self.read_only = False self.__db.create_table(self.table_name, self.__fields, keys = self.__keys, conflict_strategy = self.__conflict_strategy) @property def database(self): """:return: :class:`~versuchung.database.Database` -- the database the table is located in""" return self.__db @property def table_name(self): """:return: string -- return the name of the table in the database""" assert self.static_experiment name = self.name try: i = self.name.rindex("-") name = name[i+1:] except: pass return self.static_experiment.title + "__" + name def insert(self, data=None, **kwargs): """Insert a dict of data into the database table""" assert self.read_only == False if data: kwargs.update(data) kwargs["experiment"] = self.dynamic_experiment.experiment_identifier assert set(kwargs.keys()) == set([f for f, t in self.__fields]) items = kwargs.items() insert_statement = "INSERT INTO %s(%s) values(%s)" % ( self.table_name, ", ".join([f for f, t in items]), ", ".join(["?" for _ in items])) self.__db.execute(insert_statement, *[v for k,v in items]) def clear(self): """Remove all entries associated with the current running experiment""" self.__db.execute("DELETE FROM " + self.table_name +" WHERE experiment = ?", self.dynamic_experiment.experiment_identifier) @property def value(self): """The value of the table. It returns a tuple. The first entry is a tuple of column headings. The second entry is a list of rows, in the same order as the column headings. The column that associates the entry with the experiment is stripped apart and only data for the static enclosing experiment is shown.""" (cols, rows) = self.__db.values(self.table_name, ' where experiment = ?', self.static_experiment.experiment_identifier) index = cols.index("experiment") table = [] for row in rows: l = list(row) del l[index] table.append(tuple(l)) del cols[index] return tuple(cols), table class TableDict(Table, dict): """Can be used as **input parameter** and **output parameter** This uses a :class:`~versuchung.database.Table` as a backend for a python dict. This object can be used in the same way :class:`~versuchung.tex.PgfKeyDict` is used. Please be aware, that the storage and retrieval of keys from the associated table is done lazy. Therefore the data is only then visible if the experiment was successful. """ def __init__(self, db=None): self.__key_name = "key" self.__value_name = "value" columns = [(self.__key_name, 'text'), (self.__value_name, 'text')] Table.__init__(self, columns, keys=[self.__key_name], db=db, conflict_strategy = "REPLACE") dict.__init__(self) def insert(self, *args, **kwargs): raise NotImplementedError def flush(self): """Save the current dict content to the database.""" Table.clear(self) for key, value in self.items(): Table.insert(self, {self.__key_name: key, self.__value_name: value}) def after_experiment_run(self, parameter_type): assert self.parameter_type == parameter_type if parameter_type == "output": self.flush() Table.after_experiment_run(self, parameter_type) def before_experiment_run(self, parameter_type): Table.before_experiment_run(self, parameter_type) if parameter_type == "input": (header, values) = self.value key_index = header.index(self.__key_name) value_index = header.index(self.__value_name) self.update([(x[key_index], x[value_index]) for x in values]) class Database_SQlite_Merger: def log(self, msg, *args): if self.logging: print "merger: " + (msg % args) def __init__(self, target_path, source_paths = [], logging = True): self.target_path = target_path self.logging = logging self.source_paths = {} self.target = sqlite3.connect(target_path) db_counter = 0 for source in source_paths: assert os.path.exists(source), "Path does not exist " + source name = "db_%d" % db_counter db_counter += 1 self.target.execute("ATTACH DATABASE '%s' AS %s" %(source, name)) self.log("attached %s as %s", source, name) self.source_paths[name] = source def collect_and_create_tables(self, drop = True): cur = self.target.cursor() self.tables = {} for db in self.source_paths: cur.execute("SELECT * FROM " + db + ".sqlite_master WHERE type = 'table'") header = [x[0] for x in cur.description] for table in cur.fetchall(): table = dict(zip(header, table)) name = table["name"] if table["name"] in self.tables: if self.tables[name]["sql"] != table["sql"]: self.log("Two tables with different defintions found: %s" % name) sys.exit(-1) self.tables[name]["databases"].append(db) else: self.tables[name] = table self.tables[name]["databases"] = [db] for name, table in self.tables.items(): if drop: try: cur.execute("DROP TABLE %s" % name) except: pass cur.execute(table["sql"]) else: cur.execute(table["sql"].replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS')) self.log("created table %s", name) cur.close() def collect_data(self): cur = self.target.cursor() TableDictrows = set() for name in self.tables: rows = set() headers = None for db in self.tables[name]["databases"]: cur.execute("SELECT * FROM %s.%s" % (db, name)) for i in cur.fetchall(): rows.add(i) headers = [x[0] for x in cur.description] cur.executemany("INSERT INTO %s (%s) values(%s)" % (\ name, ", ".join(headers), ", ".join(["?" for x in headers]) ), rows) self.log("inserted %d rows into %s", len(rows), name) if headers == ["experiment", "key", "value"]: TableDictrows.update(rows) cur.execute("CREATE TABLE IF NOT EXISTS TableDict (experiment text, key text, value text," "UNIQUE (key) ON CONFLICT REPLACE)") cur.executemany("INSERT INTO TableDict (experiment, key, value) values(?,?,?)", TableDictrows) self.log("inserted %d key-value pairs into TableDict", len(TableDictrows)) cur.close() self.target.commit() def merge(self, update = True): """Do the actual merge operation""" self.collect_and_create_tables(drop = not update) self.collect_data() self.target.close() if __name__ == '__main__': import sys if len(sys.argv) < 2: print sys.argv[0] + " [ ...]" print " -- merges different versuchung sqlite databases into a single one" sys.exit(-1) merger = Database_SQlite_Merger(sys.argv[1], sys.argv[2:]) merger.merge() versuchung-1.1/src/versuchung/events.py000066400000000000000000000031441242273412000204010ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from versuchung.files import CSV_File from versuchung.execute import shell import logging import os import time class EventLog(CSV_File): """Log events with timestamp""" def event(self, event, key, value = ""): """Log a event to the event log. There the event and the description together with the time of the event is stored :return: float -- UNIX Time of the Event""" t = time.time() self.append([t, event, key, value]) return t def shell(self, command, *args): """Like :func:`~versuchung.execute.shell`, but logs the start and stop of the process in the ``".events"``-file.""" _args = ["'%s'"%x.replace("'", "\'") for x in args] _command = command % tuple(_args) start = self.event("process started", _command) shell(command, *args) stop = self.event("process finished", _command) self.event("process duration", _command, stop - start) versuchung-1.1/src/versuchung/execute.py000066400000000000000000000240241242273412000205370ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from subprocess import * from versuchung.files import CSV_File import logging import os import resource import thread import time import pipes from versuchung.tools import AdviceManager, Advice from multiprocessing import cpu_count as __cpu_count try: cpu_count = __cpu_count() except NotImplementedError: cpu_count = 1 class CommandFailed(RuntimeError): """ Indicates that some command failed Attributes: command: the command that failed returncode: the exitcode of the failed command """ def __init__(self, command, returncode, stdout=""): assert(returncode != 0) self.command = command self.returncode = returncode self.repr = "Command %s failed to execute (returncode: %d)" % \ (command, returncode) self.stdout = stdout RuntimeError.__init__(self, self.repr) def __str__(self): return self.repr + "\n\nSTDOUT:\n" + self.stdout def quote_args(args): if len(args) == 1 and type(args[0]) == dict: ret = {} for k,v in args[0].items(): ret[k] = pipes.quote(v) return ret elif type(args) == list or type(args) == tuple: args = tuple([pipes.quote(x) for x in args]) else: assert False return args def __shell(failok, command, *args): os.environ["LC_ALL"] = "C" args = quote_args(args) command = command % args logging.debug("executing: " + command) p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True) stdout = "" while True: x = p.stdout.readline() if not x: break stdout += x logging.debug("stdout|%s", x.replace("\n", "")) p.wait() if len(stdout) > 0 and stdout[-1] == '\n': stdout = stdout[:-1] if not failok and p.returncode != 0: raise CommandFailed(command, p.returncode, stdout) return (stdout.__str__().rsplit('\n'), p.returncode) @AdviceManager.advicable def shell(command, *args): """ executes 'command' in a shell .. note:: The following command enables capturing `stderr`, `stdout` and runtime information (with `/usr/bin/time`):: shell.track(experiment.path) .. note:: Tracking is enabled automatically after setup. It can be disabled and re-enabled while running the experiment with:: >> shell.track.disable() >> shell.track.enable() The tracking feature creates files like ``shell_0_time``, ``shell_0_stderr``, and so on. These files are created in the ``experiment.path`` directory. .. note:: To write the results of the tracking feature into the experiment output folder, use ``self.path`` within a :meth:`run()` method of an experiment:: shell.track(experiment.path) :rtype: a tuple with: 1. the command's standard output as list of lines 2. the exitcode :raises: :exc:`CommandFailed` if the returncode is != 0 """ return __shell(False, command, *args) @AdviceManager.advicable def shell_failok(command, *args): """Like :meth:`.shell`, but the throws no exception""" return __shell(True, command, *args) def add_sys_path(path): """Add path to the PATH environment variable""" os.environ["PATH"] = path + ":" + os.environ["PATH"] class AdviceShellTracker(Advice): def __call__(self, base_directory): self.base_directory = base_directory assert os.path.isdir(base_directory) self.count = 0 # Enable the Advice self.enable() def around(self, func, args, kwargs): assert len(args) > 0 command = args[0] import versuchung.execute args = versuchung.execute.quote_args(list(args)[1:]) command = command % args cmd = "/usr/bin/time --verbose -o %s_time sh -c %s 2> %s_stderr" base = os.path.join(self.base_directory, "shell_%d" % self.count) self.count += 1 args = tuple([cmd, base, command, base]) # Dump away stdout ret = func(args, kwargs) with open(base + "_stdout", "w+") as fd: fd.write("\n".join(ret[0]) + "\n") return ret shell.track = AdviceShellTracker("versuchung.execute.shell") shell_failok.track = AdviceShellTracker("versuchung.execute.shell_failok") class MachineMonitor(CSV_File): """Can be used as: **input parameter** and **output parameter** With this parameter the systems status during the experiment can be monitored. The tick interval can specified on creation and also what values should be captured. This parameter creates a :class:`~versuchung.files.CSV_File` with the given name. When the experiment starts the monitor fires up a thread which will every ``tick_interval`` milliseconds capture the status of the system and store the information as a row in the normal csv. A short example:: class SimpleExperiment(Experiment): outputs = {"ps": MachineMonitor("ps_monitor", tick_interval=100)} def run(self): shell("sleep 1") shell("seq 1 100000 | while read a; do echo > /dev/null; done") shell("sleep 1") experiment = SimpleExperiment() experiment(sys.argv) >>> experiment.o.ps.extract(["time", "net_send"]) [[1326548338.701827, 0], [1326548338.810422, 3], [1326548338.913667, 0], [1326548339.016836, 0], [1326548339.119982, 2], .... """ def __init__(self, default_filename = "", tick_interval=100, capture = ["cpu", "mem", "net", "disk"]): CSV_File.__init__(self, default_filename) self.tick_interval = tick_interval self.__running = True self.capture = capture def __get_cpu(self): return [self.psutil.cpu_percent()] def __get_memory(self): phymem = self.psutil.phymem_usage() virtmem = self.psutil.virtmem_usage() cached = self.psutil.cached_phymem() buffers = self.psutil.phymem_buffers() return [phymem.total, phymem.used, phymem.free, virtmem.total, virtmem.used, virtmem.free, cached, buffers] def __get_net(self): if not hasattr(self, "old_network_stat"): self.old_network_stat = self.psutil.network_io_counters() stat = self.psutil.network_io_counters() ret = [stat.bytes_sent - self.old_network_stat.bytes_sent, stat.bytes_recv - self.old_network_stat.bytes_recv] self.old_network_stat = stat return ret def __get_disk(self): if not hasattr(self, "old_disk_stat"): self.old_disk_stat = self.psutil.disk_io_counters() stat = self.psutil.disk_io_counters() ret = [stat.read_bytes - self.old_disk_stat.read_bytes, stat.write_bytes - self.old_disk_stat.write_bytes] self.old_disk_stat = stat return ret def monitor_thread(self): try: import psutil self.psutil = psutil except ImportError: raise RuntimeError("Please install psutil to use PsMonitor") while self.__running: row = [time.time()] if "cpu" in self.capture: row += self.__get_cpu() else: row += [-1] if "mem" in self.capture: row += self.__get_memory() else: row += [-1,-1,-1,-1,-1,-1,-1,-1] if "net" in self.capture: row += self.__get_net() else: row += [-1,-1] if "disk" in self.capture: row += self.__get_disk() else: row += [-1,-1] assert len(row) == len(self.sample_keys) self.append(row) time.sleep(self.tick_interval/1000.0) def inp_extract_cmdline_parser(self, opts, args): CSV_File.inp_parser_extract(self, opts, None) self.event_file = CSV_File(self.path + ".events") def before_experiment_run(self, parameter_type): if parameter_type == "output": CSV_File.before_experiment_run(self, "output") self.event_file = CSV_File(self.path + ".events") self.event_file.before_experiment_run("output") self.thread = thread.start_new_thread(self.monitor_thread, tuple()) def after_experiment_run(self, parameter_type): if parameter_type == "output": self.__running = False time.sleep(self.tick_interval/1000.0) CSV_File.after_experiment_run(self, "output") self.event_file.after_experiment_run("output") sample_keys = ["time", "cpu_percentage", "phymem_total", "phymem_used", "phymem_free", "virtmem_total", "virtmem_used", "virtmem_free", "cached", "buffers", "net_send", "net_recv", "disk_read", "disk_write"] """The various fields in the csv file are organized like the strings in this list. E.g. The unix time is the first field of the csv file.""" def extract(self, keys = ["time", "cpu_percentage"]): """Extract single columns from the captured information. Useful keys are defined in :attr:`~.sample_keys`""" indices = [self.sample_keys.index(x) for x in keys] ret = [] for row in self.value: r = [] for index in indices: r.append(row[index]) ret.append(r) return ret versuchung-1.1/src/versuchung/experiment.py000066400000000000000000000421251242273412000212570ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from optparse import OptionParser import datetime import logging import pprint from versuchung.types import InputParameter, OutputParameter, Type from versuchung.files import Directory from versuchung.tools import JavascriptStyleDictAccess, setup_logging import sys import os.path import glob import hashlib import shutil import copy import tempfile import signal LambdaType = type(lambda x:x) class ExperimentError(Exception): pass class Experiment(Type, InputParameter): """Can be used as: **input parameter**""" version = 1 """Version of the experiment, defaults to 1. The version is included in the metadata **and** used for the metadata hash.""" i = None """Shorthand for :attr:`~.inputs`""" inputs = {} """In the input dictionary all input parameters are defined. They may and will influence the metadata and the metadata hash. Only objects which are marked as **input parameters** may be used here. The key in this ``dict`` is used as :attr:`~.name` attribute and propagated to the parameters. From these input parameters the command line interface is created. This ``dict`` can not only be used as a dictionary but also a object with the dot-notation (this behaviour is known and widely used in javascript). And there is i as a shorthand. >>> self.inputs["string_parameter"] >>> self.inputs.string_parameter >>> self.i.string_parameter """ o = None """Shorthand for :attr:`~.outputs`""" outputs = {} """Similar to the :attr:`~.inputs` attribute, in the output dictionary all experiment results are defined. Only objects that are explicitly marked as **output parameters** can be used here. When a experiment is used as an input parameter. The results of the old experiment can be accessed through this attribute. Of course at all points the short hands for inputs and outputs can be used. As well as the javascript style access to dictionary members. >>> self.inputs["experiment"].outputs["out_file"] >>> self.i.experiment.o.out_file """ title = None """Title of the experiment, this is normally the classname""" name = None """The name of the object. This is in execution mode (Experiment instance is the executed experiment) the result set name (str). When the experiment is used as input parameter it is the key-value in the :attr:`~.inputs` dictionary.""" suspend_on_error = False """Suspend the experiment process, if the run() method fails. The path of the tmp-directory is printed after suspension""" tmp_directory = None # Override base_directory from versuchung.types.Type base_directory = None @property def static_experiment(self): return self @static_experiment.setter def static_experiment(self, value): pass def __init__(self, default_experiment_instance = None): """The constructor of an experiment just fills in the necessary attributes but has *no* sideeffects on the outside world. :param default_experiment_instance: If used as input parameter, this is the default result set used. For example ``"SimpleExperiment-aeb298601cdc582b1b0d8260195f6cfd"`` :type default_experiment_instance: str. """ Type.__init__(self) InputParameter.__init__(self) self.title = self.__class__.__name__ self.static_experiment = self self.__experiment_instance = default_experiment_instance self.__metadata = None # Copy input and output objects self.inputs = JavascriptStyleDictAccess(copy.deepcopy(self.__class__.inputs)) self.i = self.inputs self.outputs = JavascriptStyleDictAccess(copy.deepcopy(self.__class__.outputs)) self.o = self.outputs if default_experiment_instance != None: self.base_directory = os.path.join(os.curdir, self.__experiment_instance) self.base_directory = os.path.realpath(self.base_directory) else: self.base_directory = os.path.realpath(os.curdir) # Sanity checking for input parameters. for (name, inp) in self.inputs.items(): # Lambdas are resolved, when the experiment is really started if type(inp) == LambdaType: continue if not isinstance(inp, InputParameter): print "%s cannot be used as an input parameter" % name sys.exit(-1) self.subobjects[name] = inp for (name, outp) in self.outputs.items(): if not isinstance(outp, OutputParameter): print "%s cannot be used as an output parameter" % name sys.exit(-1) self.subobjects[name] = outp def __setup_parser(self): self.__parser = OptionParser("%prog ") self.__parser.add_option('-d', '--base-dir', dest='base_dir', action='store', help="Directory which is used for storing the experiment data", default = ".") self.__parser.add_option('-l', '--list', dest='do_list', action='store_true', help="list all experiment results") self.__parser.add_option('-s', '--symlink', dest='do_symlink', action='store_true', help="symlink the result dir (as newest)") self.__parser.add_option('-v', '--verbose', dest='verbose', action='count', help="increase verbosity (specify multiple times for more)") for (name, inp) in self.inputs.items(): if type(inp) == LambdaType: continue inp.inp_setup_cmdline_parser(self.__parser) def __setup_tmp_directory(self): """Creat temporary directory and assign it to every input and output directories tmp_directory slots""" # Create temp directory self.tmp_directory = Directory(tempfile.mkdtemp()) self.subobjects["tmp_directory"] = self.tmp_directory def execute(self, args = [], **kwargs): """Calling this method will execute the experiment :param args: The command line arguments, normally ``sys.argv`` :type args: list. :kwargs: The keyword arguments can be used to overwrite the default values of the experiment, without assembling a command line. The normal mode of operation is to give ``sys.argv`` as argument: >>> experiment.execute(sys.argv) But with keyword arguments the following two expression result in the same result set: >>> experiment.execute(["--input_parameter", "foo"]) >>> experiment.execute(input_parameter="foo") """ self.dynamic_experiment = self self.subobjects.update() # Set up the argument parsing self.__setup_parser() (opts, args) = self.__parser.parse_args(args) os.chdir(opts.base_dir) setup_logging(opts.verbose) self.__opts = opts self.__args = args if self.__opts.do_list: for experiment in os.listdir(self.base_directory): if experiment.startswith(self.title): print "EXP", experiment self.__do_list(self.__class__(experiment)) return None for key in kwargs: if not hasattr(opts, key): raise AttributeError("No argument called %s" % key) setattr(opts, key, kwargs[key]) # Set up the experiment self.before_experiment_run("output") try: self.run() except: # Clean up the tmp directory if self.suspend_on_error: print "tmp-dir: %s" % self.tmp_directory.path self.suspend_python() logging.error("Removing tmp directory") shutil.rmtree(self.tmp_directory.path) raise # Tear down the experiment self.after_experiment_run("output") return self.__experiment_instance @property def experiment_identifier(self): """:return: string -- directory name of the produced experiment results""" return self.__experiment_instance __call__ = execute """A experiment can also executed by calling it, :attr:`execute` will be called. >>> experiment(sys.argv)""" def suspend_python(self): """Suspend the running python process. Give the control back to the terminal. This sends a SIGSTOP to the python process""" os.kill(os.getpid(), signal.SIGSTOP) def __do_list(self, experiment, indent = 0): with open(os.path.join(experiment.base_directory, "metadata")) as fd: content = fd.read() d = eval(content) content = experiment.__experiment_instance + "\n" + content print "+%s%s" % ("-" * indent, content.strip().replace("\n", "\n|" + (" " * (indent+1)))) for dirname in d.values(): if type(dirname) != type(""): continue if os.path.exists(os.path.join(dirname, "metadata")) and \ os.path.realpath(dirname) != os.path.realpath(experiment.base_directory): self.__do_list(Experiment(dirname), indent + 3) def before_experiment_run(self, parameter_type): # When experiment run as input, just run the normal input handlers if parameter_type == "input": Type.before_experiment_run(self, "input") return for (name, inp) in self.inputs.items(): if type(inp) == LambdaType: continue ret = inp.inp_extract_cmdline_parser(self.__opts, self.__args) if ret: (self.__opts, self.__args) = ret # After all input parameters are parsed. Execute the # calculated input parameters for (name, inp) in self.inputs.items(): if type(inp) != LambdaType: continue inp = inp(self) inp.name = name self.subobjects[name] = inp self.inputs[name] = inp self.subobjects.update() # Now set up the experiment tmp directory self.__setup_tmp_directory() for obj in self.inputs.values(): obj.before_experiment_run("input") self.__calculate_metadata() for obj in self.outputs.values(): obj.before_experiment_run("output") def __calculate_metadata(self): metadata = {} for name in self.inputs: metadata.update( self.inputs[name].inp_metadata() ) m = hashlib.md5() m.update("version %s" % str(self.version)) calc_metadata = self.filter_metadata(metadata) for key in sorted(calc_metadata.keys()): m.update(key + " " + str(calc_metadata[key])) self.__experiment_instance = "%s-%s" %(self.title, m.hexdigest()) self.base_directory = os.path.join(os.curdir, self.__experiment_instance) self.base_directory = os.path.realpath(self.base_directory) if os.path.exists(self.base_directory): logging.info("Removing all files from existing output directory") for f in glob.glob(os.path.join(self.base_directory, '*')): if os.path.isdir(f): shutil.rmtree(f) else: os.unlink(f) try: os.mkdir(self.base_directory) except OSError: pass # Here the hash is already calculated, so we can change the # metadata nonconsitent metadata["date-start"] = str(datetime.datetime.now()) metadata["experiment-name"] = self.title metadata["experiment-version"] = self.version metadata["experiment-hash"] = m.hexdigest() fd = open(os.path.join(self.base_directory, "metadata"), "w+") fd.write(pprint.pformat(metadata) + "\n") fd.close() self.__metadata = metadata def after_experiment_run(self, parameter_type): if parameter_type == "output": for (name, outp) in self.outputs.items(): outp.after_experiment_run("output") for (name, inp) in self.inputs.items(): inp.after_experiment_run("input") self.__metadata["date-end"] = str(datetime.datetime.now()) fd = open(os.path.join(self.path, "metadata"), "w+") fd.write(pprint.pformat(self.__metadata) + "\n") fd.close() shutil.rmtree(self.tmp_directory.path) # Create a Symlink to the newsest result set if self.__opts.do_symlink: link = os.path.join(self.__opts.base_dir, self.title) if os.path.islink(link): os.unlink(link) if not os.path.exists(link): os.symlink(self.__experiment_instance, link) else: logging.warn("Didn't create symlink, %s exists and is no symlink", link) else: for (name, outp) in self.outputs.items(): outp.after_experiment_run("input") ### Input Type def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__experiment_instance) def inp_extract_cmdline_parser(self, opts, args): self.__experiment_instance = self.inp_parser_extract(opts, None) if not self.__experiment_instance: print "Missing argument for %s" % self.title raise ExperimentError # Resolve symlink relative to the current directory self.__experiment_instance = os.path.realpath(self.__experiment_instance) self.__experiment_instance = self.__experiment_instance[len(os.path.realpath(os.curdir))+1:] self.base_directory = os.path.join(os.curdir, self.__experiment_instance) self.base_directory = os.path.realpath(self.base_directory) for (name, outp) in self.outputs.items(): del self.subobjects[name] self.subobjects[name] = outp def inp_metadata(self): return {self.name: self.__experiment_instance} @property def metadata(self): """Return the metadata as python dict. This works for experiments, which are running at the moment, and for already finished experiments by reading the /metadata file.""" if not self.__metadata: md_path = os.path.join(self.base_directory, "metadata") with open(md_path) as fd: self.__metadata = eval(fd.read()) return self.__metadata @property def path(self): """Return the path to output directory""" return self.base_directory def run(self): """This method is the heart of every experiment and must be implemented by the user. It is called when the experiment is executed. Before all input parameters are parsed, the output directory is set up. Afterwards all temporary data is removed and the output parameters are deinitialized. .. warning:: Must be implemented by the user.""" raise NotImplemented def filter_metadata(self, metadata): """This method is invocated on the dict which is stored in $result_dir/metadata before the result_hash is calculated. This helps to take influence on the input parameters which alter the experiment hash. So use it with care. .. note:: Can be implemented by the user.""" return metadata def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: pass inp = None outp = None try: inp = getattr(self.inputs, name) except AttributeError: pass try: outp = getattr(self.outputs, name) except AttributeError: pass if inp != None and outp != None: raise AttributeError("'%s.%s' is ambigous, use .inputs/.outputs" %(\ self.__class__.__name__, name)) elif inp != None: return inp elif outp != None: return outp raise AttributeError("'%s' object has no attribute '%s'" %(\ self.__class__.__name__, name)) versuchung-1.1/src/versuchung/files.py000066400000000000000000000302301242273412000201730ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from versuchung.types import InputParameter, OutputParameter, Type from versuchung.tools import before from cStringIO import StringIO import shutil import csv import os, stat import hashlib class FilesystemObject(InputParameter, OutputParameter, Type): def __init__(self, default_name=""): InputParameter.__init__(self) OutputParameter.__init__(self) Type.__init__(self) self.__object_name = default_name self.__enclosing_directory = os.path.abspath(os.curdir) self.__force_enclosing_directory = False def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__object_name) def inp_extract_cmdline_parser(self, opts, args): self.__object_name = self.inp_parser_extract(opts, None) def inp_metadata(self): return {self.name: self.__object_name} @property def path(self): """:return: string -- path to the file/directory""" if not self.__force_enclosing_directory: if self.parameter_type == "input": if self.static_experiment == self.dynamic_experiment: self.__enclosing_directory = os.path.abspath(os.curdir) else: self.__enclosing_directory = self.static_experiment.base_directory elif self.parameter_type == "output": assert self.static_experiment == self.dynamic_experiment self.__enclosing_directory = self.dynamic_experiment.base_directory else: self.__enclosing_directory = os.path.abspath(os.curdir) return os.path.join(self.__enclosing_directory, self.__object_name) @property def basename(self): return os.path.basename(self.path) @property def dirname(self): return os.path.basename(self.path) def set_path(self, base_directory, object_name): assert base_directory[0] == "/" self.__force_enclosing_directory = True self.__enclosing_directory = base_directory self.__object_name = object_name class File(FilesystemObject): """Can be used as: **input parameter** and **output parameter** The File type represents the content of a single file. Its contents can be read and written most easily with the :attr:`value` property. Alternatively, the method :meth:`write` appends new content if the parameter `append` is set to `True`. NB: The content of the file is flushed only after the experiment finishes. Use :meth:`flush` to force writing the buffered data to disk before the experiment finishes. """ def __init__(self, default_filename=""): FilesystemObject.__init__(self, default_filename) self.__value = None @property def value(self): """This attribute can be read and written and represent the content of the specified file""" if not self.__value: try: with open(self.path) as fd: self.__value = self.after_read(fd.read()) except IOError: # File couldn't be read self.__value = self.after_read("") return self.__value @value.setter def value(self, value): self.__value = value def write(self, content, append = False): """Similar to the :attr:`value` property. If the parameter `append` is `False`, then the property :attr:`value` is reset (i.e., overwritten), otherwise the content is appendend""" if append: self.value += content else: self.value = content def after_experiment_run(self, parameter_type): FilesystemObject.after_experiment_run(self, parameter_type) assert parameter_type in ["input", "output"] if parameter_type == "output": self.flush() def flush(self): """Flush the cached content of the file to disk""" if not self.__value: return with open(self.path, "w+") as fd: v = self.before_write(self.value) if v is None: v = "" fd.write(v) def copy_contents(self, filename): """Read the given file and replace the current .value with the files content. Flushes automatically afterwards.""" with open(filename) as fd: self.value = self.after_read(fd.read()) self.flush() def make_executable(self): """makes a file exectuable (chmod +x $file)""" st = os.stat(self.path) os.chmod(self.path, st.st_mode | stat.S_IEXEC) def after_read(self, value): """To provide filtering of file contents in subclasses, overrwrite this method. It is gets the file content as a string and returns the value()""" return value def before_write(self, value): """To provide filtering of file contents in subclasses, overrwrite this method. This method gets the value() and returns a string, when the file is written to disk""" return value class Executable(File): """Can be used as: **input parameter** An executable is a :class:`versuchung.files.File` that only references an executable. It checksums the executable and puts the checksum into the metadata. The executable is never changed. """ def __init__(self, default_filename): File.__init__(self, default_filename) @property def value(self): raise NotImplemented @value.setter def value(self, value): raise NotImplementedError def write(self, content, append = False): raise NotImplementedError def after_experiment_run(self, parameter_type): pass def flush(self): raise NotImplementedError def copy_contents(self, filename): raise NotImplementedError def make_executable(self): raise NotImplementedError def inp_metadata(self): return {self.name + "-md5": hashlib.md5(open(self.path).read()).hexdigest()} def execute(self, cmdline, *args): """Does start the executable with meth:`versuchung.execute.shell` and args, which is of type list, as arguments.""" from versuchung.execute import shell shell(self.path + " " + cmdline, *args) class Directory_op_with: def __init__(self): self.__olddir = [] def __enter__(self): self.__olddir.append(os.path.abspath(os.curdir)) os.chdir(self.path) return self.path def __exit__(self, *excinfo): path = self.__olddir[-1] del self.__olddir[-1] os.chdir(path) class Directory(FilesystemObject, Directory_op_with): """Can be used as: **input parameter** and **output parameter** Represents the contents of directory. It can also be used with the **with**-keyword to change the current working directory temporarily to this directory:: with directory as dir: # Do something with adjusted current working directory print os.curdir """ def __init__(self, default_filename=""): FilesystemObject.__init__(self, default_filename) Directory_op_with.__init__(self) self.__value = None self.__new_files = [] def ___ensure_dir_exists(self): if not os.path.exists(self.path): os.mkdir(self.path) # Ensure dir exists DECORATOR __ensure_dir_exists = before(___ensure_dir_exists) @property def value(self): """:return: list -- directories and files in given directory""" if not self.__value: self.__value = os.listdir(self.path) return self.__value def __iter__(self): for name in self.value: p = os.path.join(self.path, name) if os.path.isdir(p): d = Directory(name) d.set_path(self.path, p) self.subobjects[name] = d yield d else: f = File(name) f.set_path(self.path, p) self.subobjects[name] = f yield f def before_experiment_run(self, parameter_type): FilesystemObject.before_experiment_run(self, parameter_type) if parameter_type == "output": self.___ensure_dir_exists() @__ensure_dir_exists def new_file(self, name): """Generate a new :class:`~versuchung.files.File` in the directory. It will be flushed automatically if the experiment is over.""" f = File(name) f.set_path(self.path, name) self.subobjects[name] = f return f @__ensure_dir_exists def new_directory(self, name): """Generate a new :class:`~versuchung.files.Directory` in the directory. The directory must not be present before""" f = Directory(name) f.set_path(self.path, name) os.mkdir(f.path) self.subobjects[name] = f return f @__ensure_dir_exists def mirror_directory(self, path, include_closure = None): """Copies the contents of the given directory to this directory. The include closure is a function, which checks for every (absolute) path in the origin directory, if it is mirrored. If it is None, all files are included.""" if not include_closure: include_closure = lambda arg: True if not os.path.exists(path) and os.path.isdir(path): raise RuntimeError("Argument is no directory") path = os.path.abspath(path) for root, dirs, files in os.walk(path): root = root[len(path)+1:] for d in dirs: src = os.path.join(path, root, d) if not include_closure(src): continue dst = os.path.join(self.path, root, d) if not os.path.isdir(dst): os.mkdir(dst) for f in files: src = os.path.join(path, root, f) if not include_closure(src): continue dst = os.path.join(self.path, root, f) shutil.copyfile(src,dst) self.__value = None class CSV_File(File): """Can be used as: **input parameter** and **output parameter** It is a normal :class:`~versuchung.files.File` but the content of the file is interpreted as a csv file. It is parsed before the value is exposed to the user. And formatted before the content is written to disk. Internally the :mod:`csv` is used, so all arguments to ``csv.reader`` and ``csv.writer`` can be given in *csv_args*.""" value = File.value """Other than a normal CSV_File the value of a CSV_File is a list of lists, which represents the structure of the csv file. This value can be manipulated by the user. >>> CSV_File("csv_output").value [["1", "2", "3"]]""" def __init__(self, default_filename = "", **csv_args): File.__init__(self, default_filename) self.csv_args = csv_args def after_read(self, value): fd = StringIO(value) reader = csv.reader(fd, self.csv_args) return list(reader) def before_write(self, value): fd = StringIO() writer = csv.writer(fd, self.csv_args) writer.writerows(value) return fd.getvalue() def write(self): raise NotImplemented def append(self, row): """Append a row to the csv file It is just a shorthand for >>> csv_file.value.append([1,2,3]) :param row: row to append :type row: list.""" if type(row) != list: raise TypeError("list of values required") self.value.append(row) versuchung-1.1/src/versuchung/search.py000066400000000000000000000106471242273412000203500ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . import os import logging def search_experiment_results(experiment_type, directory, selector = None): """In large experiment setups it is hard to keep track of all result sets, which were produced. Therefore a search on the "result set database" is implemented with this function. :param experiment_type: The experiment class object you are looking for :param directory: Which directory to search for (recursivly) :param selector: function that gets an experiment_type instance and returns a bool :rtype: a list of experiment_type objects The selector can also be a :class:`dict` will be wrapped automatically with :func:`search_selector_metadata`. >>> search_experiment_results(MyExperiment, ".", lambda e: "home" in e.path) [] """ # Name -> Path experiment_map = {} experiment_title = experiment_type.__name__ if selector == None: selector = lambda x: True if type(selector) == dict: selector = search_selector_metadata(selector) for root, dirs, files in os.walk(directory, followlinks=True): if "metadata" in files: experiment_name = os.path.basename(root) path = root if experiment_name.startswith(experiment_title): dataset = experiment_type(path) if selector(dataset): exp = experiment_type(path) if exp.path not in [e.path for e in experiment_map.values()]: experiment_map[experiment_name] = exp return experiment_map.values() def search_experiment(experiment_type, directory, selector = None): """Like :func:`search_experiment_results`, but returns only one experiment result set. And fails if it is ambigious""" exps = search_experiment_results(experiment_type, directory, selector) if len(exps) != 1: logging.error("search_experiment didn't exactly one instance of %s (%d found)", experiment_type, len(exps)) for exp in exps: logging.error(" - %s", exp.path) assert False return exps[0] def search_path_go_up_till(path, till): """Go up in the given path (which is of type string), until the directory is called till""" while path and path != "" and os.path.basename(path) != till: path = os.path.dirname(path) assert path return path def search_selector_metadata(metadata_dict): """Creates a selector to be used with search_experiment_results. The selector will only select experiments where all metadata keys eqyal to the given metadata_dict.""" def selector(experiment): for key in metadata_dict: if experiment.metadata[key] != metadata_dict[key]: return False return True return selector def assert_metadata_unique(metadata_field, experiments): """Ensure that all experiments have a different value in their metadata according to the metadata_field""" fields = set() for e in experiments: field = e.metadata[metadata_field] assert not field in fields fields.add(field) def assert_metadata_common(metadata_field, experiments): """Ensure that all experiments have the same value in their metadata according to the metadata_field""" if len(experiments) > 1: field = experiments[0].metadata[metadata_field] for e in experiments: assert field == e.metadata[metadata_field] if __name__ == '__main__': import sys from versuchung.experiment import Experiment if len(sys.argv) != 4: print "%s " % sys.argv[0] sys.exit(-1) Experiment.__name__ = sys.argv[1] for exp in search_experiment_results(Experiment, ".", {sys.argv[2]: sys.argv[3]}): print exp.path versuchung-1.1/src/versuchung/tex.py000066400000000000000000000127561242273412000177060ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . from versuchung.files import File import re import os class Macros(File): """Can be used as: **input parameter** and **output parameter** A Macros file is a normal :class:`~versuchung.files.File` with the extension, that you can define TeX macros easily. This is especially useful for writing texts. You may have a experiment, which may be an analysis to an experiment that produces raw data. The produced numbers should appear in your LaTeX document. So instead of copying the numbers you can define TeX macros and use them in the text. This is especially useful if you work on the experiment and the text in parallel and the numbers change often. >>> from versuchung.tex import Macros >>> macro = Macros("/tmp/test.tex") >>> macro.macro("MyNewTexMacro", 23) >>> print macro.value \\newcommand{\MyNewTexMacro} {23} """ def __init__(self, filename = "data.tex"): """Define tex macros directly as output of a experiment. Use this only as output parameter!.""" File.__init__(self, filename) def macro(self, macro, value): """Define a new tex macro with \\\\newcommand. This will result in:: \\newcommand{%(macro)s} { %(value)s} """ self.write("\\newcommand{\\%s} {%s}\n" % (macro, value), append = True) def comment(self, comment): """Add a comment in the macro file""" for line in comment.split("\n"): self.write("%% %s\n" % line.strip(), append = True) def newline(self): """Append an newline to the texfile""" self.write("\n", append = True) class PgfKeyDict(File, dict): """Can be used as: **input parameter** and **output parameter** PgfKeyDict is very similar to :class:`~versuchung.tex.Macros`, but instead of \\\\newcommand directives it uses pgfkeys, can be used as a ``dict`` and it is possible to read it in again to produce the (almost) same dict again. >>> from versuchung.tex import PgfKeyDict >>> pgf = PgfKeyDict("/tmp/test.tex") >>> pgf["abcd"] = 23 >>> pgf.flush() # flush method of File >>> print open("/tmp/test.tex").read() \\pgfkeyssetvalue{/versuchung/abcd}{23} In the TeX source you can do something like:: \\usepackage{tikz} \\pgfkeys{/pgf/number format/.cd,fixed,precision=1} [...] \\newcommand{\\versuchung}[1]{\\pgfkeysvalueof{/versuchung/#1}} \\versuchung{abcd} .. note:: It is better to use :class:`PgfKeyDict` instead of :class:`Macros`, because you can also use spaces and other weird characters in pgfkeys, which cannot be used in TeX macro names. """ def __init__(self, filename = "data.tex", pgfkey = "/versuchung", setmacro="pgfkeyssetvalue"): File.__init__(self, filename) dict.__init__(self) self.__pgfkey = pgfkey self.format_string = "\\" + setmacro + "{%s/%s}{%s}" # Ensure the file is written if os.path.exists(self.path): a = self.value def after_read(self, value): regex = self.format_string %(self.__pgfkey,"([^{}]*)", "([^{}]*)") regex = regex.replace('\\', r'\\') for line in value.split("\n"): m = re.search(regex, line) if m: self[m.groups()[0]] = m.groups()[1] return self def before_write(self, value): v = [] last_base_key = None for key in sorted(self): value = self[key] if "/" in key: base_key = key[:key.rindex("/")] else: base_key = None if last_base_key and last_base_key != base_key: v.append("") last_base_key = base_key v.append(self.format_string % (self.__pgfkey, key, value)) return "\n".join(v) + "\n" def flush(self): self.value = self.before_write(self) File.flush(self) class PrefixForPgfKeyDict: def __init__(self, prefix, d): self.prefix = prefix self.d = d def __getitem__(self, key): return self.d[self.prefix + key] def __setitem__(self, key, value): self.d[self.prefix + key] = value def __delitem__(self, key): del self.d[self.prefix + key] def prefixed_with(self, prefix): return self.d.PrefixForPgfKeyDict(self.prefix + prefix, self.d) def prefixed_with(self, prefix): return self.PrefixForPgfKeyDict(prefix, self) class DatarefDict(PgfKeyDict): """Can be used as: **input parameter** and **output parameter** DatarefDict is like :class:`~versuchung.tex.PgfKeyDict`, but generates keys for dataref.""" def __init__(self, filename = "data.tex", key = ""): PgfKeyDict.__init__(self, filename, key, "drefset") if __name__ == '__main__': import sys print PgfKeyDict(sys.argv[1]) versuchung-1.1/src/versuchung/tools.py000066400000000000000000000126111242273412000202340ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . import logging class JavascriptStyleDictAccess(dict): def __init__(self, d): self.update(d) def __getattribute__(self, name): try: return dict.__getattribute__(self, name) except AttributeError: pass if name in self: return self[name] name = name.replace("_", "-") if name in self: return self[name] raise AttributeError def setup_logging(log_level): """ setup the logging module with the given log_level """ l = logging.WARNING # default if log_level == 1: l = logging.INFO elif log_level >= 2: l = logging.DEBUG logging.basicConfig(level=l) def before(decorator_argument): """Decorator for executing functions before other functions""" def decorator(func): def wrapped(self, *args, **kwargs): # Late binding inb4 = decorator_argument if type(decorator_argument) == str: inb4 = getattr(self, decorator_argument) if "func_code" in dir(inb4): argcount = inb4.func_code.co_argcount else: raise RuntimeError("Invalid argument to decorator") if argcount == 1: inb4(self) elif argcount == 0: inb4() else: raise RuntimeError("Unexpected parameter count") return func(self, *args, **kwargs) wrapped.__doc__ = func.__doc__ return wrapped return decorator class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( cls, *args, **kwargs) return cls._instance class AdviceManager(Singleton): def __init__(self): if not "before" in dir(self): self.before = dict() self.around = dict() self.after = dict() def around_wrapper(self, func, last = None): def wrapped(args, kwargs): if last: return func(last, args, kwargs) else: return func(*args, **kwargs) return wrapped @staticmethod def advicable(func): """Decorator to mark a function as advicable""" if not "func_name" in dir(func): raise ValueError("No function adviced") full_name = "%s.%s" % (func.__module__, func.func_name) self = AdviceManager() if full_name in self.before: raise RuntimeError("Function already marked as advicable") self.before[full_name] = [] self.around[full_name] = [] self.after[full_name] = [] def wrapped(*args, **kwargs): am = AdviceManager() for f in am.before[full_name]: ret = f(args, kwargs) if ret: (args, kwargs) = ret if len(am.around[full_name]) > 0: func_ = am.around_wrapper(func, None) for f in am.around[full_name]: func_ = am.around_wrapper(f, func_) ret = func_(args, kwargs) else: ret = func(*args, **kwargs) for f in am.after[full_name]: ret = f(ret) return ret wrapped.__doc__ = func.__doc__ return wrapped class Advice: def __init__(self, method, enabled = False): self.method = method am = AdviceManager() self.am = am if not method in am.before: raise RuntimeError("Function was not marked @advicable") self.enabled = False if enabled: self.enable() def disable(self): am = self.am am.before[self.method] = [ x for x in am.before[self.method] if x != self.before ] am.around[self.method] = [ x for x in am.around[self.method] if x != self.around ] am.after[self.method] = [ x for x in am.after[self.method] if x != self.after ] def enable(self): am = self.am if self.enabled: return # Hook only in if the methods are overwritten if self.before.im_func != Advice.before.im_func: am.before[self.method].append(self.before) if self.around.im_func != Advice.around.im_func: am.around[self.method].append(self.around) if self.after.im_func != Advice.after.im_func: am.after[self.method].append(self.after) self.enabled = True def before(self, args, kwargs): return (args, kwargs) def around(self, func, args, kwargs): return func(args, kwargs) def after(self, ret): return ret versuchung-1.1/src/versuchung/types.py000066400000000000000000000325711242273412000202470ustar00rootroot00000000000000# This file is part of versuchung. # # versuchung 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. # # versuchung 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 # versuchung. If not, see . import os import csv from cStringIO import StringIO from optparse import OptionParser import copy class SubObjects(dict): def __init__(self, type_object): dict.__init__(self) self.parent = type_object def __setitem__(self, key, value): assert not key in self or self[key] == value, "Duplicated object name: %s = %s" % (key, value) dict.__setitem__(self, key, value) value.parent_object = self.parent self.update() def update(self): if not "parent" in dir(self) and len(self) > 0: print "You probably used python multiprocessing, this might break horrible" return for name, obj in self.items(): if self.parent.name != None: obj.name = "%s-%s" % (self.parent.name, name) else: obj.name = name obj.static_experiment = self.parent.static_experiment obj.dynamic_experiment = self.parent.dynamic_experiment class Type(object): static_experiment = None """A reference to the static enclosing experiment: where the type was defined in""" dynamic_experiment = None """A reference to the currently running experiment""" subobjects = None """A Type.Subobjects instance that collects all Types that are used by this type. Subordinate types""" parent_object = None """A Type instance that is the parent of this object""" parameter_type = None def __init__(self): # We gather a list of objects that are used by us. self.subobjects = SubObjects(self) def before_experiment_run(self, parameter_type): self.parameter_type = parameter_type self.subobjects.update() for subobj in self.subobjects.values(): subobj.before_experiment_run(parameter_type) def after_experiment_run(self, parameter_type): for subobj in self.subobjects.values(): subobj.after_experiment_run(parameter_type) ################################################################ # Accessors ################################################################ """This is the base type for all input and output parameters""" @property def name(self): return self.__name @name.setter def name(self, name): self.__name = name def path_to_root_object(self): """Returns all parent objects""" ret = [] p = self while p.parent_object != None: ret.append(p) p = p.parent_object return list(reversed(ret)) @property def value(self): """Default accessor for this kind of data""" raise NotImplemented @property def base_directory(self): """The base directory of a type is always the base directory of the (statically) enclosing experiment instance. The Directory has the form -""" if not self.static_experiment: return None return self.static_experiment.base_directory @property def tmp_directory(self): """A temporary directory, which can be used during experiment execution. The tmp_directory is deduced through the dynamic experiment reference""" assert self.dynamic_experiment, "Type is not used part of a running experiment" return self.dynamic_experiment.tmp_directory class InputParameter: def __init__(self): pass def inp_setup_cmdline_parser(self, parser): raise NotImplemented def inp_extract_cmdline_parser(self, opts, args): raise NotImplemented def __parser_option(self, option = None): if option: return self.name + "-" + option return self.name def was_given(self): """Checks if an optional parameter was given""" if not hasattr(self, "optional_parameter_given"): return True if self.optional_parameter_given: return True return False def inp_parser_add(self, parser, option, default, **kwargs): option = self.__parser_option(option) kw = { "dest": option, } if not hasattr(self, "optional_parameter_given"): kw["default"] = default kw["help"] = "(default: %s)" % default kw.update(kwargs) parser.add_option('', '--%s' % option, **kw) def inp_parser_extract(self, opts, option): a = getattr(opts, self.__parser_option(option), None) if a != None and hasattr(self, "optional_parameter_given"): self.optional_parameter_given = True return a def inp_metadata(self): return {} def Optional(input_parameter): """Makes an input parameter optional. input_parameter.was_given() checks if the parameter was given on the command line.""" if not isinstance(input_parameter, InputParameter): raise RuntimeError("Optional() can only be used with input parameters") input_parameter.optional_parameter_given = False return input_parameter class OutputParameter: def __init__(self): pass class String(InputParameter, Type): """Can be used as: **input parameter** A String is the most simple input parameter.""" def __init__(self, default_value=""): InputParameter.__init__(self) Type.__init__(self) self.__value = default_value def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__value) def inp_extract_cmdline_parser(self, opts, args): self.__value = self.inp_parser_extract(opts, None) def inp_metadata(self): return {self.name: self.value} def __str__(self): return self.value @property def value(self): """The value of the string. This is either the default value or the parameter given on the command line""" return self.__value class Bool(InputParameter, Type): """Can be used as: **input parameter** A boolean flag parameter (will accept "yes" and "no" on the command line.""" def __init__(self, default_value=False): InputParameter.__init__(self) Type.__init__(self) self.__value = default_value def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__value) def inp_extract_cmdline_parser(self, opts, args): yes_values = ("yes", "y", "true", "1") no_values = ("no", "n", "false", "0") self.__value = self.inp_parser_extract(opts, None) if type(self.value) == str and self.__value.lower() in yes_values: self.__value = True elif type(self.value) == str and self.__value.lower() in no_values: self.__value = False elif type(self.__value) == bool: pass else: raise RuntimeError("Wrong parameter for Bool() argument (%s = %s), possible values are %s, %s" %\ (self.name, self.__value, yes_values, no_values)) def inp_metadata(self): return {self.name: self.value} def __str__(self): return str(self.value) @property def value(self): """The value of the bool. This is either the default value or the parameter given on the command line""" return self.__value class Integer(InputParameter, Type): """Can be used as: **input parameter** A integer flag argument (will accept a number on the command line.""" def __init__(self, default_value = 0): InputParameter.__init__(self) Type.__init__(self) self.__value = default_value def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, self.__value) def inp_extract_cmdline_parser(self, opts, args): self.__value = self.inp_parser_extract(opts, None) if type(self.__value) == int: pass else: try: self.__value = int(self.__value) except: raise RuntimeError("Wrong parameter for Bool() argument (%s)" % self.__value) def inp_metadata(self): return {self.name: self.value} def __str__(self): return str(self.value) @property def value(self): """The value of the integer. This is either the default value or the parameter given on the command line""" return self.__value class List(InputParameter, Type, list): """Can be used as: **input parameter** Sometimes there is the need to give a variable length of other **input types** as argument to an experiment. Of course here the command line parsing is somewhat more difficult, because the argument count isn't determined in before. The *datatype* argument is the type of the input parameter which should be collected:: inputs = { "strings": List(String) } The default_value must be a list of compatible instances. List list will be used, if no arguments are given. If any argument of this type on the command line is given, the default_value will not be used:: inputs = { "strings": List(String, default_value=[String("abc")]) } On the command line the List parameter can be given multiple times. These will be collected, if you want collect the strings ``["abc", "foobar", "Hallo Welt"]`` you can use the following parameters on the command line:: --strings abc --strings foobar --strings "Hallo Welt" .. note:: mention that the list members will appear as separate fields in the metadata. all start with the name of the input, and have a running number -%d appended. More complicated is the situation, when the subtype takes more than one command-line argument. There you can replace the name prefix with a colon. For example if you want to give a list of two :class:`~versuchung.archives.GitArchive` instances use the input definition ``"git": List(GitArchive)`` together with the command line:: --git ":clone-url /path/to/git1" --git ":clone-url /path/to/git2" .. note:: Be aware of the quotation marks here! In the experiment the input parameter behaves like a list (it inherits from ``list``), so it is really easy to iterate over it:: for string in self.inputs.strings: print string.value for git in self.inputs.git: # Clone all given Git Archives print git.path """ def __init__(self, datatype, default_value=[]): InputParameter.__init__(self) Type.__init__(self) list.__init__(self) self.__default_value = default_value if type(datatype) != type: datatype = type(datatype) self.datatype = datatype self.__command_line_parsed = False def inp_setup_cmdline_parser(self, parser): self.inp_parser_add(parser, None, copy.deepcopy(self.__default_value), action="append", help = "List parameter for type %s" % self.datatype.__name__) def before_experiment_run(self, parameter_type): if parameter_type == "input" and \ not self.__command_line_parsed: count = 0 for i in self.__default_value: self.subobjects["%d" % count] = i self.append(i) count += 1 Type.before_experiment_run(self,parameter_type) def inp_extract_cmdline_parser(self, opts, args): import shlex args = self.inp_parser_extract(opts, None) # No argument where given, us the default_values in before_experiment_run if len(args) == len(self.__default_value) and len(args) > 0\ and type(args[0]) == type(args[0]) == self.datatype: return self.__command_line_parsed = True if len(args) > len(self.__default_value): args = [x for x in args if type(x) != self.datatype] count = 0 for arg in args: # Create Subtype and initialize its parser subtype = self.datatype() self.subobjects["%d" % count] = subtype count += 1 subtype_parser = OptionParser() subtype.inp_setup_cmdline_parser(subtype_parser) if not ":" in arg: arg = ": " + arg arg = arg.replace(": ", "--" + subtype.name + " ") arg = arg.replace(":", "--" + subtype.name + "-") arg = shlex.split(arg) (opts, args) = subtype_parser.parse_args(arg) subtype.inp_extract_cmdline_parser(opts,args) self.append(subtype) def inp_metadata(self): metadata = {} for item in self: metadata.update(item.inp_metadata()) return metadata @property def value(self): """Returns the object (which behaves like a list) itself. This is only implemented for a coherent API.""" return self versuchung-1.1/tests/000077500000000000000000000000001242273412000147035ustar00rootroot00000000000000versuchung-1.1/tests/Makefile000066400000000000000000000005261242273412000163460ustar00rootroot00000000000000TESTS = $(patsubst ./%,%,$(shell find . -maxdepth 1 -mindepth 1 -type d)) PHONY = $(TESTS) PWD = $(shell pwd) check: $(TESTS) define test_cmd $(1): FORCE @echo -n "Running test $(1)..." @cd $(1); PYTHONPATH=$(PWD)/../src python test.py endef $(foreach test,$(TESTS),$(eval $(call test_cmd,$(test)))) FORCE: .PHONY: $(PHONY) FORCE versuchung-1.1/tests/advices/000077500000000000000000000000001242273412000163215ustar00rootroot00000000000000versuchung-1.1/tests/advices/test.py000066400000000000000000000012231242273412000176500ustar00rootroot00000000000000#!/usr/bin/python from versuchung.experiment import Experiment from versuchung.files import File from versuchung.execute import shell import os class SimpleExperiment(Experiment): def run(self): shell.track(self.path) shell("echo 1") shell("cd %s && test -x ./sh", "/bin") if __name__ == "__main__": import shutil, sys experiment = SimpleExperiment() dirname = experiment(sys.argv) assert os.path.exists(dirname + "/shell_0_time") assert os.path.exists(dirname + "/shell_0_stdout") assert os.path.exists(dirname + "/shell_0_stderr") if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/basic_types/000077500000000000000000000000001242273412000172105ustar00rootroot00000000000000versuchung-1.1/tests/basic_types/test.py000066400000000000000000000014271242273412000205450ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String, Optional, Bool class BasicTypesTest(Experiment): inputs = {"string": String("ABC"), "bool" : Bool(True), "string_optional": Optional(String())} def run(self): assert not self.string_optional.was_given() assert self.string.was_given() assert str(self.string) == "ABC" assert str(self.string) != repr(self.string) assert " 0 assert self.se.table1["foo"] == "bar" assert self.se.table2.value[1][0] == (23,) if __name__ == "__main__": import shutil, sys e1 = SimpleExperiment() r1 = e1([]) assert os.path.exists(os.path.join(r1, "sqlite3.db")) assert os.path.exists(os.path.join(r1, "foobar.db")) e2 = SimpleExperiment2() r2 = e2(se=r1) if r1: shutil.rmtree(r1) if r2: shutil.rmtree(r2) print "success" versuchung-1.1/tests/database_mergetool/000077500000000000000000000000001242273412000205245ustar00rootroot00000000000000versuchung-1.1/tests/database_mergetool/test.py000066400000000000000000000062121242273412000220560ustar00rootroot00000000000000#!/usr/bin/python from versuchung.experiment import Experiment from versuchung.types import Integer from versuchung.database import Database, TableDict, Table, Database_SQlite_Merger import os class DatabaseGenerator(Experiment): inputs = {'mode': Integer(0) } outputs = {'keydict': TableDict(), "table2": Table([("version", "integer"), ("method", "text"), ("result", "text")], keys = ["version", "method"], conflict_strategy = "REPLACE")} def run(self): for i in range(0, self.mode.value + 3): self.keydict[str(i)] = "barfoo " + str(i) if self.mode.value == 0: self.table2.insert(version = 1, method = "GET", result = "404") # 1 self.table2.insert(version = 1, method = "GET", result = "404") # 2: replace 1 self.table2.insert(version = 1, method = "POST", result = "200")# 3 else: self.table2.insert(version = 1, method = "GET", result = "200") # 4: replace 2 self.table2.insert(version = 1, method = "GET", result = "300") # 5: replace 4 self.table2.insert(version = 1, method = "DROP", result = "404") # 6 self.table2.insert(version = 1, method = "POST", result = "200") # 7: replace 3 # After merging are in Database 7, 6, 5 if __name__ == "__main__": import shutil, sys e1 = DatabaseGenerator() r1 = e1(["--mode=0"]) e2 = DatabaseGenerator() r2 = e2(["--mode=10"]) merger = Database_SQlite_Merger("output.db", [e1.table2.database.path], logging = False) merger.merge() merger = Database_SQlite_Merger("output.db", [e2.table2.database.path], logging = False) merger.merge(update = True) merger = Database_SQlite_Merger("output.db", [e2.table2.database.path], logging = False) merger.merge(update = True) # Test the resulting database import sqlite3 conn = sqlite3.connect("output.db") cur = conn.cursor() # Checking table 2 cur.execute("SELECT * from DatabaseGenerator__table2") table2 = cur.fetchall() assert len(table2) == 3 assert all([x[0] == table2[0][0] for x in table2]) table2 = set([x[1:] for x in table2]) assert (1, "POST", "200") in table2 assert (1, "DROP", "404") in table2 assert (1, "GET", "300") in table2 # Checking Metadata cur.execute("SELECT * from metadata") metadata = cur.fetchall() metadata = dict([(x[0], eval(x[1])) for x in metadata]) assert metadata[e1.experiment_identifier]["mode"] == 0 assert metadata[e2.experiment_identifier]["mode"] == 10 # Checking Keydict cur.execute("SELECT * from DatabaseGenerator__keydict") keydict = cur.fetchall() keydict = dict([(x[1], x[2]) for x in keydict]) assert len(keydict) == 13 assert keydict['10'] == 'barfoo 10' cur.close() conn.close() if r1: shutil.rmtree(r1) if r2: shutil.rmtree(r2) os.unlink("output.db") print "success" versuchung-1.1/tests/directory_output/000077500000000000000000000000001242273412000203275ustar00rootroot00000000000000versuchung-1.1/tests/directory_output/test.py000066400000000000000000000017301242273412000216610ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String from versuchung.files import Directory import os class SimpleExperiment(Experiment): outputs = {"dir1": Directory("d1"), "dir2": Directory("d2")} def run(self): a = self.o.dir1.new_file("barfoo") a.value="abc" a.flush() os.mkdir(self.o.dir1.path + "/tmpdir") with open(self.o.dir1.path + "/tmpdir/foo", "w+") as fd: fd.write("Hallo") self.o.dir2.mirror_directory(self.o.dir1.path, lambda x: True) if __name__ == "__main__": import shutil, sys,os experiment = SimpleExperiment() dirname = experiment(sys.argv) assert os.path.isdir(experiment.o.dir2.path + "/tmpdir") assert os.path.exists(experiment.o.dir2.path + "/barfoo") assert os.path.exists(experiment.o.dir2.path + "/tmpdir/foo") if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/event_log/000077500000000000000000000000001242273412000166655ustar00rootroot00000000000000versuchung-1.1/tests/event_log/test.py000066400000000000000000000013011242273412000202110ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.events import EventLog class SimpleExperiment(Experiment): outputs = {"events": EventLog("events")} def run(self): shell = self.o.events.shell shell("sleep 0.5") shell("seq 1 100 | while read a; do echo > /dev/null; done") shell("sleep 0.5") assert len(self.o.events.value) == 9 # Runtime of sleep 0.5 should be about half a second assert int(self.o.events.value[2][3] * 10) in [4,5,6] if __name__ == "__main__": import shutil, sys experiment = SimpleExperiment() dirname = experiment(sys.argv) if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/experiment_getattr/000077500000000000000000000000001242273412000206155ustar00rootroot00000000000000versuchung-1.1/tests/experiment_getattr/test.py000066400000000000000000000017261242273412000221540ustar00rootroot00000000000000#!/usr/bin/python from versuchung.experiment import Experiment from versuchung.files import File from versuchung.types import String from versuchung.execute import shell import os class SimpleExperiment(Experiment): inputs = {'abc': File("/dev/null"), "xxx": File("/dev/null"), "empty": String(None)} outputs = {'xyz': File("asd"), "zzz": File("asd")} def run(self): assert self.abc == self.inputs.abc assert self.xyz == self.outputs.xyz exception = False try: self.xxx != None except AttributeError: exception = True assert exception == False assert self.empty.value is None if __name__ == "__main__": import shutil, sys experiment = SimpleExperiment() dirname = experiment(sys.argv) assert experiment.metadata["experiment-version"] == experiment.version if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/file_output/000077500000000000000000000000001242273412000172425ustar00rootroot00000000000000versuchung-1.1/tests/file_output/test.py000066400000000000000000000013621242273412000205750ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String from versuchung.files import File class SimpleExperiment(Experiment): inputs = {"input_key": String("default key"), "input_value": String("default value")} outputs = {"output_file": File("output")} def run(self): # Combine the input parameters content = self.inputs.input_key.value \ + ": " + self.inputs.input_value.value # write the result to the output file self.outputs.output_file.value = content + "\n" if __name__ == "__main__": import shutil, sys experiment = SimpleExperiment() dirname = experiment(sys.argv) if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/git_archive/000077500000000000000000000000001242273412000171675ustar00rootroot00000000000000versuchung-1.1/tests/git_archive/origin.tar.gz000066400000000000000000000153271242273412000216150ustar00rootroot00000000000000NN=MoIv^ vrlNAMKk2dS-yeɻdƳltwS2vE.Aln!d,)! ^Uu7?[xD6~^ʍlUhff5WjݴoTFV j8c7D$IGD]w¦-?@ѿD7 V6rmI޽[ro#%]?6#p)߮![R/ _D0~R`9WIZ^EO*3V0ΐXD0aIND{cv c;ሞw̒ 3~_3f&d~cAx De{z^80X!k`}#u%"tp<l w=g'%= bx2l1N@=|-df& f0|"qb y fY );`WTQj7m r?b~, { mTOܛ 1K"!XZ8I6OYkNQs:-VU4omm67j|cpDmS-ߧcDnN;I4e.x~p':q(c6 J.$"p wq8`^Lj+h4400Wg~8}yI`x`Xa]@ 3W'6jOv(2y 0LD4W 7ODd-Ip#?n0`~G٣T]]YeG$IT,1d2J@r`ƃ0?nJF:'i7qe9ABbYag v [լ(0>][.[{¬?>zZ]+JDYEa@ z&eSCo#ʁۀ؃ѱu"DM,PaHI*_@ďCH89( E s¦Rh1tܞ呄8 & ^ iZ~WHaZ)tJJ2>ZhJ .Cok"E?2_îv@_ e QK2{<ίx0|Ź"̢|ܚQJCјqY350W@.讥XhZ!k@srt8 kBiXw]K3KNvw K`Dv}qO4<8|/|CJW=]/o>-7V+fOpufl6M N>ݥLj+2[ V (NvȳמM%Kf9zGU=a A8_+{ΆCݪΉ8yZcF7Z_DWQ#TTFTmaPnc(MWh޺*9߮S_mVkK_Dq AP X&haHG0O5αr62{ܶBC N/>$ϚRS0 ,jʑQqqn^D' 4=Aـ>/y )vo\Q1; 'aqE_W9P?rA@ Bquc\)p"? ʹEi:t{'ӻeoq(pE0&/J$a"cy0-[{7H褧2dZ-JFv |\7GXk2ki},4mO>Q aQN" FD6:k%,  -OfUvݢ%m(L 9:.'c XuvQM$ӊc2 nY*1Ec[4]'Q L5yӎL[!敉@9:_eZ7c? T8@>psen@tfE C9,=K= H'_}1wRPx1e(轔eSb-$z Z9zf39?=GvZ)"O,ںh ZJzAL.oq-Oe$7X.}& $<{0? kSr2q7Y2ӫĪ% >iYW$3?,!ƁMV̎ֈ0Ļ%gs))V CxxSl!1GE*"@[Di/3$ F隇2QSlM sH XC`+1$.ϡ%pp.z4+ ŀ684Ӛ:A}=p‡PC?Ӧ71ce.oWQeV0Of]^fMoHx15jj(?}sʉ2۠1 t#H/:̭cIu.Kt?J˯C{GWW:ڜBڅ?eyäJ]T5 L(g谏;>3Vg2jKeB&È4$Ur=:t ±؏bBԙa ؛Fڝhl6 V庎*kmzm~6-Y8F]8nMrz"B_,0()$s&BG*g0a%MkzbYV =:z p4mnQZs^kOZ]Hh_q{V̫ՌXlQ(i5cՠ(r#l8@QlF6ZVp0,MtOՂ,R͝|N:OI99 FX"`8ҥ&&0&(Aq/pdM4V 0n~)S G4̕R*"bd%J} rF x9Tj3hH@l!8qPP !!X 05XJ88rSn_$9*,CnǡJG@&송)ZiN3&]*'Eg_cfXSYa+lR4cYJ +^ܖ̪@7 ft0 &ade)_+ @v&[%~uj6,S~Vi;+-8ݜY i2N8{P.;`8Ѡ ƊJN]>b2xR??!S^U y߮6^"UtLߤ#:\C,iTA5.1yWI-,N[I2 Aɖg[ ҋ/d^~=ۀ$Qe'rEAY(Iz)p A/%e}{^D/ʭ ~qHuAʉA舌0rR\^+v4? օ/H8 c-?y׺wx~>^~C^!˕3r!ŧ3A?dS:aPxԸ9t"YGMrvh2P9ir[ ;q<R;Ae`c!H{P,1$ھJV'WR: ruPK[5QJEVG%4P\'ԇAzY3   9TΒ^| c:Α㣈iH[UX>?J0fky@:Kွ"psSH#ҕ K3S_ a쓃"4ء"y%UB-]<7LP6[:@Jbӑr%&Riw(}"!&@P4BAxXUBM|!O^YIE>d4D9 V~tITI  Hy9Hc2_qD3]S7(ȕfөG[hYc^|(UMJ37 h/5(1eYSLO#*eg>c/|a$밽*S=̖cf{Vrtc_@ܟUSVA`H0^ Oߤ|߁ d2֒z#I4TA<(/uj6Ƹ/J("RWkKJӬu#xݨŔ֕/$@zx ‡hPs#gNC5!:˼oҹt{y`j`,mZD}Jh%nUhhc,,>i.Ү0xϿ'@l'8ɽ4'9NWu~-/ +]d۶=߶_٫_QSWnbZe;_W u _ӿvf,ПNBvӿՄ?K/ͧ< 5.OvZ,Ƈq_k&_eBZyڞ٨Ꝗ6-Q7*o6mѲNdȏ_X!{nx'/Dφۧ`&_#m XZt}q0xd<D)*SlTdc öH)OS,I2TDjcPnRhYsVSBh};TP7p"GYKUVBV$ڧKTo6;QS(CJd Ƴy ) 'WM!;Kp럎/łkkcJiE versuchung-1.1/tests/git_archive/test.py000066400000000000000000000015241242273412000205220ustar00rootroot00000000000000#!/usr/bin/python from versuchung.experiment import Experiment from versuchung.archives import TarArchive, GitArchive import os class GitArchiveTest(Experiment): inputs = {"git": GitArchive(TarArchive("origin.tar.gz")), "git_bare": GitArchive(TarArchive("origin.tar.gz"), shallow=True) } def run(self): directory = self.i.git.value assert set(["TEST", "ABC", ".git"]) == set(directory.value) directory = self.i.git_bare.value assert set(["TEST", "ABC"]) == set(directory.value) with self.i.git as path: assert path == self.i.git.value.path assert os.path.abspath(os.curdir) == path print "success" if __name__ == "__main__": import sys import shutil t = GitArchiveTest() dirname = t(sys.argv) shutil.rmtree(dirname) versuchung-1.1/tests/gzip_file/000077500000000000000000000000001242273412000166535ustar00rootroot00000000000000versuchung-1.1/tests/gzip_file/content.gz000066400000000000000000000000341242273412000206640ustar00rootroot00000000000000QaOs q kd~`versuchung-1.1/tests/gzip_file/test.py000066400000000000000000000013171242273412000202060ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.archives import GzipFile from versuchung.files import Directory class SimpleExperiment(Experiment): inputs = { "gz": GzipFile("content.gz") } outputs = {"gz_out": GzipFile("content.gz") } def run(self): with self.tmp_directory as d: assert self.tmp_directory.path in self.gz.path assert self.gz.value.strip() == "CONTENT" self.gz_out.value = "OUTPUT" if __name__ == "__main__": import shutil, sys experiment = SimpleExperiment() dirname = experiment(sys.argv) assert len(open(experiment.gz_out.path).read()) > 0 if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/list_parameter/000077500000000000000000000000001242273412000177165ustar00rootroot00000000000000versuchung-1.1/tests/list_parameter/test.py000066400000000000000000000017321242273412000212520ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String, List class SimpleExperiment(Experiment): inputs = {"strings": List(String(), default_value=[]), "default": List(String, default_value=[String("foo")]), "default2": List(String, default_value=[String("foo")])} def run(self): strings = [s.value for s in self.i.strings] assert strings == ["x86", "sparc"] default = [s.value for s in self.i.default] assert default == ["foo"] default2 = [s.value for s in self.i.default2] assert default2 == ["bar"] assert self.metadata["strings-0"] == "x86" assert self.metadata["strings-1"] == "sparc" if __name__ == "__main__": import shutil experiment = SimpleExperiment() strings = ["--strings", "x86", "--strings", "sparc", "--default2", "bar"] dirname = experiment(strings) if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/list_parameter_lambda/000077500000000000000000000000001242273412000212165ustar00rootroot00000000000000versuchung-1.1/tests/list_parameter_lambda/test.py000066400000000000000000000040561242273412000225540ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String, List from versuchung.files import File from versuchung.archives import GzipFile from versuchung.search import search_experiment_results def find_results(): return search_experiment_results(SimpleExperiment, ".") class SimpleExperiment(Experiment): inputs = {"input_key": String("default key"), "input_value": String("default value")} outputs = {"output_file": File("output"), "gzip": GzipFile("foo.gz") } def run(self): # Combine the input parameters content = self.inputs.input_key.value \ + ": " + self.inputs.input_value.value # write the result to the output file self.outputs.output_file.value = content + "\n" self.gzip.value = "BAR" class SimpleExperiment2(Experiment): inputs = {"se": lambda x: List(SimpleExperiment(), default_value = find_results())} def run(self): assert type(self.se.static_experiment) == SimpleExperiment2 assert type(self.se[0].static_experiment) == SimpleExperiment assert type(self.se.dynamic_experiment) == SimpleExperiment2 assert type(self.se[0].dynamic_experiment) == SimpleExperiment2 assert type(self.se[0].output_file.static_experiment) == SimpleExperiment assert type(self.se[0].output_file.dynamic_experiment) == SimpleExperiment2 assert self.se[0].output_file.tmp_directory.path for i in self.se: assert "abc:" in i.output_file.value assert i.gzip.value == "BAR" if __name__ == "__main__": import shutil dirs_to_del = [] experiment = SimpleExperiment() dirname = experiment(input_key="abc", input_value="1") dirs_to_del.append(dirname) experiment = SimpleExperiment() dirname = experiment(input_key="abc", input_value="2") dirs_to_del.append(dirname) experiment = SimpleExperiment2() dirname = experiment() dirs_to_del.append(dirname) for dirname in dirs_to_del: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/machine_monitor/000077500000000000000000000000001242273412000200565ustar00rootroot00000000000000versuchung-1.1/tests/machine_monitor/test.py000066400000000000000000000013201242273412000214030ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.execute import shell, MachineMonitor class SimpleExperiment(Experiment): outputs = {"ps": MachineMonitor("monitor", tick_interval=10)} def run(self): shell("sleep 0.5") shell("seq 1 100 | while read a; do echo > /dev/null; done") shell("sleep 0.5") if __name__ == "__main__": import shutil, sys try: import psutil if not "phymem_usage" in dir(psutil): print "skipped" sys.exit(0) except: print "skipped" sys.exit(0) experiment = SimpleExperiment() dirname = experiment(sys.argv) if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/run_shell/000077500000000000000000000000001242273412000166765ustar00rootroot00000000000000versuchung-1.1/tests/run_shell/test.py000066400000000000000000000014221242273412000202260ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.execute import shell, shell_failok, CommandFailed import sys class ShellExperiment(Experiment): def run(self): shell.track(self.path) shell("date") try: shell("/bin/false") # should always raise the exception assert False except CommandFailed: pass # this must not fail the experiment shell_failok("/bin/false") assert (['2 23'], 0) == shell("echo %(foo)s %(bar)s", {"foo": "2", "bar": "23"}) shell("cat %s", __file__) if __name__ == "__main__": import shutil experiment = ShellExperiment() dirname = experiment(sys.argv) print "success" if dirname: shutil.rmtree(dirname) versuchung-1.1/tests/start_end_date/000077500000000000000000000000001242273412000176635ustar00rootroot00000000000000versuchung-1.1/tests/start_end_date/test.py000066400000000000000000000006321242273412000212150ustar00rootroot00000000000000from versuchung.experiment import Experiment import time class SimpleExperiment(Experiment): def run(self): time.sleep(0.1) if __name__ == "__main__": import shutil, sys,os experiment = SimpleExperiment() dirname = experiment(sys.argv) assert experiment.metadata["date-start"] != experiment.metadata["date-end"] if dirname: shutil.rmtree(dirname) print "success" versuchung-1.1/tests/tar_archive/000077500000000000000000000000001242273412000171725ustar00rootroot00000000000000versuchung-1.1/tests/tar_archive/test.py000066400000000000000000000011031242273412000205160ustar00rootroot00000000000000#!/usr/bin/python from versuchung.experiment import Experiment from versuchung.archives import TarArchive class TarArchiveText(Experiment): inputs = {"tar": TarArchive("test.tar.gz")} def run(self): with self.tmp_directory as path: directory = self.i.tar.value assert len(directory.value) == 2 assert "ABC" in directory.value assert "Hallo" in directory.value print "success" if __name__ == "__main__": import sys import shutil t = TarArchiveText() dirname = t(sys.argv) shutil.rmtree(dirname) versuchung-1.1/tests/tar_archive/test.tar.gz000066400000000000000000000002451242273412000213010ustar00rootroot00000000000000GNӽ 0@(y?ZB o# Bu oC7pȜ M M~/bLLQ{m^Tֱ(%kjL:Լ?O]wGD鮯zp%wS6y{W(versuchung-1.1/tests/tex_output/000077500000000000000000000000001242273412000171235ustar00rootroot00000000000000versuchung-1.1/tests/tex_output/test.py000066400000000000000000000017731242273412000204640ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.tex import * class TexTest(Experiment): outputs = {"tex": Macros("macro.tex"), "pgf": PgfKeyDict("pgf.tex"), "dref": DatarefDict("dref.tex") } def run(self): tex = self.o.tex tex.macro("foo", "bar") tex.newline() tex.comment("barfoo") pgf = self.o.pgf pgf["foobar"] = 23 self.dref["foobar"] = 42 if __name__ == "__main__": import sys import shutil t = TexTest() dirname = t(sys.argv) with open(dirname + "/macro.tex") as fd: content = fd.read() assert r'\newcommand{\foo} {bar}' in content assert "% barfoo" in content pgf = PgfKeyDict(dirname + "/pgf.tex") a = pgf.value assert len(pgf) == 1 assert pgf["foobar"] == "23" dref = DatarefDict(dirname + "/dref.tex") a = dref.value assert len(dref) == 1 assert dref["foobar"] == "42" shutil.rmtree(dirname) print "success" versuchung-1.1/tests/two_experiments/000077500000000000000000000000001242273412000201375ustar00rootroot00000000000000versuchung-1.1/tests/two_experiments/test.py000066400000000000000000000022421242273412000214700ustar00rootroot00000000000000from versuchung.experiment import Experiment from versuchung.types import String from versuchung.files import File class SimpleExperiment(Experiment): inputs = {"input_key": String("default key"), "input_value": String("default value")} outputs = {"output_file": File("output")} def run(self): # Combine the input parameters content = self.inputs.input_key.value \ + ": " + self.inputs.input_value.value # write the result to the output file self.outputs.output_file.value = content + "\n" class SimpleExperiment2(Experiment): inputs = {"se": SimpleExperiment()} outputs = {"key": File("key") } def run(self): content = "%s: %s\n" %(self.i.se.metadata["input_key"], self.i.se.metadata["input_value"]) assert content == self.i.se.o.output_file.value assert self.metadata["experiment-name"] == self.title if __name__ == "__main__": import shutil, sys e1 = SimpleExperiment() r1 = e1([]) e2 = SimpleExperiment2() r2 = e2(se=r1) if r1: shutil.rmtree(r1) if r2: shutil.rmtree(r2) print "success"