././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5196893 logilab-constraint-1.0/0000755000000000000000000000000014554256110013706 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/CHANGELOG.md0000666000000000000000000000305614554256055015537 0ustar00rootroot## Version 1.0 (2024-01-24) ### 🎉 New features - pkginfo: depends on logilab-common 2.x ## Version 0.7.1 (2023-11-30) ### 👷 Bug fixes - setup.py: ensure we correctly shit the packages files ## Version 0.7.0 (2023-11-30) ### 🎉 New features - run flynt on the code base to convert everything into f-strings ### 🤖 Continuous integration - add safety job - add twine-check job - disable from forge and triggering other pipelines ### 🤷 Various changes - add .readthedocs.yaml ## Version 0.6.2 (2022-06-07) ### 👷 Bug fixes - check-manifest: include CHANGELOG.md ## Version 0.6.1 (2022-06-07) ### 👷 Bug fixes - it's 2021 let's use utf-8 - rql repo has been moved ### 📝 Documentation - licence: update licence dates ### 🤖 Continuous integration - add .cube-doctor.yml - add check-dependencies-resolution - add pytest-caputre-deprecatedwarnings - integrate pytest-deprecated-warnings - make py3 jobs interruptible - migrate to v2 of gitlab ci templates - use templates - add a gitlab-ci.yml based on tox - add super basic tox.ini, project is broken anyway - gitlab-ci/fix: forgot to pass `TRIGGERED_FROM_OTHER_PROJECT` variable to other pipelines - gitlab-ci: add py3-from-forge pipeline - gitlab-ci: makes curl fails on bad http code and display it - gitlab-ci: refactor to use except:variables instead of bash if - pkg: include `__pkginfo__.py` in sdist tarball - tests: trigger rql builds from logilab-constraint if all other tests passed - tox/fix: missing -U in pip install in from-forge - use new gitlab syntax for triggering other pipeline ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/COPYING0000666000000000000000000004310314554256055014756 0ustar00rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/COPYING.LESSER0000666000000000000000000006363714554256055015770 0ustar00rootroot GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/ChangeLog0000666000000000000000000000350114554256055015473 0ustar00rootrootChangeLog for logilab.constraint ================================ 2015-07-06 -- 0.6.0 * python3 support 2012-03-29 -- 0.5.0 * drop pscysupport (#90272) * make FiniteDomain inherits from set builting (#89865) * test fixes 2008-08-07 -- 0.4.0 * allow capture of solver output 2005-09-05 -- 0.3.0 * Added finite interval domains and constraints in module constraint.fi * constraint now depends on logilab.common to support a larger number of python versions * Optimisation of finite domains by using copy on write * Better heuristics for constraint queuing 2005-06-17 -- 0.2.7 * Added fd.InSet special constraint that tests for set inclusion * bumped copyright * pylint fixes 2004-12-22 -- 0.2.6 * Dropped support for python2.2, added support for python2.4 * Optimized version of Expression and BinaryExpression, as well as several other optimizations lead to increased performance (money2 runs almost 40% faster with the new release, queens about 20%) * Optimizations in the search algorithm leads to important speedups when only looking for a single solution (instead of performing an exhaustive search of all solutions) * Added a warning when psyco cannot be loaded 2004-06-13 -- 0.2.5 * logilab/debian packaging * New constraint AllDistinct with linear narrowing time * updated unit tests * updated send+more=money example * added RandomizingDistributor 2002-10-16 -- 0.2.3 * New distributors SplitDistributor and EnumeratorDistributor * fast solution in examples/menza2.py * Dichotomy distributors can now split domains in more than two parts. * added timestamps to log messages * updated queens.py to use the new EnumeratorDistributor (25% speed increase) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/MANIFEST.in0000666000000000000000000000066714554256055015471 0ustar00rootrootinclude tox.ini recursive-include doc *.xml recursive-include doc *.html include doc/* include ChangeLog include COPYING include COPYING.LESSER include README.rst recursive-include examples *.py recursive-include logilab *.py include __pkginfo__.py include test/__profile__.py exclude announce.txt exclude .yamllint exclude .gitlab-ci.yml exclude .cube-doctor.yml exclude .hg-format-source exclude .readthedocs.yaml include CHANGELOG.md ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5156891 logilab-constraint-1.0/PKG-INFO0000644000000000000000000000271214554256110015005 0ustar00rootrootMetadata-Version: 2.1 Name: logilab-constraint Version: 1.0 Summary: constraints satisfaction solver in Python Home-page: http://www.logilab.org/projects/logilab-constraint Author: Alexandre Fayolle Author-email: contact@logilab.fr License: LGPL Classifier: Topic :: Scientific/Engineering Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 License-File: COPYING License-File: COPYING.LESSER Requires-Dist: setuptools Requires-Dist: logilab-common<3.0.0,>=2.0.0 Requires-Dist: six>=1.4.0 Requires-Dist: importlib_metadata; python_version < "3.10" This package implements an extensible constraint satisfaction problem solver written in pure Python, using constraint propagation algorithms. The logilab.constraint module provides finite domains with arbitrary values, finite interval domains, and constraints which can be applied to variables linked to these domains. It requires python 2.6 or later to work, and is released under the GNU Lesser General Public License. The documentation is in the doc/ directory. Examples are in the examples/ directory. Discussion about constraint should take place on the python-projects mailing list. Information on subscription and mailing list archives can be accessed at https://lists.logilab.org/mailman/listinfo/python-projects/ Your feedback is very valuable to us. Please share your experience with other users of the package on the mailing list. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/README.rst0000666000000000000000000000151614554256055015414 0ustar00rootrootThis package implements an extensible constraint satisfaction problem solver written in pure Python, using constraint propagation algorithms. The logilab.constraint module provides finite domains with arbitrary values, finite interval domains, and constraints which can be applied to variables linked to these domains. It requires python 2.6 or later to work, and is released under the GNU Lesser General Public License. The documentation is in the doc/ directory. Examples are in the examples/ directory. Discussion about constraint should take place on the python-projects mailing list. Information on subscription and mailing list archives can be accessed at https://lists.logilab.org/mailman/listinfo/python-projects/ Your feedback is very valuable to us. Please share your experience with other users of the package on the mailing list. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/__pkginfo__.py0000666000000000000000000000404714554256055016532 0ustar00rootroot# pylint: disable-msg=W0622 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . modname = "constraint" distname = "logilab-constraint" numversion = (1, 0) version = ".".join(map(str, numversion)) license = "LGPL" copyright = """Copyright (c) 2002-2010 LOGILAB S.A. (Paris, FRANCE). http://www.logilab.fr/ -- mailto:contact@logilab.fr""" description = "constraints satisfaction solver in Python" long_desc = """Extensible constraint satisfaction problem solver written in pure Python, using constraint propagation algorithms. The logilab.constraint module provides finite domains with arbitrary values, finite interval domains, and constraints which can be applied to variables linked to these domains. """ author = "Alexandre Fayolle" author_email = "contact@logilab.fr" web = f"http://www.logilab.org/projects/{distname}" mailinglist = "http://lists.logilab.org/mailman/listinfo/python-logic/" subpackage_of = "logilab" classifiers = [ "Topic :: Scientific/Engineering", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ] install_requires = [ "setuptools", "logilab-common >= 2.0.0, < 3.0.0", "six >= 1.4.0", 'importlib_metadata; python_version < "3.10"', ] tests_require = [] ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1706122311.503689 logilab-constraint-1.0/doc/0000755000000000000000000000000014554256110014453 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/doc/CONTRIBUTORS0000666000000000000000000000016414554256055016350 0ustar00rootrootAlexandre Fayolle: core coding Herb Schilling: documentation proof reading Terry Reedy: documentation proof reading ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/doc/documentation.html0000666000000000000000000002533514554256055020236 0ustar00rootrootConstraint Propagation in Python

Constraint Propagation in Python


Constraint Propagation in Python

Alexandre Fayolle


Copyright 2002 by Logilab

This manual presents how to use the constraint package to solve constraint propagation problems in Python. It also presents the the extension mechanisms available in the package

1. Using the constraint package

1.1. Sample problem

Let's take a real-life problem to get started. You're organising a an international Python Programming event, and you have to schedule conferences. There are 10 different conferences, you have 3 conference rooms available during 2 days. Each conference is 4 hours long, so you can organize at most 2 conferences per day in a given room.

Conferences 3, 4, 5 and 6 have to take place in room C, because it's the only one with Internet access.

Some of the speakers are not available on both days, so conferences 1, 5 and 10 have to take place on day 1, and conferences 2, 3 4 and 9 on day 2.

You have made a quick poll over the python mailing list, and it turns out that people attending some of the conferences are likely to be attending some other conferences too, so you want to make sure that such conferences are not scheduled at the same time. A careful statistical study has found 4 groups of potential attendees. The first group want to attend conferences 1, 2, 3 and 10, the second conferences 2, 6, 8 and 9 the third group conferences 3, 5, 6 and 7, and the last group conferences 1, 3, 7 and 8.

You've tried to put this on a whiteboard, but this quickly proved to be tedious, so you thought about using the constraint solving package.

1.2. Variables, Domains and Constraints

The first thing to find out in order to use the constraint package is what the variables are, what their domains are and what the constraints between variables are.

If we look at our problem, the variables are the conferences' room and time slot, and for each conference, the domain is the cross product of the set of available rooms with the set of available time slots. We could say that the conferences which require Internet access have a different domain, because they need to be in room C. This is perfectly valid. However, we will model this as a constraint.

Variables are manipulated as names, stored in character strings. Domains are instances of the fd.FiniteDomain class, which is instantiated with a list of values. Domains are manipulated through a dictionnary mapping a variable to its domain. Do not use the same domain instance for several variables, because in the current implementation, this is guaranteed to break. The code looks like this:

# import Repository class and fd module, 
from logilab.constraint import *
variables = ('c01','c02','c03','c04','c05','c06','c07','c08','c09','c10')
values = [(room,slot) 
          for room in ('room A','room B','room C') 
          for slot in ('day 1 AM','day 1 PM','day 2 AM','day 2 PM')]
domains = {}
for v in variables:
    domains[v]=fd.FiniteDomain(values)

Constraints, like domains are objects. So far the only class that can be used is fd.Expression and fd.BinaryExpression. We use the fd.make_expression factory function to build an instance of the right class, depending on the number of variables that is passed. This function takes a list of affected variables and a python expression that evaluates to true if the constraint is satisfied.

We have several constraints on our variables. First some conferences need to take place in room C:

constraints = []
for conf in ('c03','c04','c05','c06'):
    constraints.append(fd.make_expression((conf,),
                                          "%s[0] == 'room C'"%conf))

Availability of the speakers impose some more constraints:

for conf in ('c01','c05','c10'):
    constraints.append(fd.make_expression((conf,),
                                          "%s[1].startswith('day 1')"%conf))
for conf in ('c02','c03','c04','c09'):
    constraints.append(fd.make_expression((conf,),
                                          "%s[1].startswith('day 2')"%conf))

Then we want to say that some of the conferences should not be scheduled at the same time:

groups = (('c01','c02','c03','c10'),
          ('c02','c06','c08','c09'),
          ('c03','c05','c06','c07'),
          ('c01','c03','c07','c08'))
for g in groups:
    for conf1 in g:
        for conf2 in g:
            if conf2 > conf1:
                constraints.append(fd.make_expression((conf1,conf2),
                                                      '%s[1] != %s[1]'%\
                                                        (conf1,conf2)))

Finally, no two conferences can be scheduled in the same room at the same time:

for conf1 in variables:
    for conf2 in variables:
        if conf2 > conf1:
            constraints.append(fd.make_expression((conf1,conf2),
                                                  '%s != %s'%(conf1,conf2)))

1.3. The Repository class

Repository objects are used to hold the variables, domains and constraints describing the problem. A Solver object can solve the problem described by a Repository.

Here's the final touch:

r = Repository(variables,domains,constraints)
solutions = Solver().solve(r)
print solutions

The code is available in the file conferences.py in the examples directory of the distribution. It finds 64 possible schedules in a couple of seconds on my machine.

1.4. Performance considerations

There is still a lot of things to be worked on with this package. Here are a few tips that can help you to use it in its current state:

  • Try to avoid constraints with a lot of variables. It is better to have several binary constraints than one big N-ary constraint with several 'and' conditions

  • If you cannot avoid constraint with lots of variable, put the constraints with less variables first in the list, because they will get evaluated before, will take less time to process, and will hopefully reduce the domains of the variables playing a role in your big constraints

2. Extending the constraint package

WRITE ME!

././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/doc/documentation.xml0000666000000000000000000002506314554256055020070 0ustar00rootroot
Constraint Propagation in Python Alexandre Fayolle This manual presents how to use the constraint package to solve constraint propagation problems in Python. It also presents the the extension mechanisms available in the package 2002-2005Logilab $Revision: 1.6 $ $Date: 2005-09-05 15:56:26 $ $Author: alf $ Using the constraint package Sample problem Let's take a real-life problem to get started. You're organising a an international Python Programming event, and you have to schedule conferences. There are 10 different conferences, you have 3 conference rooms available during 2 days. Each conference is 4 hours long, so you can organize at most 2 conferences per day in a given room. Conferences 3, 4, 5 and 6 have to take place in room C, because it's the only one with Internet access. Some of the speakers are not available on both days, so conferences 1, 5 and 10 have to take place on day 1, and conferences 2, 3 4 and 9 on day 2. You have made a quick poll over the python mailing list, and it turns out that people attending some of the conferences are likely to be attending some other conferences too, so you want to make sure that such conferences are not scheduled at the same time. A careful statistical study has found 4 groups of potential attendees. The first group want to attend conferences 1, 2, 3 and 10, the second conferences 2, 6, 8 and 9 the third group conferences 3, 5, 6 and 7, and the last group conferences 1, 3, 7 and 8. You've tried to put this on a whiteboard, but this quickly proved to be tedious, so you thought about using the constraint solving package. Variables, Domains and Constraints The first thing to find out in order to use the constraint package is what the variables are, what their domains are and what the constraints between variables are. If we look at our problem, the variables are the conferences' room and time slot, and for each conference, the domain is the cross product of the set of available rooms with the set of available time slots. We could say that the conferences which require Internet access have a different domain, because they need to be in room C. This is perfectly valid. However, we will model this as a constraint. Variables are manipulated as names, stored in character strings. Domains are instances of the fd.FiniteDomain class, which is instantiated with a list of values. Domains are manipulated through a dictionnary mapping a variable to its domain. Do not use the same domain instance for several variables, because in the current implementation, this is guaranteed to break. The code looks like this: # import Repository class and fd module, from logilab.constraint import * variables = ('c01','c02','c03','c04','c05','c06','c07','c08','c09','c10') values = [(room,slot) for room in ('room A','room B','room C') for slot in ('day 1 AM','day 1 PM','day 2 AM','day 2 PM')] domains = {} for v in variables: domains[v]=fd.FiniteDomain(values) Constraints, like domains are objects. So far the only class that can be used is fd.Expression and fd.BinaryExpression. We use the fd.make_expression factory function to build an instance of the right class, depending on the number of variables that is passed. This function takes a list of affected variables and a python expression that evaluates to true if the constraint is satisfied. We have several constraints on our variables. First some conferences need to take place in room C: constraints = [] for conf in ('c03','c04','c05','c06'): constraints.append(fd.make_expression((conf,), "%s[0] == 'room C'"%conf)) Availability of the speakers impose some more constraints: for conf in ('c01','c05','c10'): constraints.append(fd.make_expression((conf,), "%s[1].startswith('day 1')"%conf)) for conf in ('c02','c03','c04','c09'): constraints.append(fd.make_expression((conf,), "%s[1].startswith('day 2')"%conf)) Then we want to say that some of the conferences should not be scheduled at the same time: groups = (('c01','c02','c03','c10'), ('c02','c06','c08','c09'), ('c03','c05','c06','c07'), ('c01','c03','c07','c08')) for g in groups: for conf1 in g: for conf2 in g: if conf2 > conf1: constraints.append(fd.make_expression((conf1,conf2), '%s[1] != %s[1]'%\ (conf1,conf2))) Finally, no two conferences can be scheduled in the same room at the same time: for conf1 in variables: for conf2 in variables: if conf2 > conf1: constraints.append(fd.make_expression((conf1,conf2), '%s != %s'%(conf1,conf2))) The Repository class Repository objects are used to hold the variables, domains and constraints describing the problem. A Solver object can solve the problem described by a Repository. Here's the final touch: r = Repository(variables,domains,constraints) solutions = Solver().solve(r) print solutions The code is available in the file conferences.py in the examples directory of the distribution. It finds 64 possible schedules in a couple of seconds on my machine. Performance considerations There is still a lot of things to be worked on with this package. Here are a few tips that can help you to use it in its current state: Try to avoid constraints with a lot of variables. It is better to have several binary constraints than one big N-ary constraint with several 'and' conditions If you cannot avoid constraint with lots of variable, put the constraints with less variables first in the list, because they will get evaluated before, will take less time to process, and will hopefully reduce the domains of the variables playing a role in your big constraints Extending the constraint package WRITE ME!
././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/doc/makefile0000666000000000000000000000063014554256055016166 0ustar00rootroot#MKHTML=mkdoc #MKHTMLOPTS=--doctype book --param toc.section.depth=2 --target html --stylesheet single-file #SRC=. #TXTFILES:= $(wildcard *.txt) #TARGET := $(TXTFILES:.txt=.html) all: apydoc #%.html: %.txt # ${MKHTML} ${MKHTMLOPTS} $< apydoc: epydoc -o apidoc --html -v --graph all --no-private --exclude="__pkginfo__" --exclude="setup" -n "Logilab's common library" ../ clean: rm -rf apidoc ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1706122311.507689 logilab-constraint-1.0/examples/0000755000000000000000000000000014554256110015524 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/chess.py0000666000000000000000000000543614554256055017227 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Chess constraints and domains""" from logilab.constraint import fd from logilab.constraint.propagation import AbstractConstraint, ConsistencyFailure class ChessDomain(fd.FiniteDomain): def __init__(self, size): values = [(i, j) for i in range(size) for j in range(size)] fd.FiniteDomain.__init__(self, values) def __repr__(self): vals = self.getValues() vals.sort() return f"" class QueensConstraint(AbstractConstraint): def __init__(self, variables): AbstractConstraint.__init__(self, variables) def __repr__(self): return f"" def narrow(self, domains): maybe_entailed = 1 var1 = self._variables[0] dom1 = domains[var1] values1 = dom1.getValues() var2 = self._variables[1] dom2 = domains[var2] values2 = dom2.getValues() keep1 = {} keep2 = {} maybe_entailed = 1 for val1 in values1: val1_0 = val1[0] val1_1 = val1[1] for val2 in values2: if val1 in keep1 and val2 in keep2 and maybe_entailed == 0: continue val2_0 = val2[0] val2_1 = val2[1] if ( val1_0 < val2_0 and val1_1 != val2_1 and abs(val1_0 - val2_0) != abs(val1_1 - val2_1) ): keep1[val1] = 1 keep2[val2] = 1 else: maybe_entailed = 0 try: dom1.removeValues([val for val in values1 if val not in keep1]) dom2.removeValues([val for val in values2 if val not in keep2]) except ConsistencyFailure: raise ConsistencyFailure(f"Inconsistency while applying {repr(self)}") except Exception: print(self) raise return maybe_entailed ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/conferences.py0000666000000000000000000000456514554256055020416 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . # import Repository, ListDomain and MathematicConstraint from logilab.constraint import fd, Repository, Solver variables = ("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10") values = [ (room, slot) for room in ("room A", "room B", "room C") for slot in ("day 1 AM", "day 1 PM", "day 2 AM", "day 2 PM") ] domains = {} for v in variables: domains[v] = fd.FiniteDomain(values) constraints = [] # Internet access is in room C only for conf in ("c03", "c04", "c05", "c06"): constraints.append(fd.make_expression((conf,), f"{conf}[0] == 'room C'")) # Speakers only available on day 1 for conf in ("c01", "c05", "c10"): constraints.append(fd.make_expression((conf,), f"{conf}[1].startswith('day 1')")) # Speakers only available on day 2 for conf in ("c02", "c03", "c04", "c09"): constraints.append(fd.make_expression((conf,), f"{conf}[1].startswith('day 2')")) # try to satisfy people willing to attend several conferences groups = ( ("c01", "c02", "c03", "c10"), ("c02", "c06", "c08", "c09"), ("c03", "c05", "c06", "c07"), ("c01", "c03", "c07", "c08"), ) for g in groups: for conf1 in g: for conf2 in g: if conf2 > conf1: print(f"{conf1}[1] != {conf2}[1]") constraints.append( fd.make_expression((conf1, conf2), f"{conf1}[1] != {conf2}[1]") ) constraints.append(fd.AllDistinct(variables)) r = Repository(variables, domains, constraints) solutions = Solver().solve(r) print(solutions) print(len(solutions)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/intervals.py0000666000000000000000000000463214554256055020126 0ustar00rootroot#!/usr/bin/python # copyright 2002-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """ Example problem with intervals """ from logilab.constraint import Repository, Solver, fi def intervals(size=5, verbose=0): variables = [] domains = {} constraints = [] for i in range(size): name = "v%02d" % i variables.append(name) domains[name] = fi.FiniteIntervalDomain(0, size * 5, 5) for i, q1 in enumerate(variables): if i + 1 == len(variables): continue q2 = variables[i + 1] c = fi.StartsAfterEnd(q1, q2) constraints.append(c) # print domains # print constraints r = Repository(variables, domains, constraints) yield from Solver(fi.FiniteIntervalDistributor()).solve_all(r, verbose) def main(args=None): import sys import getopt if args is None: args = sys.argv[1:] opts, args = getopt.getopt(args, "dvf") display = 0 verbose = 0 first = 0 if args: size = int(args[0]) else: size = 8 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 1 elif o == "-f": first = 1 count = 0 for sol in intervals(size, verbose): count += 1 if display: print(sol) print("*" * 80) if first: break if not display: print("Use -d option to display solutions") print(count, "solutions found.") if __name__ == "__main__": # import hotshot # p = hotshot.Profile('/tmp/queens.prof') # p.runcall(main) # p.close() main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/knights.py0000666000000000000000000000757214554256055017574 0ustar00rootroot#!/usr/bin/env python2.3 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Knight tour problem: Place n*n values on a checker so that consecutive values are a knight's move away from each other""" from logilab.constraint import fd, Repository, Solver from logilab.constraint.distributors import EnumeratorDistributor def knight_tour(size=6, verbose=0): variables = [] domains = {} constraints = [] black_checker = [] # the black tiles white_checker = [] # the white tiles: one less if n is odd for row in range(size): for column in range(size): if (row + column) % 2 == 0: black_checker.append((row, column)) else: white_checker.append((row, column)) # One variable for each step in the tour for i in range(size * size): name = "x%02d" % i variables.append(name) # The knight's move jumps from black to white # and vice versa, so we make all the even steps black # and all the odd ones white. if i % 2 == 0: domains[name] = fd.FiniteDomain(black_checker) else: domains[name] = fd.FiniteDomain(white_checker) if i > 0: j = i - 1 k1 = "x%02d" % j k2 = "x%02d" % i # the knight's move constraint c = fd.make_expression( (k1, k2), "abs(%(v1)s[0]-%(v2)s[0]) + abs(%(v1)s[1]-%(v2)s[1]) == 3" % {"v1": k1, "v2": k2}, ) constraints.append(c) c = fd.make_expression( (k1, k2), "abs(abs(%(v1)s[0]-%(v2)s[0]) - abs(%(v1)s[1]-%(v2)s[1])) == 1" % {"v1": k1, "v2": k2}, ) constraints.append(c) constraints.append(fd.AllDistinct(variables)) r = Repository(variables, domains, constraints) sol = Solver(EnumeratorDistributor()).solve_one(r, verbose) return sol def draw_solution(sol, size): # change the keys into elements, elements into keys # to display the results. # I'm sure there's a better way to do this, but I'm # new to python board = "" board += "_" * (size * 3 + 1) + "\n" squares = {} for t in sol.items(): squares[(t[1][0] * size) + t[1][1]] = t[0] for i in range(size): for j in range(size): # find the variable whose value is (i,j) square = squares[i * size + j] # numbering should start from 1 ,not 0 intsquare = int(square[1:4]) + 1 board += "|%02s" % intsquare board += "|\n" board += "¯" * (size * 3 + 1) + "\n" print(board) if __name__ == "__main__": import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") display = 0 verbose = 0 if args: size = int(args[0]) else: size = 6 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 2 count = 0 sol = knight_tour(size, verbose) if display: print("Solution found:") draw_solution(sol, size) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/menza.py0000666000000000000000000000545314554256055017233 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """ Solve a puzzle that got discussed on c.l.p. on october 2002 ABC*DE=FGHIJ with all letters different and in domain [0,9] """ from logilab.constraint import fd, Repository, Solver from logilab.constraint.propagation import BasicConstraint class DistinctDigits(BasicConstraint): def __init__(self, variable): BasicConstraint.__init__(self, variable, None, None) def narrow(self, domains): domain = domains[self._variable] for v in domain.getValues(): s = str(v) for d in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): if s.count(d) not in (0, 1): domain.removeValue(v) break return 1 def __repr__(self): return f"" def menza(): """ """ VARS = "ab" variables = list(VARS) domains = {} constraints = [] domains["a"] = fd.FiniteDomain(range(0, 1000)) domains["b"] = fd.FiniteDomain(range(0, 100)) me = fd.make_expression for v in variables: constraints.append(DistinctDigits(v)) dist = ["10000 < a*b "] for digit in range(10): dist.append('("%%.3d%%.2d%%.5d" %% (a,b,a*b)).count("%d")==1' % digit) constraints.append(me(("a", "b"), " and ".join(dist))) r = Repository(variables, domains, constraints) return r if __name__ == "__main__": import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") verbose = 0 display = 0 create_problem = menza for o, v in opts: if o == "-v": verbose += 1 elif o == "-d": display = 1 r = create_problem() print("problem created. let us solve it.") s = [] for sol in Solver().solve_all(r, verbose): s.append(sol) if display: sol["c"] = sol["a"] * sol["b"] print(f"{sol['a']} x {sol['b']} = {sol['c']}") if not display: print(f"Found {len(s)} solutions") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/menza2.py0000666000000000000000000000621414554256055017311 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """ Solve a puzzle that got discussed on c.l.p. on october 2002 ABC*DE=FGHIJ with all letters different and in domain [0,9] """ from logilab.constraint import fd, Repository, Solver from logilab.constraint.propagation import BasicConstraint, ConsistencyFailure class DistinctDigits(BasicConstraint): def __init__(self, variable): BasicConstraint.__init__(self, variable, None, None) def narrow(self, domains): domain = domains[self._variable] try: for v in domain.getValues(): s = str(v) for d in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): if s.count(d) not in (0, 1): domain.removeValue(v) break except ConsistencyFailure: raise ConsistencyFailure(f"inconsistency while applying {repr(self)}") return 1 def __repr__(self): return "" def mensa(): """ ABC*DE=FGHIJ with all letters different and in domain [0,9] """ VARS = "xy" variables = list(VARS) domains = {} constraints = [] # x = ABC and y = DE, x*y = FGHIJ domains["x"] = fd.FiniteDomain(range(0, 1000)) domains["y"] = fd.FiniteDomain(range(0, 100)) # x and y *must* have distinct digits themselves # (for example this will remove 232 from x's domain) for v in variables: constraints.append(DistinctDigits(v)) # x,y and x*y must have distinct digits dist = [] for digit in range(10): dist.append('("%%.3d%%.2d%%.5d" %% (x,y,x*y)).count("%d")==1' % digit) c = " and ".join(dist) constraints.append(fd.make_expression(("x", "y"), c)) r = Repository(variables, domains, constraints) return r if __name__ == "__main__": import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") verbose = 0 display = 0 for o, v in opts: if o == "-v": verbose += 1 elif o == "-d": display = 1 r = mensa() print("problem created. let us solve it.") s = [] for sol in Solver().solve_all(r, verbose): s.append(sol) if display: sol["c"] = sol["x"] * sol["y"] print(f"{sol['x']} x {sol['y']} = {sol['c']}") if not display: print(f"Found {len(s)} solutions") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/menza_brute_force.py0000666000000000000000000000253614554256055021611 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . def menza(): sol = [] all_digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for a in range(1000): for b in range(100): c = a * b if c > 9999: digits = list("%.3d%.2d%.5d" % (a, b, c)) digits.sort() if digits == all_digits: sol.append({"a": a, "b": b}) print("%.3d x %.2d = %.5d" % (a, b, c)) return sol if __name__ == "__main__": sol = menza() print(len(sol)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/money.py0000666000000000000000000000500514554256055017241 0ustar00rootroot#!/usr/bin/env python2.2 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . from logilab.constraint import fd, Repository, Solver def money(verbose=0): """SEND +MORE ------- MONEY """ digits = range(10) variables = list("sendmory") domains = {} constraints = [] for v in variables: domains[v] = fd.FiniteDomain(digits) constraints.append(fd.AllDistinct(variables)) constraints.append(fd.NotEquals("m", 0)) constraints.append(fd.NotEquals("s", 0)) constraints.append( fd.make_expression(("s", "m", "o"), "(s+m) in (10*m+o,10*m+o-1)") ) constraints.append(fd.make_expression(("d", "e", "y"), "(d+e)%10 == y")) constraints.append(fd.make_expression(("n", "r", "e"), "(n+r)%10 in (e,e-1)")) constraints.append(fd.make_expression(("o", "e", "n"), "(o+e)%10 in (n,n-1)")) constraints.append( fd.make_expression( variables, "m*10000+(o-m-s)*1000+(n-o-e)*100+(e-r-n)*10+y-e-d == 0" ) ) r = Repository(variables, domains, constraints) s = Solver().solve_one(r, verbose) return s def display_solution(d): for s in d: print(" SEND\t \t", " %(s)d%(e)d%(n)d%(d)d" % s) print("+ MORE\t \t", "+ %(m)d%(o)d%(r)d%(e)d" % s) print("------\t-->\t", "------") print(" MONEY\t \t", " %(m)d%(o)d%(n)d%(e)d%(y)d" % s) print() if __name__ == "__main__": import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") verbose = 0 display = 0 for o, v in opts: if o == "-v": verbose += 1 if o == "-d": display = 1 sol = money(verbose) if display: display_solution([sol]) else: print(sol) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/money2.py0000666000000000000000000000500214554256055017320 0ustar00rootroot#!/usr/bin/env python2.2 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . from logilab.constraint import fd, Repository, Solver from logilab.constraint.distributors import SplitDistributor def money(verbose=0): """SEND +MORE ------- MONEY """ digits = range(10) variables = list("sendmory") domains = {} constraints = [] for v in variables: domains[v] = fd.FiniteDomain(digits) constraints.append(fd.AllDistinct(variables)) constraints.append(fd.NotEquals("m", 0)) constraints.append(fd.NotEquals("s", 0)) for v1 in variables: for v2 in variables: if v1 < v2: constraints.append(fd.make_expression((v1, v2), f"{v1} != {v2}")) constraints.append( fd.make_expression( variables, "m*10000+(o-m-s)*1000+(n-o-e)*100+(e-r-n)*10+y-e-d == 0" ) ) r = Repository(variables, domains, constraints) s = Solver(distributor=SplitDistributor(10)).solve_one(r, verbose) return s def display_solution(d): print(" SEND\t \t", " %(s)d%(e)d%(n)d%(d)d" % d) print("+ MORE\t \t", "+ %(m)d%(o)d%(r)d%(e)d" % d) print("------\t-->\t", "------") print(" MONEY\t \t", " %(m)d%(o)d%(n)d%(e)d%(y)d" % d) if __name__ == "__main__": print("WARNING!") print("This example takes looooooooooooooots of CPU to complete.") print("try money.py for a faster version.") import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") verbose = 0 display = 0 for o, v in opts: if o == "-v": verbose += 1 if o == "-d": display = 1 sol = money(verbose) if display: display_solution(sol) else: print(sol) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/queens.py0000666000000000000000000000732014554256055017414 0ustar00rootroot#!/usr/bin/env python # copyright 2002-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """N queens problem The problem is solved with a EnumeratorDistributor splitting the smallest domain in at most N subdomains.""" from logilab.constraint import fd, Repository, Solver from logilab.constraint.distributors import ( EnumeratorDistributor, DichotomyDistributor, NaiveDistributor, ) distributors = { "enum": EnumeratorDistributor, "dicho": DichotomyDistributor, "naive": NaiveDistributor, } def queens(size=8, verbose=0, distrib="enum"): variables = [] domains = {} constraints = [] for i in range(size): name = "Q%02d" % i variables.append(name) domains[name] = fd.FiniteDomain([(i, j) for j in range(size)]) for q1 in variables: for q2 in variables: if q1 < q2: c = fd.make_expression( (q1, q2), "%(q1)s[0] < %(q2)s[0] and " "%(q1)s[1] != %(q2)s[1] and " "abs(%(q1)s[0]-%(q2)s[0]) != " "abs(%(q1)s[1]-%(q2)s[1])" % {"q1": q1, "q2": q2}, ) constraints.append(c) r = Repository(variables, domains, constraints) Distrib = distributors[distrib] yield from Solver(Distrib()).solve_all(r, verbose) def draw_solution(s): size = len(s) queens = {} board = "" for q, p in s.items(): queens[p] = q board += "_" * (size * 2 + 1) + "\n" for i in range(size): # for j in range(size): q = queens.get((i, j)) if q is None: board += "|" + "·-"[(i + j) % 2] else: board += "|Q" board += "|\n" board += "¯" * (size * 2 + 1) print(board) def main(args=None): import sys import getopt if args is None: args = sys.argv[1:] opts, args = getopt.getopt(args, "dvfD:") display = 0 verbose = 0 first = 0 distrib = "enum" if args: size = int(args[0]) else: size = 8 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 1 elif o == "-f": first = 1 elif o == "-D": if v in distributors: distrib = v else: raise RuntimeError( f"Distributor must be one of {', '.join(distributors.keys())}" ) count = 0 for sol in queens(size, verbose, distrib): count += 1 if display: print("solution #%d" % count) draw_solution(sol) print("*" * 80) if first: break if not display: print("Use -d option to display solutions") print(count, "solutions found.") if __name__ == "__main__": # import hotshot # p = hotshot.Profile('/tmp/queens.prof') # p.runcall(main) # p.close() main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/queens2.py0000666000000000000000000000742214554256055017501 0ustar00rootroot#!/usr/bin/env python # copyright 2002-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """N queens problem The problem is solved with a EnumeratorDistributor splitting the smallest domain in at most N subdomains.""" from logilab.constraint import fd, Repository, Solver from logilab.constraint.distributors import ( EnumeratorDistributor, DichotomyDistributor, NaiveDistributor, RandomizingDistributor, ) distributors = { "enum": EnumeratorDistributor, "dicho": DichotomyDistributor, "naive": NaiveDistributor, "random": RandomizingDistributor, } def queens(size=8, verbose=0, distrib="enum"): variables = [] domains = {} constraints = [] for i in range(size): name = "Q%02d" % i variables.append(name) domains[name] = fd.FiniteDomain(range(size)) for r1 in range(size): q1 = "Q%02d" % r1 for r2 in range(r1 + 1, size): q2 = "Q%02d" % r2 D = {"q1": q1, "q2": q2, "diag": r2 - r1} c = fd.make_expression( (q1, q2), f"{D['q1']} != {D['q2']} and {D['diag']} != abs({D['q1']}-{D['q2']})", ) constraints.append(c) r = Repository(variables, domains, constraints) Distrib = distributors[distrib] yield from Solver(Distrib()).solve_all(r, verbose) def draw_solution(s): size = len(s) board = "" queens = s.items() queens.sort() board += "_" * (size * 2 + 1) + "\n" for i in range(size): qj = queens[i][1] for j in range(size): if j != qj: board += "|" + "·-"[(i + j) % 2] else: board += "|Q" board += "|\n" board += "¯" * (size * 2 + 1) print(board) def main(args=None): import sys import getopt if args is None: args = sys.argv[1:] opts, args = getopt.getopt(args, "dvfD:") display = 0 verbose = 0 first = 0 distrib = "enum" if args: size = int(args[0]) else: size = 8 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 1 elif o == "-f": first = 1 elif o == "-D": if v in distributors: distrib = v else: raise RuntimeError( f"Distributor must be one of {', '.join(distributors.keys())}" ) count = 0 for sol in queens(size, verbose, distrib): count += 1 if display: print("solution #%d" % count) draw_solution(sol) print("*" * 80) if first: break if not display: print("Use -d option to display solutions") print(count, "solutions found.") print("Domains copy:", fd.FiniteDomain._copy_count) print("Domains writes:", fd.FiniteDomain._write_count) if __name__ == "__main__": # import hotshot # p = hotshot.Profile('/tmp/queens.prof') # p.runcall(main) # p.close() main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/queens3.py0000666000000000000000000000575614554256055017512 0ustar00rootroot#!/usr/bin/env python # copyright 2002-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """N queens problem The problem is solved with a EnumeratorDistributor splitting the smallest domain in at most N subdomains.""" from logilab.constraint import Repository, Solver from logilab.constraint.distributors import EnumeratorDistributor from chess import ChessDomain, QueensConstraint def queens(size=8, verbose=0): variables = [] domains = {} constraints = [] for i in range(size): name = "Q%02d" % i variables.append(name) domains[name] = ChessDomain(size) for q1 in variables: for q2 in variables: if q1 < q2: c = QueensConstraint((q1, q2)) constraints.append(c) r = Repository(variables, domains, constraints) yield from Solver(EnumeratorDistributor()).solve_all(r, verbose) def draw_solution(s): size = len(s) queens = {} board = "" for q, p in s.items(): queens[p] = q board += "_" * (size * 2 + 1) + "\n" for i in range(size): # for j in range(size): q = queens.get((i, j)) if q is None: board += "|" + "·-"[(i + j) % 2] else: board += "|Q" board += "|\n" board += "¯" * (size * 2 + 1) print(board) def main(args=None): import sys import getopt if args is None: args = sys.argv[1:] opts, args = getopt.getopt(args, "dvf") display = 0 verbose = 0 first = 0 if args: size = int(args[0]) else: size = 8 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 1 elif o == "-f": first = 1 count = 0 for sol in queens(size, verbose): count += 1 if display: print("solution #%d" % count) draw_solution(sol) print("*" * 80) if first: break if not display: print("Use -d option to display solutions") print(count, "solutions found.") if __name__ == "__main__": # import hotshot # p = hotshot.Profile('/tmp/queens.prof') # p.runcall(main) # p.close() main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/rooks.py0000666000000000000000000000607114554256055017253 0ustar00rootroot#!/usr/bin/env python # copyright 2002-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """N queens problem The problem is solved with a EnumeratorDistributor splitting the smallest domain in at most N subdomains.""" from logilab.constraint import fd, Repository, Solver from logilab.constraint.distributors import EnumeratorDistributor def rooks(size=8, verbose=0): variables = [] domains = {} constraints = [] for i in range(size): name = "R%02d" % i variables.append(name) domains[name] = fd.FiniteDomain(range(size)) for r1 in range(size): for r2 in range(size): q1 = "R%02d" % r1 q2 = "R%02d" % r2 if r1 < r2: D = {"q1": q1, "q2": q2, "r1": r1, "r2": r2} c = fd.make_expression((q1, q2), f"{D['q1']} != {D['q2']}") constraints.append(c) r = Repository(variables, domains, constraints) yield from Solver(EnumeratorDistributor()).solve_all(r, verbose) def draw_solution(s): size = len(s) board = "" queens = s.items() queens.sort() board += "_" * (size * 2 + 1) + "\n" for i in range(size): qj = queens[i][1] for j in range(size): if j != qj: board += "|" + "·-"[(i + j) % 2] else: board += "|R" board += "|\n" board += "¯" * (size * 2 + 1) print(board) def main(args=None): import sys import getopt if args is None: args = sys.argv[1:] opts, args = getopt.getopt(args, "dvf") display = 0 verbose = 0 first = 0 if args: size = int(args[0]) else: size = 8 for o, v in opts: if o == "-d": display = 1 elif o == "-v": verbose += 1 elif o == "-f": first = 1 count = 0 for sol in rooks(size, verbose): count += 1 if display: print("solution #%d" % count) draw_solution(sol) print("*" * 80) if first: break if not display: print("Use -d option to display solutions") print(count, "solutions found.") if __name__ == "__main__": # import hotshot # p = hotshot.Profile('/tmp/queens.prof') # p.runcall(main) # p.close() main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/examples/sudoku.py0000666000000000000000000000650414554256055017431 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . from logilab.constraint import fd, Repository, Solver # games found on http://www.websudoku.com/ # I'm not sure how they rate the difficulty of their problems. easy = [ " 5 27 ", " 4 79 ", "1 6 8 35", "4 32 16 9", " 5 8 ", "8 76 95 3", "73 2 1 6", " 41 2 ", " 12 8 ", ] medium = [ " 9 85 ", " 3 1 5 ", " 283 1 ", " 2 4 7", " 3 5 ", "4 7 5 ", " 4 362 ", " 2 7 1 ", " 26 3 ", ] hard = [ " 19 73 4", " 98 72 ", " 5", " 4 6", "93 72", "4 6 ", "8 ", " 92 36 ", "5 42 31 ", ] evil = [ " 1 9 ", " 5 4 ", "2 1 365", " 327 ", "9 8", " 821 ", "473 5 1", " 6 4 ", " 3 8 ", ] def sudoku(problem, verbose=0): assert len(problem) == 9 # more sizes later variables = ["v%02d_%02d" % (i, j) for i in range(9) for j in range(9)] domains = {} constraints = [] values = list("123456789") for v in variables: domains[v] = fd.FiniteDomain(values) # line and column constraints for i in range(9): constraints.append(fd.AllDistinct(["v%02d_%02d" % (i, j) for j in range(9)])) constraints.append(fd.AllDistinct(["v%02d_%02d" % (j, i) for j in range(9)])) # square constraints: for i in (0, 3, 6): for j in (0, 3, 6): constraints.append( fd.AllDistinct( [ "v%02d_%02d" % (i + ii, j + jj) for ii in (0, 1, 2) for jj in (0, 1, 2) ] ) ) # fixed values: for i, line in enumerate(problem): for j, value in enumerate(line): if value != " ": constraints.append(fd.Equals("v%02d_%02d" % (i, j), value)) r = Repository(variables, domains, constraints) s = Solver().solve_one(r, verbose) return s def display_solution(d): for i in range(9): for j in range(9): print(d["v%02d_%02d" % (i, j)], end=" ") print() if __name__ == "__main__": import sys import getopt opts, args = getopt.getopt(sys.argv[1:], "dv") verbose = 0 display = 0 for o, v in opts: if o == "-v": verbose += 1 if o == "-d": display = 1 sol = sudoku(evil, verbose) if display: display_solution(sol) else: print(sol) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1706122311.495689 logilab-constraint-1.0/logilab/0000755000000000000000000000000014554256107015325 5ustar00rootroot././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5116892 logilab-constraint-1.0/logilab/constraint/0000755000000000000000000000000014554256110017503 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/__init__.py0000666000000000000000000000252214554256055021631 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Constraint Satisfaction Problem (CSP) Solver in Python.""" import sys if sys.version_info < (3, 10): from importlib_metadata import version else: from importlib.metadata import version from logilab.constraint.propagation import Repository, Solver from logilab.constraint.distributors import DefaultDistributor from logilab.constraint import fd from logilab.constraint import fi __all__ = ["Repository", "Solver", "DefaultDistributor", "fd", "fi"] __version__ = version("logilab-constraint") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/distributors.py0000666000000000000000000001455514554256055022640 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """ distributors - part of Logilab's constraint satisfaction solver. """ from logilab.constraint.interfaces import DistributorInterface import math import random def make_new_domains(domains): """return a shallow copy of dict of domains passed in argument""" domain = {} for key, value in domains.items(): domain[key] = value.copy() return domain class AbstractDistributor: """Implements DistributorInterface but abstract because _distribute is left unimplemented.""" __implements__ = DistributorInterface def __init__(self, nb_subspaces=2): self.nb_subspaces = nb_subspaces self.verbose = 0 def findSmallestDomain(self, domains): """returns the variable having the smallest domain. (or one of such varibles if there is a tie) """ domlist = [ (dom.size(), variable) for variable, dom in domains.items() if dom.size() > 1 ] domlist.sort() return domlist[0][1] def findLargestDomain(self, domains): """returns the variable having the largest domain. (or one of such variables if there is a tie) """ domlist = [ (dom.size(), variable) for variable, dom in domains.items() if dom.size() > 1 ] domlist.sort() return domlist[-1][1] def nb_subdomains(self, domains): """return number of sub domains to explore""" return self.nb_subspaces def distribute(self, domains, verbose=0): """do the minimal job and let concrete class distribute variables""" self.verbose = verbose replicas = [] for i in range(self.nb_subdomains(domains)): replicas.append(make_new_domains(domains)) modified_domains = self._distribute(*replicas) for domain in modified_domains: domain.resetFlags() return replicas def _distribute(self, *args): """method to implement in concrete class take self.nb_subspaces copy of the original domains as argument distribute the domains and return each modified domain """ raise NotImplementedError( "Use a concrete implementation of " "the Distributor interface" ) class NaiveDistributor(AbstractDistributor): """distributes domains by splitting the smallest domain in 2 new domains The first new domain has a size of one, and the second has all the other values""" def __init__(self): AbstractDistributor.__init__(self) def _distribute(self, dom1, dom2): """See AbstractDistributor""" variable = self.findSmallestDomain(dom1) values = dom1[variable].getValues() if self.verbose: print("Distributing domain for variable", variable, "at value", values[0]) dom1[variable].removeValues(values[1:]) dom2[variable].removeValue(values[0]) return (dom1[variable], dom2[variable]) class RandomizingDistributor(AbstractDistributor): """distributes domains as the NaiveDistrutor, except that the unique value of the first domain is picked at random.""" def __init__(self): AbstractDistributor.__init__(self) def _distribute(self, dom1, dom2): """See AbstractDistributor""" variable = self.findSmallestDomain(dom1) values = dom1[variable].getValues() distval = random.choice(values) values.remove(distval) if self.verbose: print("Distributing domain for variable", variable, "at value", distval) dom1[variable].removeValues(values) dom2[variable].removeValue(distval) return (dom1[variable], dom2[variable]) class SplitDistributor(AbstractDistributor): """distributes domains by splitting the smallest domain in nb_subspaces equal parts or as equal as possible. If nb_subspaces is 0, then the smallest domain is split in domains of size 1""" def __init__(self, nb_subspaces=3): AbstractDistributor.__init__(self, nb_subspaces) self.__to_split = None def nb_subdomains(self, domains): """See AbstractDistributor""" self.__to_split = self.findSmallestDomain(domains) if self.nb_subspaces: return min(self.nb_subspaces, domains[self.__to_split].size()) else: return domains[self.__to_split].size() def _distribute(self, *args): """See AbstractDistributor""" variable = self.__to_split nb_subspaces = len(args) values = args[0][variable].getValues() nb_elts = max(1, len(values) * 1.0 / nb_subspaces) slices = [ (int(math.floor(index * nb_elts)), int(math.floor((index + 1) * nb_elts))) for index in range(nb_subspaces) ] if self.verbose: print("Distributing domain for variable", variable) modified = [] for dom, (end, start) in zip(args, slices): dom[variable].removeValues(values[:end]) dom[variable].removeValues(values[start:]) modified.append(dom[variable]) return modified class DichotomyDistributor(SplitDistributor): """distributes domains by splitting the smallest domain in two equal parts or as equal as possible""" def __init__(self): SplitDistributor.__init__(self, 2) class EnumeratorDistributor(SplitDistributor): """distributes domains by splitting the smallest domain in domains of size 1.""" def __init__(self): SplitDistributor.__init__(self, 0) DefaultDistributor = DichotomyDistributor ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/fd.py0000666000000000000000000002650114554256055020466 0ustar00rootroot# pylint: disable-msg=W0142 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Tools to work with finite domain variables and constraints This module provides the following usable classes: * FiniteDomain: a class for storing FiniteDomains * Expression: a constraint represented as an expression * BinaryExpression: a binary constraint represented as an expression * various BasicConstraint classes The Expression and BinaryExpression classes can be constructed using the make_expression factory function. """ import sys import operator from logilab.constraint.propagation import ( AbstractDomain, BasicConstraint, ConsistencyFailure, AbstractConstraint, ) class FiniteDomain(AbstractDomain, set): """ Variable Domain with a finite set of possible values """ _copy_count = 0 _write_count = 0 def __init__(self, values): """values is a list of values in the domain This class uses a dictionnary to make sure that there are no duplicate values""" AbstractDomain.__init__(self) assert len(values) > 0 set.__init__(self, values) def removeValue(self, value): """Remove value of domain and check for consistency""" self.remove(value) self._valueRemoved() def removeValues(self, values): """Remove values of domain and check for consistency""" if values: self.difference_update(values) self._valueRemoved() __delitem__ = removeValue size = set.__len__ def getValues(self): """return all the values in the domain""" return list(self) def copy(self): """clone the domain""" return FiniteDomain(self) def __repr__(self): return f"" ## # Constraints ## class AllDistinct(AbstractConstraint): """Contraint: all values must be distinct""" def __init__(self, variables): assert len(variables) > 1 AbstractConstraint.__init__(self, variables) # worst case complexity self.__cost = len(variables) * (len(variables) - 1) / 2 def __repr__(self): return f"" def estimateCost(self, domains): """return cost""" return self.__cost def narrow(self, domains): """narrowing algorithm for the constraint""" variables = [ (domains[variable].size(), variable, domains[variable]) for variable in self._variables ] variables.sort() # if a domain has a size of 1, # then the value must be removed from the other domains for size, var, dom in variables: if dom.size() == 1: for _siz, _var, _dom in variables: if _var != var: try: _dom.removeValue(dom.getValues()[0]) except KeyError: # we ignore errors caused by the removal of # non existing values pass # if there are less values than variables, the constraint fails values = {} for size, var, dom in variables: for val in dom: values[val] = 0 if len(values) < len(variables): raise ConsistencyFailure() # the constraint is entailed if all domains have a size of 1 for variable in variables: if variable[2].size() != 1: return 0 return 1 class Expression(AbstractConstraint): """A constraint represented as a python expression.""" _FILTER_CACHE = {} def __init__(self, variables, formula, type="fd.Expression"): """variables is a list of variables which appear in the formula formula is a python expression that will be evaluated as a boolean""" AbstractConstraint.__init__(self, variables) self.formula = formula self.type = type try: self.filterFunc = Expression._FILTER_CACHE[formula] except KeyError: self.filterFunc = eval(f"lambda {','.join(variables)}: {formula}", {}, {}) Expression._FILTER_CACHE[formula] = self.filterFunc def _init_result_cache(self): """key = (variable,value), value = [has_success,has_failure]""" result_cache = {} for var_name in self._variables: result_cache[var_name] = {} return result_cache def _assign_values(self, domains): variables = [] kwargs = {} for variable in self._variables: domain = domains[variable] values = domain.getValues() variables.append((domain.size(), [variable, values, 0, len(values)])) kwargs[variable] = values[0] # sort variables to instanciate those with fewer possible values first variables.sort() go_on = 1 while go_on: yield kwargs # try to instanciate the next variable for size, curr in variables: if (curr[2] + 1) < curr[-1]: curr[2] += 1 kwargs[curr[0]] = curr[1][curr[2]] break else: curr[2] = 0 kwargs[curr[0]] = curr[1][0] else: # it's over go_on = 0 def narrow(self, domains): """generic narrowing algorithm for n-ary expressions""" maybe_entailed = 1 ffunc = self.filterFunc result_cache = self._init_result_cache() for kwargs in self._assign_values(domains): if maybe_entailed: for var, val in kwargs.items(): if val not in result_cache[var]: break else: continue if ffunc(**kwargs): for var, val in kwargs.items(): result_cache[var][val] = 1 else: maybe_entailed = 0 try: for var, keep in result_cache.items(): domain = domains[var] domain.removeValues([val for val in domain if val not in keep]) except ConsistencyFailure: raise ConsistencyFailure(f"Inconsistency while applying {repr(self)}") except KeyError: # There are no more value in result_cache pass return maybe_entailed def __repr__(self): return f'<{self.type} "{self.formula}">' class BinaryExpression(Expression): """A binary constraint represented as a python expression This implementation uses a narrowing algorithm optimized for binary constraints.""" def __init__(self, variables, formula, type="fd.BinaryExpression"): assert len(variables) == 2 Expression.__init__(self, variables, formula, type) def narrow(self, domains): """specialized narrowing algorithm for binary expressions Runs much faster than the generic version""" maybe_entailed = 1 var1 = self._variables[0] dom1 = domains[var1] values1 = dom1.getValues() var2 = self._variables[1] dom2 = domains[var2] values2 = dom2.getValues() ffunc = self.filterFunc if dom2.size() < dom1.size(): var1, var2 = var2, var1 dom1, dom2 = dom2, dom1 values1, values2 = values2, values1 kwargs = {} keep1 = {} keep2 = {} maybe_entailed = 1 try: # iterate for all values for val1 in values1: kwargs[var1] = val1 for val2 in values2: kwargs[var2] = val2 if val1 in keep1 and val2 in keep2 and maybe_entailed == 0: continue if ffunc(**kwargs): keep1[val1] = 1 keep2[val2] = 1 else: maybe_entailed = 0 dom1.removeValues([val for val in values1 if val not in keep1]) dom2.removeValues([val for val in values2 if val not in keep2]) except ConsistencyFailure: raise ConsistencyFailure(f"Inconsistency while applying {repr(self)}") except Exception: print(self, kwargs) raise return maybe_entailed def make_expression(variables, formula, constraint_type=None): """create a new constraint of type Expression or BinaryExpression The chosen class depends on the number of variables in the constraint""" # encode unicode vars = [] for var in variables: if sys.version_info < (3,) and isinstance(var, str): vars.append(var.encode()) else: vars.append(var) if len(vars) == 2: if constraint_type is not None: return BinaryExpression(vars, formula, constraint_type) else: return BinaryExpression(vars, formula) else: if constraint_type is not None: return Expression(vars, formula, constraint_type) else: return Expression(vars, formula) class Equals(BasicConstraint): """A basic constraint variable == constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.eq) class NotEquals(BasicConstraint): """A basic constraint variable != constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.ne) class LesserThan(BasicConstraint): """A basic constraint variable < constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.lt) class LesserOrEqual(BasicConstraint): """A basic constraint variable <= constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.le) class GreaterThan(BasicConstraint): """A basic constraint variable > constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.gt) class GreaterOrEqual(BasicConstraint): """A basic constraint variable >= constant value""" def __init__(self, variable, reference): BasicConstraint.__init__(self, variable, reference, operator.ge) def _in(v, set): """test presence of v in set""" return v in set class InSet(BasicConstraint): """A basic contraint variable in set value""" def __init__(self, variable, set): BasicConstraint.__init__(self, variable, set, _in) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/fi.py0000666000000000000000000002726314554256055020501 0ustar00rootroot# pylint: disable-msg=W0142 # copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Tools to work with finite interval domain interval and constraints """ from logilab.constraint.distributors import AbstractDistributor from logilab.constraint.propagation import ( AbstractDomain, ConsistencyFailure, AbstractConstraint, ) class Interval: """representation of an interval This class is used to give back results from a FiniteIntervalDomain """ def __init__(self, start, end): self._start = start self._end = end def __repr__(self): return f"" def __eq__(self, other): return self._start == other._start and self._end == other._end def __hash__(self): return hash((self.__class__, self._start, self._end)) class FiniteIntervalDomain(AbstractDomain): """ Domain for a variable with interval values. """ def __init__( self, lowestMin, highestMax, min_length, max_length=None, resolution=1 ): """ lowestMin is the lowest value of a low boundary for a variable (inclusive). highestMax is the highest value of a high boundary for a variable (exclusive). min_length is the minimum width of the interval. max_length is the maximum width of the interval. Use None to have max = min. resolution is the precision to use for constraint satisfaction. Defaults to 1 """ assert highestMax >= lowestMin if max_length is None: max_length = min_length assert 0 <= min_length <= max_length assert min_length <= highestMax - lowestMin assert resolution > 0 AbstractDomain.__init__(self) self.lowestMin = lowestMin self.highestMax = highestMax self._min_length = min_length max_length = min(max_length, highestMax - lowestMin) self._max_length = max_length self._resolution = resolution def __eq__(self, other): return ( self.lowestMin == other.lowestMin and self.highestMax == other.highestMax and self._min_length == other._min_length and self._max_length == other._max_length and self._resolution == other._resolution ) def __hash__(self): return hash( ( self.__class__, self.lowestMin, self.highestMax, self._min_length, self._max_length, self._resolution, ) ) def getValues(self): return list(self.iter_values()) def iter_values(self): length = self._min_length while length <= self._max_length: start = self.lowestMin while start + length <= self.highestMax: yield Interval(start, start + length) start += self._resolution length += self._resolution def size(self): """computes the size of a finite interval""" size = 0 length = self._min_length while length <= self._max_length: size += ((self.highestMax - length) - self.lowestMin) / self._resolution + 1 length += self._resolution return size def _highestMin(self): return self.highestMax - self._min_length def _lowestMax(self): return self.lowestMin + self._min_length lowestMax = property(_lowestMax, None, None, "") highestMin = property(_highestMin, None, None, "") def copy(self): """clone the domain""" return FiniteIntervalDomain( self.lowestMin, self.highestMax, self._min_length, self._max_length, self._resolution, ) def setLowestMin(self, new_lowestMin): self.lowestMin = new_lowestMin self._valueRemoved() def setHighestMax(self, new_highestMax): self.highestMax = new_highestMax self._valueRemoved() def setMinLength(self, new_min): self._min_length = new_min self._valueRemoved() def setMaxLength(self, new_max): self._max_length = new_max self._valueRemoved() def overlap(self, other): return other.highestMax > self.lowestMin and other.lowestMin < self.highestMax def no_overlap_impossible(self, other): return self.lowestMax > other.highestMin and other.lowestMax > self.highestMin def hasSingleLength(self): return self._max_length == self._min_length def _valueRemoved(self): if self.lowestMin >= self.highestMax: raise ConsistencyFailure( "earliest start [%.2f] higher than latest end [%.2f]" % (self.lowestMin, self.highestMax) ) if self._min_length > self._max_length: raise ConsistencyFailure( "min length [%.2f] greater than max length [%.2f]" % (self._min_length, self._max_length) ) self._max_length = min(self._max_length, self.highestMax - self.lowestMin) AbstractDomain._valueRemoved(self) def __repr__(self): return "" % ( self.size(), self.lowestMin, self.lowestMax, self.highestMin, self.highestMax, ) ## # Distributors ## class FiniteIntervalDistributor(AbstractDistributor): """Distributes a set of FiniteIntervalDomain The distribution strategy is the following: - the smallest domain of size > 1 is picked - if its max_length is greater than its min_length, a subdomain if size min_length is distributed, with the same boundaries - otherwise, a subdomain [lowestMin, lowestMax[ is distributed """ def __init__(self): AbstractDistributor.__init__(self) def _split_values(self, copy1, copy2): lm = copy1.lowestMin hM = copy1.highestMax if copy1.hasSingleLength(): r = copy1._resolution L = copy1._min_length m = (hM - L + lm) // (2 * r) * r # copy1.highestMax = copy1.lowestMin + copy1._min_length # copy2.lowestMin += copy2._resolution copy1.highestMax = m + L copy2.lowestMin = m + r else: copy1._max_length = copy1._min_length copy2._min_length += copy2._resolution def _distribute(self, dom1, dom2): variable = self.findSmallestDomain(dom1) if self.verbose: print("Distributing domain for variable", variable) splitted = dom1[variable] cpy1 = splitted.copy() cpy2 = splitted.copy() self._split_values(cpy1, cpy2) dom1[variable] = cpy1 dom2[variable] = cpy2 return cpy1, cpy2 ## # Constraints ## class AbstractFIConstraint(AbstractConstraint): def __init__(self, var1, var2): AbstractConstraint.__init__(self, (var1, var2)) def estimateCost(self, domains): return 1 def __repr__(self): return f"<{self.__class__.__name__} {str(self._variables)}>" def __eq__(self, other): return self.__class__ is other.__class__ and tuple( sorted(self._variables) ) == tuple(sorted(other._variables)) def __hash__(self): # FIXME: to be able to add constraints in Sets (and compare them) # FIXME: improve implementation variables = tuple(sorted(self._variables)) return hash((self.__class__.__name__, variables)) def narrow(self, domains): """narrowing algorithm for the constraint""" dom1 = domains[self._variables[0]] dom2 = domains[self._variables[1]] return self._doNarrow(dom1, dom2) def _doNarrow(self, dom1, dom2): """virtual method which does the real work""" raise NotImplementedError # FIXME: deal with more than 2 domains at once ? class NoOverlap(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if not dom1.overlap(dom2): return 1 elif dom1.no_overlap_impossible(dom2): raise ConsistencyFailure elif dom1.lowestMax == dom2.highestMin and dom2.lowestMax > dom1.highestMin: dom1.setHighestMax(dom2.highestMin) dom2.setLowestMin(dom1.lowestMax) return 1 elif dom1.lowestMax > dom2.highestMin and dom2.lowestMax == dom1.highestMin: dom2.setHighestMax(dom1.highestMin) dom1.setLowestMin(dom2.lowestMax) return 1 return 0 class StartsBeforeStart(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.lowestMin > dom2.highestMin: raise ConsistencyFailure if dom1.highestMin < dom2.lowestMin: return 1 return 0 class StartsBeforeEnd(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.lowestMin > dom2.highestMax: raise ConsistencyFailure if dom1.highestMin < dom2.lowestMax: return 1 return 0 class EndsBeforeStart(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.lowestMax > dom2.highestMin: raise ConsistencyFailure if dom1.highestMax < dom2.lowestMin: return 1 if dom1.highestMax > dom2.highestMin: dom1.setHighestMax(dom2.highestMin) return 0 class EndsBeforeEnd(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.lowestMax > dom2.highestMax: raise ConsistencyFailure if dom1.highestMax < dom2.lowestMax: return 1 if dom1.highestMax > dom2.highestMax: dom1.setHighestMax(dom2.highestMax) return 0 class StartsAfterStart(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.highestMin < dom2.lowestMin: raise ConsistencyFailure if dom1.lowestMin > dom2.highestMin: return 1 if dom1.lowestMin < dom2.lowestMin: dom1.setLowestMin(dom2.lowestMin) return 0 class StartsAfterEnd(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.highestMin < dom2.lowestMax: raise ConsistencyFailure if dom1.lowestMin > dom2.highestMax: return 1 if dom1.lowestMin < dom2.lowestMax: dom1.setLowestMin(dom2.lowestMax) if dom2.highestMax > dom1.highestMin: dom2.setHighestMax(dom1.highestMin) return 0 class EndsAfterStart(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.highestMax < dom2.lowestMin: raise ConsistencyFailure if dom1.lowestMax > dom2.highestMin: return 1 return 0 class EndsAfterEnd(AbstractFIConstraint): def _doNarrow(self, dom1, dom2): if dom1.highestMax < dom2.lowestMax: raise ConsistencyFailure if dom1.lowestMax > dom2.highestMax: return 1 return 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/interfaces.py0000666000000000000000000001064314554256055022220 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Definition of interfaces""" class ConstraintInterface: """The interface that all constraints should implement""" def isVariableRelevant(self, variable): """Returns true if changes in the domaine of the variable should trigger an evaluation of the constraint""" raise NotImplementedError def affectedVariables(self): """Return a list of all variables affected by this constraint""" raise NotImplementedError def estimateCost(self, domains): """Return an estimate of the cost of the narrowing of the constraint""" raise NotImplementedError def narrow(self, domains): """ensures that the domains are consistent with the constraint Calls domain.removeValue to remove values from a domain raises ConsistencyFailure if the narrowing fails Returns 1 if the constraint is entailed, and 0 otherwise""" raise NotImplementedError class DomainInterface: """The interface that all domains should implement""" def resetFlags(self): """resets the hasChanged flag""" raise NotImplementedError def hasChanged(self): """returns true if values have been removed from the domain since the last call to resetFlags""" raise NotImplementedError def removeValue(self, value): """Removes a value from the domain""" raise NotImplementedError def size(self): """returns the number of values in the domain""" raise NotImplementedError def getValues(self): """returns a tuple containing all the values in the domain These values should not be modified!""" raise NotImplementedError class DistributorInterface: """The interface that all distributors should implement""" def distribute(self, domains, verbose=0): """domains is a dictionnary of variable -> Domain objects This method returns a list of dictionnaries similar to the domain argument This list should be a partition of the initial domains""" raise NotImplementedError # class VariableInterface: # """The interface that all variables should implement""" # def getDomain(self): # """returns the domain of the variable""" # raise NotImplementedError # def setDomain(self, domain): # """sets a new domain to the variable""" # raise NotImplementedError # Magic methods for various operations # def __add__(self, other): # raise NotImplementedError # def __sub__(self, other): # raise NotImplementedError # def __mul__(self, other): # raise NotImplementedError # def __div__(self, other): # raise NotImplementedError # def __radd__(self, other): # raise NotImplementedError # def __rsub__(self, other): # raise NotImplementedError # def __rmul__(self, other): # raise NotImplementedError # def __rdiv__(self, other): # raise NotImplementedError # def __abs__(self): # raise NotImplementedError # def __neg__(self): # raise NotImplementedError # def __pos__(self): # raise NotImplementedError # def __lt__(self, other): # raise NotImplementedError # def __le__(self, other): # raise NotImplementedError # def __gt__(self, other): # raise NotImplementedError # def __ge__(self, other): # raise NotImplementedError # def __eq__(self, other): # raise NotImplementedError # def __ne__(self, other): # raise NotImplementedError # def __len__(self): # raise NotImplementedError # def __getitem__(self, size): # raise NotImplementedError ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/logilab/constraint/propagation.py0000666000000000000000000003650214554256055022422 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """The code of the constraint propagation algorithms""" import sys from operator import mul as MUL from functools import reduce from time import strftime from logilab.constraint.interfaces import DomainInterface, ConstraintInterface def quiet_printer(*args): pass class ConsistencyFailure(Exception): """The repository is not in a consistent state""" class Repository: """Stores variables, domains and constraints Propagates domain changes to constraints Manages the constraint evaluation queue""" def __init__(self, variables, domains, constraints=None, printer=print): # encode unicode self._printer = printer for i, var in enumerate(variables): if sys.version_info < (3,) and isinstance(var, str): variables[i] = var.encode() self._variables = variables # list of variable names self._domains = domains # maps variable name to domain object self._constraints = [] # list of constraint objects # self._queue = [] # queue of constraints waiting to be processed self._variableListeners = {} for var in self._variables: self._variableListeners[var] = [] assert var in self._domains for constr in constraints or (): self.addConstraint(constr) def display(self): self._printer("VARIABLES") self._printer("---------") for v in sorted(self._variables): self._printer(f"{v} = {self._domains[v]}") self._printer("CONSTRAINTS") self._printer("-----------") for c in self._constraints: self._printer(c) def display_vars(self): self._printer(f"{len(self._constraints)} constraints with:") for v in sorted(self._variables): self._printer("%15s = %s" % (v, self._domains[v])) def __repr__(self): return "" % ( len(self._constraints), self._domains, ) def vcg_draw(self, filename, title="Constraints graph"): """draw a constraints graph readable by vcg""" from logilab.common.vcgutils import VCGPrinter, EDGE_ATTRS stream = open(filename, "w") printer = VCGPrinter(stream) printer.open_graph( title=title, textcolor="black", # layoutalgorithm='dfs', # manhattan_edges='yes' # port_sharing='no' # late_edge_labels='yes' ) for var in self._variables: printer.node(var, shape="ellipse") type_colors = {} color_index = 2 i = 0 for constraint in self._constraints: key = constraint.type if key not in type_colors: type_colors[key] = color_index color_index += 1 affected_vars = constraint.affectedVariables() if len(affected_vars) <= 1: continue if len(affected_vars) == 2: var1 = affected_vars[0] var2 = affected_vars[1] printer.edge( var1, var2, arrowstyle="none", color=EDGE_ATTRS["color"][type_colors[key]], ) continue n_id = "N_aire%i" % i i += 1 printer.node(n_id, shape="triangle") for var1 in affected_vars: printer.edge( var1, n_id, arrowstyle="none", color=EDGE_ATTRS["color"][type_colors[key]], ) # self._printer( legend) for node_type, color in type_colors.items(): printer.node(node_type, shape="box", color=EDGE_ATTRS["color"][color]) printer.close_graph() stream.close() def addConstraint(self, constraint): if isinstance(constraint, BasicConstraint): # Basic constraints are processed just once # because they are straight away entailed var = constraint.getVariable() constraint.narrow({var: self._domains[var]}) else: self._constraints.append(constraint) for var in constraint.affectedVariables(): self._variableListeners[var].append(constraint) def _removeConstraint(self, constraint): self._constraints.remove(constraint) for var in constraint.affectedVariables(): try: self._variableListeners[var].remove(constraint) except ValueError: raise ValueError( "Error removing constraint from listener", var, self._variableListeners[var], constraint, ) def getDomains(self): return self._domains def distribute(self, distributor, verbose=0): """Create new repository using the distributor and self""" for domains in distributor.distribute(self._domains, verbose): yield Repository( self._variables, domains, self._constraints, printer=self._printer ) # alf 20041216 -- I tried the following to avoid the cost of the # creation of new Repository objects. It resulted in functional, but # slightly slower code. If you want to try to improve it, I keep the # commented out version in the source, but the version above stays # active as it is both simpler and faster. # backup_constraints = self._constraints[:] # for domains in distributor.distribute(self._domains, verbose): # self._domains = domains # self._constraints = [] # self._queue = [] # for var in self._variables: # self._variableListeners[var] = [] # for constraint in backup_constraints: # self.addConstraint(constraint) # yield self def consistency(self, verbose=0, custom_printer=None): """Prunes the domains of the variables This method calls constraint.narrow() and queues constraints that are affected by recent changes in the domains. Returns True if a solution was found""" if custom_printer is None: printer = self._printer else: printer = custom_printer if verbose: printer(strftime("%H:%M:%S"), "** Consistency **") _queue = [ (constr.estimateCost(self._domains), id(constr), constr) for constr in self._constraints ] _queue.sort() _affected_constraints = {} while True: if not _queue: # refill the queue if some constraints have been affected _queue = [ (constr.estimateCost(self._domains), id(constr), constr) for constr in _affected_constraints ] if not _queue: break _queue.sort() _affected_constraints.clear() if verbose > 2: printer(strftime("%H:%M:%S"), "Queue", _queue) cost, _, constraint = _queue.pop(0) if verbose > 1: printer( strftime("%H:%M:%S"), "Trying to entail constraint", constraint, "[cost:%d]" % cost, ) entailed = constraint.narrow(self._domains) for var in constraint.affectedVariables(): # affected constraints are listeners of # affected variables of this constraint dom = self._domains[var] if not dom.hasChanged(): continue if verbose > 1: printer( strftime("%H:%M:%S"), " -> New domain for variable", var, "is", dom, ) for constr in self._variableListeners[var]: if constr is not constraint: _affected_constraints[constr] = True dom.resetFlags() if entailed: if verbose: printer(strftime("%H:%M:%S"), "--> Entailed constraint", constraint) self._removeConstraint(constraint) if constraint in _affected_constraints: del _affected_constraints[constraint] for domain in self._domains.values(): if domain.size() != 1: return 0 return 1 class Solver: """Top-level object used to manage the search""" def __init__(self, distributor=None, printer=print): """if no distributer given, will use the default one""" self.printer = printer if distributor is None: from logilab.constraint.distributors import DefaultDistributor distributor = DefaultDistributor() self.verbose = True self._distributor = distributor self.max_depth = 0 def solve_one(self, repository, verbose=0): """Generates only one solution""" self.verbose = verbose self.max_depth = 0 self.distrib_cnt = 0 try: return next(self._solve(repository)) except StopIteration: return def solve_best(self, repository, cost_func, verbose=0): """Generates solution with an improving cost""" self.verbose = verbose self.max_depth = 0 self.distrib_cnt = 0 best_cost = None for solution in self._solve(repository): cost = cost_func(**solution) if best_cost is None or cost <= best_cost: best_cost = cost yield solution, cost def solve_all(self, repository, verbose=0): """Generates all solutions""" self.verbose = verbose self.max_depth = 0 self.distrib_cnt = 0 for solution in self._solve(repository): yield solution def solve(self, repository, verbose=0): """return list of all solutions""" self.max_depth = 0 self.distrib_cnt = 0 solutions = [] for solution in self.solve_all(repository, verbose): solutions.append(solution) return solutions def _solve(self, repository, recursion_level=0): """main generator""" _solve = self._solve verbose = self.verbose if recursion_level > self.max_depth: self.max_depth = recursion_level if verbose >= 2: self.printer( strftime("%H:%M:%S"), ) self.printer( "*** [%d] Solve called with repository" % recursion_level, ) repository.display_vars() try: foundSolution = repository.consistency(verbose, custom_printer=self.printer) except ConsistencyFailure as exc: if verbose: self.printer(strftime("%H:%M:%S"), exc) else: if foundSolution: solution = {} for variable, domain in repository.getDomains().items(): solution[variable] = domain.getValues()[0] if verbose: self.printer(strftime("%H:%M:%S"), "### Found Solution", solution) self.printer("-" * 80) yield solution else: self.distrib_cnt += 1 for repo in repository.distribute(self._distributor, verbose >= 2): for solution in _solve(repo, recursion_level + 1): if solution is not None: yield solution if recursion_level == 0 and self.verbose: self.printer(strftime("%H:%M:%S"), "Finished search") self.printer( strftime("%H:%M:%S"), "Maximum recursion depth = ", self.max_depth ) self.printer("Nb distributions = ", self.distrib_cnt) class BasicConstraint: """A BasicConstraint, which is never queued by the Repository A BasicConstraint affects only one variable, and will be entailed on the first call to narrow()""" __implements__ = ConstraintInterface def __init__(self, variable, reference, operator): """variables is a list of variables on which the constraint is applied""" self._variable = variable self._reference = reference self._operator = operator def __repr__(self): return f"<{self.__class__} {self._variable} {self._reference}>" def isVariableRelevant(self, variable): return variable == self._variable def estimateCost(self, domains): return 0 # get in the first place in the queue def affectedVariables(self): return [self._variable] def getVariable(self): return self._variable def narrow(self, domains): domain = domains[self._variable] operator = self._operator ref = self._reference try: for val in domain.getValues(): if not operator(val, ref): domain.removeValue(val) except ConsistencyFailure: raise ConsistencyFailure(f"inconsistency while applying {repr(self)}") return 1 class AbstractDomain: """Implements the functionnality related to the changed flag. Can be used as a starting point for concrete domains""" __implements__ = DomainInterface def __init__(self): self.__changed = 0 def resetFlags(self): self.__changed = 0 def hasChanged(self): return self.__changed def _valueRemoved(self): """The implementation of removeValue should call this method""" self.__changed = 1 if self.size() == 0: raise ConsistencyFailure() class AbstractConstraint: __implements__ = ConstraintInterface def __init__(self, variables): """variables is a list of variables which appear in the formula""" self._variables = variables def affectedVariables(self): """Return a list of all variables affected by this constraint""" return self._variables def isVariableRelevant(self, variable): return variable in self._variables def estimateCost(self, domains): """Return an estimate of the cost of the narrowing of the constraint""" return reduce(MUL, [domains[var].size() for var in self._variables]) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5156891 logilab-constraint-1.0/logilab_constraint.egg-info/0000755000000000000000000000000014554256110021255 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122311.0 logilab-constraint-1.0/logilab_constraint.egg-info/PKG-INFO0000644000000000000000000000271214554256107022362 0ustar00rootrootMetadata-Version: 2.1 Name: logilab-constraint Version: 1.0 Summary: constraints satisfaction solver in Python Home-page: http://www.logilab.org/projects/logilab-constraint Author: Alexandre Fayolle Author-email: contact@logilab.fr License: LGPL Classifier: Topic :: Scientific/Engineering Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 License-File: COPYING License-File: COPYING.LESSER Requires-Dist: setuptools Requires-Dist: logilab-common<3.0.0,>=2.0.0 Requires-Dist: six>=1.4.0 Requires-Dist: importlib_metadata; python_version < "3.10" This package implements an extensible constraint satisfaction problem solver written in pure Python, using constraint propagation algorithms. The logilab.constraint module provides finite domains with arbitrary values, finite interval domains, and constraints which can be applied to variables linked to these domains. It requires python 2.6 or later to work, and is released under the GNU Lesser General Public License. The documentation is in the doc/ directory. Examples are in the examples/ directory. Discussion about constraint should take place on the python-projects mailing list. Information on subscription and mailing list archives can be accessed at https://lists.logilab.org/mailman/listinfo/python-projects/ Your feedback is very valuable to us. Please share your experience with other users of the package on the mailing list. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122311.0 logilab-constraint-1.0/logilab_constraint.egg-info/SOURCES.txt0000644000000000000000000000176014554256107023153 0ustar00rootrootCHANGELOG.md COPYING COPYING.LESSER ChangeLog MANIFEST.in README.rst __pkginfo__.py setup.py tox.ini doc/CONTRIBUTORS doc/documentation.html doc/documentation.xml doc/makefile examples/chess.py examples/conferences.py examples/intervals.py examples/knights.py examples/menza.py examples/menza2.py examples/menza_brute_force.py examples/money.py examples/money2.py examples/queens.py examples/queens2.py examples/queens3.py examples/rooks.py examples/sudoku.py logilab/constraint/__init__.py logilab/constraint/distributors.py logilab/constraint/fd.py logilab/constraint/fi.py logilab/constraint/interfaces.py logilab/constraint/propagation.py logilab_constraint.egg-info/PKG-INFO logilab_constraint.egg-info/SOURCES.txt logilab_constraint.egg-info/dependency_links.txt logilab_constraint.egg-info/requires.txt logilab_constraint.egg-info/top_level.txt test/__profile__.py test/test_constraints.py test/test_distributors.py test/test_domains.py test/test_fi.py test/test_propagation.py test/test_validation.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122311.0 logilab-constraint-1.0/logilab_constraint.egg-info/dependency_links.txt0000644000000000000000000000000114554256107025331 0ustar00rootroot ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122311.0 logilab-constraint-1.0/logilab_constraint.egg-info/requires.txt0000644000000000000000000000014214554256107023660 0ustar00rootrootsetuptools logilab-common<3.0.0,>=2.0.0 six>=1.4.0 [:python_version < "3.10"] importlib_metadata ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122311.0 logilab-constraint-1.0/logilab_constraint.egg-info/top_level.txt0000644000000000000000000000001014554256107024004 0ustar00rootrootlogilab ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5196893 logilab-constraint-1.0/setup.cfg0000644000000000000000000000004614554256110015527 0ustar00rootroot[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/setup.py0000666000000000000000000000366114554256055015442 0ustar00rootroot#!/usr/bin/env python # pylint: disable=W0404,W0622,W0704,W0613,W0152 # copyright 2003-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Generic Setup script, takes package info from __pkginfo__.py file. """ __docformat__ = "restructuredtext en" from os import path from setuptools import setup, find_namespace_packages here = path.abspath(path.dirname(__file__)) pkginfo = {} with open(path.join(here, "__pkginfo__.py")) as f: exec(f.read(), pkginfo) # Get the long description from the relevant file with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( name=pkginfo["distname"], version=pkginfo["version"], description=pkginfo["description"], long_description=long_description, url=pkginfo["web"], author=pkginfo["author"], author_email=pkginfo["author_email"], license=pkginfo["license"], # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=pkginfo["classifiers"], packages=find_namespace_packages(include=["logilab"]), install_requires=pkginfo["install_requires"], include_package_data=True, tests_require=pkginfo["tests_require"], ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1706122311.5156891 logilab-constraint-1.0/test/0000755000000000000000000000000014554256110014665 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/__profile__.py0000666000000000000000000000426414554256055017515 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . from logilab.constraint.propagation import Repository, Solver from logilab.constraint import fd def queens(size=8, verbose=0): possible_positions = [(i, j) for i in range(size) for j in range(size)] variables = [] domains = {} constraints = [] for i in range(size): name = "Q%d" % i variables.append(name) domains[name] = fd.FiniteDomain(possible_positions) for q1 in variables: for q2 in variables: if q1 < q2: constraints.append( fd.make_expression( (q1, q2), "%(q1)s[0] < %(q2)s[0] and " "%(q1)s[1] != %(q2)s[1] and " "abs(%(q1)s[0]-%(q2)s[0]) != " "abs(%(q1)s[1]-%(q2)s[1])" % {"q1": q1, "q2": q2}, ) ) r = Repository(variables, domains, constraints) s = Solver().solve(r, verbose) print("Number of solutions:", len(s)) if __name__ == "__main__": import profile profile.run("queens()", "csp.prof") import pstats p = pstats.Stats("csp.prof") p.sort_stats("time", "calls").print_stats(0.25) p.sort_stats("cum", "calls").print_stats(0.25) p.strip_dirs().sort_stats("cum", "calls").print_callers(0.25) p.strip_dirs().sort_stats("cum", "calls").print_callees() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_constraints.py0000666000000000000000000002677014554256055020675 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Unit testing for constraint propagation module""" import unittest from logilab.common.testlib import TestCase, TestSuite from logilab.constraint import fd from logilab.constraint import propagation class AbstractConstraintTC(TestCase): """override the following methods: * setUp to initialize variables * narrowingAssertions to check that narrowing was ok """ def setUp(self): self.relevant_variables = [] self.irrelevant_variable = "tagada" self.constraint = None # AbstractConstraint(self.relevant_variables) self.domains = {} self.entailed_domains = {} # raise NotImplementedError def testRelevance(self): """tests that relevant variables are relevant""" for v in self.relevant_variables: self.assertTrue(self.constraint.isVariableRelevant(v)) self.assertFalse(self.constraint.isVariableRelevant(self.irrelevant_variable)) def testNarrowing(self): """tests that narrowing is performed correctly""" self.constraint.narrow(self.domains) self.narrowingAssertions() def testEntailment(self): """tests that narrowing is performed correctly""" entailed = self.constraint.narrow(self.entailed_domains) self.assertTrue(entailed) class AllDistinctTC(AbstractConstraintTC): def setUp(self): self.relevant_variables = ["x", "y", "z"] self.irrelevant_variable = "tagada" self.constraint = fd.AllDistinct(self.relevant_variables) self.domains = { "x": fd.FiniteDomain((1, 2)), "y": fd.FiniteDomain((1, 3)), "z": fd.FiniteDomain((1, 4)), } self.entailed_domains = { "x": fd.FiniteDomain((1,)), "y": fd.FiniteDomain((1, 2)), "z": fd.FiniteDomain((1, 2, 3)), } def narrowingAssertions(self): vx = self.domains["x"].getValues() vy = self.domains["y"].getValues() vz = self.domains["z"].getValues() self.assertIn(1, vx) self.assertIn(2, vx) self.assertIn(1, vy) self.assertIn(3, vy) self.assertIn(1, vz) self.assertIn(4, vz) def testNarrowing2(self): domains = { "x": fd.FiniteDomain((1, 2)), "y": fd.FiniteDomain((1,)), "z": fd.FiniteDomain((1, 4)), } entailed = self.constraint.narrow(domains) vx = domains["x"].getValues() vy = domains["y"].getValues() vz = domains["z"].getValues() self.assertTrue(entailed) self.assertIn(2, vx) self.assertIn(1, vy) self.assertIn(4, vz) def testNarrowing3(self): domains = { "x": fd.FiniteDomain((1,)), "y": fd.FiniteDomain((2,)), "z": fd.FiniteDomain((1, 2, 3, 4)), } entailed = self.constraint.narrow(domains) vx = domains["x"].getValues() vy = domains["y"].getValues() vz = domains["z"].getValues() self.assertFalse(entailed) self.assertIn(1, vx) self.assertIn(2, vy) self.assertIn(4, vz) self.assertIn(3, vz) def testNarrowing4(self): domains = { "x": fd.FiniteDomain((1,)), "y": fd.FiniteDomain((2,)), "z": fd.FiniteDomain((1, 3, 4)), "t": fd.FiniteDomain((2, 5, 4)), "u": fd.FiniteDomain((1, 2, 4)), } constraint = fd.AllDistinct(domains.keys()) entailed = constraint.narrow(domains) vx = domains["x"].getValues() vy = domains["y"].getValues() vz = domains["z"].getValues() vt = domains["t"].getValues() vu = domains["u"].getValues() self.assertTrue(entailed) self.assertEqual([1], vx) self.assertEqual([2], vy) self.assertEqual([3], vz) self.assertEqual([5], vt) self.assertEqual([4], vu) def testFailure1(self): domains = { "x": fd.FiniteDomain((1, 2)), "y": fd.FiniteDomain((2, 1)), "z": fd.FiniteDomain((1, 2)), } exception = 0 try: self.constraint.narrow(domains) except propagation.ConsistencyFailure: exception = 1 self.assertTrue(exception) def testFailure2(self): domains = { "x": fd.FiniteDomain((1,)), "y": fd.FiniteDomain((2,)), "z": fd.FiniteDomain((1, 2)), } exception = 0 try: self.constraint.narrow(domains) except propagation.ConsistencyFailure: exception = 1 self.assertTrue(exception) def testFailure3(self): domains = { "x": fd.FiniteDomain((1,)), "y": fd.FiniteDomain((1,)), "z": fd.FiniteDomain((2, 3)), } exception = 0 try: self.constraint.narrow(domains) except propagation.ConsistencyFailure: exception = 1 self.assertTrue(exception) class UnaryMathConstrTC(AbstractConstraintTC): def setUp(self): self.relevant_variables = ["x"] self.irrelevant_variable = "tagada" self.constraint = fd.make_expression(self.relevant_variables, "x==2") self.domains = {"x": fd.FiniteDomain(range(4))} self.entailed_domains = {"x": fd.FiniteDomain([2])} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [2]) class BinaryMathConstrTC(AbstractConstraintTC): def setUp(self): self.relevant_variables = ["x", "y"] self.irrelevant_variable = "tagada" self.constraint = fd.make_expression(self.relevant_variables, "x+y==2") self.domains = {"x": fd.FiniteDomain(range(4)), "y": fd.FiniteDomain(range(2))} self.entailed_domains = {"x": fd.FiniteDomain([2]), "y": fd.FiniteDomain([0])} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [1, 2]) v = list(self.domains["y"].getValues()) v.sort() self.assertEqual(v, [0, 1]) class TernaryMathConstrTC(AbstractConstraintTC): def setUp(self): self.relevant_variables = ["x", "y", "z"] self.irrelevant_variable = "tagada" self.constraint = fd.make_expression(self.relevant_variables, "x+y==2 and z>1") self.domains = { "x": fd.FiniteDomain(range(4)), "y": fd.FiniteDomain(range(3)), "z": fd.FiniteDomain(range(4)), } self.entailed_domains = { "x": fd.FiniteDomain([2]), "y": fd.FiniteDomain([0]), "z": fd.FiniteDomain([2, 3]), } def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [0, 1, 2]) v = list(self.domains["y"].getValues()) v.sort() self.assertEqual(v, [0, 1, 2]) v = list(self.domains["z"].getValues()) v.sort() self.assertEqual(v, [2, 3]) class AbstractBasicConstraintTC(TestCase): """override the following methods: * setUp to initialize variables * narrowingAssertions to check that narrowing was ok """ def setUp(self): self.constraint = None # AbstractConstraint(self.relevant_variables) self.domains = {} self.entailed_domains = {} # raise NotImplementedError def testRelevance(self): """tests that relevant variables are relevant""" self.assertTrue(self.constraint.isVariableRelevant("x")) self.assertFalse(self.constraint.isVariableRelevant("tagada")) def testGetVariable(self): """test that getVariable returns the right variable""" self.assertEqual(self.constraint.getVariable(), "x") def testNarrowing(self): """tests that narrowing is performed correctly""" self.constraint.narrow(self.domains) self.narrowingAssertions() def testEntailment(self): """tests that narrowing is performed correctly""" entailed = self.constraint.narrow(self.domains) self.assertTrue(entailed) class EqualsConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.Equals("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [1]) class NotEqualsConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.NotEquals("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [0, 2]) class LesserThanConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.LesserThan("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [0]) class LesserOrEqualConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.LesserOrEqual("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [0, 1]) class GreaterThanConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.GreaterThan("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [2]) class GreaterOrEqualConstrTC(AbstractBasicConstraintTC): def setUp(self): self.constraint = fd.GreaterOrEqual("x", 1) self.domains = {"x": fd.FiniteDomain(range(3))} def narrowingAssertions(self): v = list(self.domains["x"].getValues()) v.sort() self.assertEqual(v, [1, 2]) def get_all_cases(module): from inspect import isclass all_cases = [] for name in dir(module): obj = getattr(module, name) if ( isclass(obj) and issubclass(obj, TestCase) and not name.startswith("Abstract") ): all_cases.append(obj) all_cases.sort(key=lambda x: x.__name__) return all_cases def suite(cases=None): import test_constraints cases = cases or get_all_cases(test_constraints) loader = unittest.defaultTestLoader loader.testMethodPrefix = "test" loader.sortTestMethodsUsing = None # disable sorting suites = [loader.loadTestsFromTestCase(tc) for tc in cases] return TestSuite(suites) if __name__ == "__main__": unittest.main(defaultTest="suite") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_distributors.py0000666000000000000000000001406414554256055021054 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Unit testing for constraint propagation module""" import unittest from logilab.common.testlib import TestCase, TestSuite from logilab.constraint import distributors, fd class AbstractDistributorTC(TestCase): """override the following methods: * buildDistributor to create the distributor * distributionAssertions to check that distribution was OK """ def setUp(self): self.variables = ("v1", "v2", "v3") self.domains1 = { "v1": fd.FiniteDomain([1]), "v2": fd.FiniteDomain([2, 3]), "v3": fd.FiniteDomain([4, 5, 6, 7]), } self.domains2 = { "v1": fd.FiniteDomain([1]), "v2": fd.FiniteDomain([2, 3, 4, 5, 6]), "v3": fd.FiniteDomain([7, 8, 9, 10, 11, 12, 13]), } self.distributor = self.buildDistributor() def buildDistributor(self): """returns a distributor""" raise NotImplementedError def distributionAssertions(self): """checks the distribution""" raise NotImplementedError def testFindSmallestDomain(self): """tests that the smallest domain is indeed the smallest one with at least 2 values inside""" dist = self.buildDistributor() self.assertEqual("v2", dist.findSmallestDomain(self.domains1)) self.assertEqual("v2", dist.findSmallestDomain(self.domains2)) def testFindLargestDomain(self): """tests that the largest domain is indeed the largest one""" dist = self.buildDistributor() self.assertEqual("v3", dist.findLargestDomain(self.domains1)) self.assertEqual("v3", dist.findLargestDomain(self.domains2)) def testSingleValueDomainNotDistributed(self): """tests that a domain of size 1 is not distributed""" for initial_domain in (self.domains1, self.domains2): distributed_domains = self.distributor.distribute(self.domains1) for d in distributed_domains: self.assertEqual(d["v1"].size(), initial_domain["v1"].size()) def testDistribution(self): """tests that the right domain is correctly distributed""" for initial_domain in (self.domains1, self.domains2): distributed_domains = self.distributor.distribute(initial_domain) self.distributionAssertions(initial_domain, distributed_domains) class NaiveDistributorTC(AbstractDistributorTC): def buildDistributor(self): return distributors.NaiveDistributor() def distributionAssertions(self, initial, distributed): self.assertEqual(len(distributed), 2) for d in distributed: for v in ("v1", "v3"): self.assertEqual(d[v].getValues(), initial[v].getValues()) self.assertEqual(distributed[0]["v2"].size(), 1) self.assertEqual(distributed[1]["v2"].size(), initial["v2"].size() - 1) class RandomizingDistributorTC(NaiveDistributorTC): def buildDistributor(self): return distributors.RandomizingDistributor() class DichotomyDistributorTC(AbstractDistributorTC): def buildDistributor(self): return distributors.DichotomyDistributor() def distributionAssertions(self, initial, distributed): self.assertEqual(len(distributed), 2) for d in distributed: for v in ("v1", "v3"): self.assertEqual(d[v].getValues(), initial[v].getValues()) self.assertEqual( distributed[0]["v2"].size() + distributed[1]["v2"].size(), initial["v2"].size(), ) class SplitDistributorTC(AbstractDistributorTC): def buildDistributor(self): return distributors.SplitDistributor(4) def distributionAssertions(self, initial, distributed): self.assertEqual(len(distributed), min(4, initial["v2"].size())) for d in distributed: for v in ("v1", "v3"): self.assertEqual(d[v].getValues(), initial[v].getValues()) sizes = [d["v2"].size() for d in distributed] tot_size = sum(sizes) self.assertEqual(tot_size, initial["v2"].size()) class EnumeratorDistributorTC(AbstractDistributorTC): def buildDistributor(self): return distributors.EnumeratorDistributor() def distributionAssertions(self, initial, distributed): self.assertEqual(len(distributed), initial["v2"].size()) for d in distributed: for v in ("v1", "v3"): self.assertEqual(d[v].getValues(), initial[v].getValues()) self.assertEqual(d["v2"].size(), 1) def get_all_cases(module): from inspect import isclass all_cases = [] for name in dir(module): obj = getattr(module, name) if ( isclass(obj) and issubclass(obj, TestCase) and not name.startswith("Abstract") ): all_cases.append(obj) all_cases.sort(key=lambda x: x.__name__) return all_cases def suite(cases=None): import test_distributors cases = cases or get_all_cases(test_distributors) loader = unittest.defaultTestLoader loader.testMethodPrefix = "test" loader.sortTestMethodsUsing = None # disable sorting suites = [loader.loadTestsFromTestCase(tc) for tc in cases] return TestSuite(suites) if __name__ == "__main__": unittest.main(defaultTest="suite") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_domains.py0000666000000000000000000000631114554256055017745 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Unit testing for constraint propagation module""" import unittest from logilab.common.testlib import TestCase, TestSuite from logilab.constraint import fd from logilab.constraint import propagation class AbstractDomainTC(TestCase): """override the following methods: * setUp to initialize variables """ def setUp(self): self.values = [] self.domain = None raise NotImplementedError def testGetValues(self): """tests the getValues() method""" v1 = list(self.domain.getValues()) v1.sort() v2 = self.values[:] v2.sort() self.assertEqual(v1, v2) def testSize(self): """tests the size() method""" self.assertEqual(self.domain.size(), len(self.values)) self.domain.removeValue(self.values[0]) self.assertEqual(self.domain.size(), len(self.values) - 1) def testRemove(self): """tests the removeValue() method""" self.domain.removeValue(self.values[0]) self.assertNotIn(self.values[0], self.domain.getValues()) def testEmptyDomain(self): """tests that a ConsistencyFailure exception is raised when the last value of a domain is removed""" exception = 0 for v in self.values[1:]: self.domain.removeValue(v) try: self.domain.removeValue(self.values[0]) except propagation.ConsistencyFailure: exception = 1 self.assertTrue(exception) class SuiteDomainTC(AbstractDomainTC): def setUp(self): self.values = list(range(3)) self.domain = fd.FiniteDomain(self.values) def get_all_cases(module): from inspect import isclass all_cases = [] for name in dir(module): obj = getattr(module, name) if ( isclass(obj) and issubclass(obj, TestCase) and not name.startswith("Abstract") ): all_cases.append(obj) all_cases.sort(key=lambda x: x.__name__) return all_cases def suite(cases=None): import test_domains cases = cases or get_all_cases(test_domains) loader = unittest.defaultTestLoader loader.testMethodPrefix = "test" loader.sortTestMethodsUsing = None # disable sorting suites = [loader.loadTestsFromTestCase(tc) for tc in cases] return TestSuite(suites) if __name__ == "__main__": unittest.main(defaultTest="suite") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_fi.py0000666000000000000000000005151314554256055016715 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Unit testing for constraint propagation module""" import unittest from logilab.common.testlib import TestCase from logilab.constraint.fi import ( FiniteIntervalDomain, ConsistencyFailure, NoOverlap, StartsBeforeStart, StartsBeforeEnd, StartsAfterStart, StartsAfterEnd, EndsBeforeStart, EndsBeforeEnd, EndsAfterStart, EndsAfterEnd, FiniteIntervalDistributor, Interval, ) from logilab.constraint import Repository, Solver from logilab.constraint.propagation import quiet_printer class FiniteIntervalTC(TestCase): def setUp(self): self.dom1 = FiniteIntervalDomain(0, 10, 2, 4, 1) self.dom2 = FiniteIntervalDomain(2, 5, 3) self.dom3 = FiniteIntervalDomain(2, 6, 2, 3, 0.5) def testConstructorExceptions(self): try: FiniteIntervalDomain(5, 1, 3) self.fail("Should have an assertion error here") except AssertionError: pass try: FiniteIntervalDomain(1, 5, 3, 1) self.fail("Should have an assertion error here") except AssertionError: pass try: FiniteIntervalDomain(1, 3, -2) self.fail("Should have an assertion error here") except AssertionError: pass try: FiniteIntervalDomain(1, 3, 5) self.fail("Should have an assertion error here") except AssertionError: pass def test_ConstructorDefaults(self): d = FiniteIntervalDomain(1, 3, 2) self.assertEqual(d._max_length, 2) self.assertEqual(d._resolution, 1) def test_ConstructorAjustMaxLength(self): d = FiniteIntervalDomain(0, 5, 2, 8) self.assertEqual(d._max_length, 5) def test_getValues(self): self.assertEqual(len(self.dom1.getValues()), self.dom1.size()) self.assertEqual(len(self.dom2.getValues()), self.dom2.size()) self.assertEqual(len(self.dom3.getValues()), self.dom3.size()) def test_Size(self): self.assertEqual(self.dom1.size(), 9 + 8 + 7) self.assertEqual(self.dom2.size(), 1) self.assertEqual(self.dom3.size(), 12) def test_overlap(self): self.assertTrue(self.dom1.overlap(self.dom2)) self.assertTrue(self.dom1.overlap(FiniteIntervalDomain(-5, 5, 1))) self.assertTrue(self.dom1.overlap(FiniteIntervalDomain(5, 15, 1))) self.assertTrue(self.dom1.overlap(FiniteIntervalDomain(-5, 15, 1))) self.assertFalse(self.dom1.overlap(FiniteIntervalDomain(-15, 0, 1))) self.assertFalse(self.dom1.overlap(FiniteIntervalDomain(10, 25, 1))) def test_SetLow(self): self.dom1.setLowestMin(2) self.assertEqual(self.dom1.lowestMin, 2) self.assertRaises(ConsistencyFailure, self.dom1.setLowestMin, 10) def test_SetHigh(self): self.dom1.setHighestMax(9) self.assertEqual(self.dom1.highestMax, 9) self.assertRaises(ConsistencyFailure, self.dom1.setHighestMax, -10) def test_SetMinLength(self): self.dom1.setMinLength(3) self.assertEqual(self.dom1._min_length, 3) self.dom1.setMinLength(4) self.assertEqual(self.dom1._min_length, 4) self.assertRaises(ConsistencyFailure, self.dom2.setMinLength, 5) def test_SetMaxLength(self): self.dom1.setMaxLength(3) self.assertEqual(self.dom1._max_length, 3) self.dom1.setMaxLength(2) self.assertEqual(self.dom1._max_length, 2) self.assertRaises(ConsistencyFailure, self.dom2.setMaxLength, 1) def test_FailureIfSizeEqualsZero(self): self.assertRaises(ConsistencyFailure, self.dom2.setHighestMax, 4) def test_LatestStart(self): self.assertEqual(self.dom1.highestMin, 8) self.assertEqual(self.dom2.highestMin, 2) self.assertEqual(self.dom3.highestMin, 4) def test_EarliestEnd(self): self.assertEqual(self.dom1.lowestMax, 2) self.assertEqual(self.dom2.lowestMax, 5) self.assertEqual(self.dom3.lowestMax, 4) # FIXME check all possible cases are handled class ConstraintOverlapTC(TestCase): def setUp(self): self.d1 = FiniteIntervalDomain(0, 5, 2) self.d2 = FiniteIntervalDomain(0, 5, 3) self.d3 = FiniteIntervalDomain(1, 5, 3) self.d4 = FiniteIntervalDomain(0, 4, 2) self.d5 = FiniteIntervalDomain(1, 4, 2) self.d6 = FiniteIntervalDomain(4, 7, 2) self.d7 = FiniteIntervalDomain(0, 5, 4) self.d8 = FiniteIntervalDomain(3, 8, 4) self.d9 = FiniteIntervalDomain(3, 8, 1) self.d10 = FiniteIntervalDomain(0, 6, 2) self.d11 = FiniteIntervalDomain(1, 5, 2) self.d12 = FiniteIntervalDomain(0, 6, 3) self.d13 = FiniteIntervalDomain(1, 6, 3) self.d14 = FiniteIntervalDomain(0, 6, 3) self.d15 = FiniteIntervalDomain(0, 2, 2) self.d16 = FiniteIntervalDomain(0, 2, 2) self.domains = { "v1": self.d1, "v2": self.d2, "v3": self.d3, "v4": self.d4, "v5": self.d5, "v6": self.d6, "v7": self.d7, "v8": self.d8, "v9": self.d9, "v10": self.d10, "v11": self.d11, "v12": self.d12, "v13": self.d13, "v14": self.d14, "v15": self.d15, "v16": self.d16, } # consistency failure def test_NoOverlap_ConsistencyFailure(self): c = NoOverlap("v2", "v3") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) c = NoOverlap("v3", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) def test_NoOverlap_ConsistencyFailure1(self): c = NoOverlap("v5", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) c = NoOverlap("v2", "v5") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) def test_NoOverlap_ConsistencyFailure2(self): c = NoOverlap("v15", "v16") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) c = NoOverlap("v16", "v15") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) # entailed def test_NoOverlap_Entailed(self): c = NoOverlap("v6", "v4") self.assertEqual(c.narrow(self.domains), 1) c = NoOverlap("v4", "v6") self.assertEqual(c.narrow(self.domains), 1) def test_NoOverlap_Entailed1(self): c = NoOverlap("v1", "v3") self.assertEqual(c.narrow(self.domains), 1) c = NoOverlap("v3", "v1") self.assertEqual(c.narrow(self.domains), 1) def test_NoOverlap_Entailed2(self): c = NoOverlap("v7", "v8") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d7, FiniteIntervalDomain(0, 4, 4)) self.assertEqual(self.d8, FiniteIntervalDomain(4, 8, 4)) def test_NoOverlap_Entailed2bis(self): c = NoOverlap("v8", "v7") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d7, FiniteIntervalDomain(0, 4, 4)) self.assertEqual(self.d8, FiniteIntervalDomain(4, 8, 4)) def test_NoOverlap_Entailed3(self): c = NoOverlap("v7", "v10") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d7, FiniteIntervalDomain(0, 4, 4)) self.assertEqual(self.d10, FiniteIntervalDomain(4, 6, 2)) def test_NoOverlap_Entailed3bis(self): c = NoOverlap("v10", "v7") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d7, FiniteIntervalDomain(0, 4, 4)) self.assertEqual(self.d10, FiniteIntervalDomain(4, 6, 2)) def test_NoOverlap_Entailed4(self): c = NoOverlap("v12", "v13") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d12, FiniteIntervalDomain(0, 3, 3)) self.assertEqual(self.d13, FiniteIntervalDomain(3, 6, 3)) def test_NoOverlap_Entailed4bis(self): c = NoOverlap("v13", "v12") self.assertEqual(c.narrow(self.domains), 1) self.assertEqual(self.d12, FiniteIntervalDomain(0, 3, 3)) self.assertEqual(self.d13, FiniteIntervalDomain(3, 6, 3)) # not entailed def test_NoOverlap_NotEntailed(self): c = NoOverlap("v4", "v1") self.assertEqual(c.narrow(self.domains), 0) def test_NoOverlap_NotEntailed2(self): c = NoOverlap("v8", "v9") self.assertEqual(c.narrow(self.domains), 0) c = NoOverlap("v9", "v8") self.assertEqual(c.narrow(self.domains), 0) def test_NoOverlap_NotEntailed3(self): c = NoOverlap("v11", "v12") self.assertEqual(c.narrow(self.domains), 0) c = NoOverlap("v12", "v11") self.assertEqual(c.narrow(self.domains), 0) def test_NoOverlap_NotEntailed4(self): c = NoOverlap("v12", "v14") self.assertEqual(c.narrow(self.domains), 0) c = NoOverlap("v14", "v12") self.assertEqual(c.narrow(self.domains), 0) def test_equality(self): c1 = NoOverlap("v12", "v14") c2 = NoOverlap("v14", "v12") c3 = NoOverlap("v15", "v12") self.assertEqual(c1, c2) self.assertNotEqual(c1, c3) self.assertNotEqual(c2, c3) self.assertEqual(c3, c3) def test_hash(self): c1 = NoOverlap("v12", "v14") c2 = NoOverlap("v14", "v12") c3 = NoOverlap("v15", "v12") d = {c1: "hello", c2: "hello", c3: "hello"} self.assertEqual(len(d), 2) class ConstraintTC(TestCase): def setUp(self): self.d1 = FiniteIntervalDomain(5, 10, 1, 1) self.d2 = FiniteIntervalDomain(2, 7, 1, 1) self.d3 = FiniteIntervalDomain(8, 10, 1, 1) self.d4 = FiniteIntervalDomain(3, 10, 5, 6) self.d5 = FiniteIntervalDomain(4, 10, 5) self.d6 = FiniteIntervalDomain(0, 3, 2) self.d7 = FiniteIntervalDomain(0, 5, 4) self.d8 = FiniteIntervalDomain(3, 8, 4) self.d9 = FiniteIntervalDomain(3, 8, 1) self.d10 = FiniteIntervalDomain(0, 6, 2) self.domains = { "v1": self.d1, "v2": self.d2, "v3": self.d3, "v4": self.d4, "v5": self.d5, "v6": self.d6, "v7": self.d7, "v8": self.d8, "v9": self.d9, "v10": self.d10, } ## # StartsBeforeStart ## def test_StartsBeforeStart_NotEntailed(self): c = StartsBeforeStart("v2", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 0) def test_StartsBeforeStart_ConsistencyFailure(self): c = StartsBeforeStart("v3", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) def test_StartsBeforeStart_Entailed(self): c = StartsBeforeStart("v2", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 1) ## # StartsBeforeEnd ## def test_StartsBeforeEnd_NotEntailed(self): c = StartsBeforeEnd("v2", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 0) def test_StartsBeforeEnd_ConsistencyFailure(self): c = StartsBeforeEnd("v3", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) def test_StartsBeforeEnd_Entailed(self): c = StartsBeforeEnd("v4", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 1) ## # EndsBeforeStart ## def test_EndsBeforeStart_Entailed(self): c = EndsBeforeStart("v2", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_EndsBeforeStart_NotEntailed(self): c = EndsBeforeStart("v3", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 0) def test_EndsBeforeStart_NotEntailed_withRemoval(self): c = EndsBeforeStart("v1", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d1.highestMax, self.d3.highestMin) def test_EndsBeforeStart_ConsistencyFailure(self): c = EndsBeforeStart("v3", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) ## # EndsBeforeEnd ## def test_EndsBeforeEnd_Entailed(self): c = EndsBeforeEnd("v2", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_EndsBeforeEnd_NotEntailed(self): c = EndsBeforeEnd("v2", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d2.highestMax, 7) def test_EndsBeforeEnd_NotEntailed_withRemoval(self): c = EndsBeforeEnd("v1", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d1.highestMax, self.d2.highestMax) def test_EndsBeforeEnd_ConsistencyFailure(self): c = EndsBeforeEnd("v3", "v2") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) ## # StartsAfterStart ## def test_StartsAfterStart_Entailed(self): c = StartsAfterStart("v3", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_StartsAfterStart_NotEntailed(self): c = StartsAfterStart("v1", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d1.lowestMin, 5) def test_StartsAfterStart_NotEntailed_withRemoval(self): c = StartsAfterStart("v2", "v1") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d2.lowestMin, self.d1.lowestMin) def test_StartsAfterStart_ConsistencyFailure(self): c = StartsAfterStart("v2", "v3") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) ## # StartsAfterEnd ## def test_StartsAfterEnd_Entailed(self): c = StartsAfterEnd("v3", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_StartsAfterEnd_NotEntailed_withRemoval(self): c = StartsAfterEnd("v1", "v4") ret = c.narrow(self.domains) self.assertEqual(ret, 0) self.assertEqual(self.d1.lowestMin, self.d4.lowestMax) def test_StartsAfterEnd_ConsistencyFailure(self): c = StartsAfterEnd("v2", "v3") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) ## # EndsAfterStart ## def test_EndsAfterStart_Entailed(self): c = EndsAfterStart("v4", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_EndsAfterStart_NotEntailed(self): c = EndsAfterStart("v4", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 0) def test_EndsAfterStart_ConsistencyFailure(self): c = EndsAfterStart("v2", "v3") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) ## # EndsAfterEnd ## def test_EndsAfterEnd_Entailed(self): c = EndsAfterEnd("v4", "v2") ret = c.narrow(self.domains) self.assertEqual(ret, 1) def test_EndsAfterEnd_NotEntailed(self): c = EndsAfterEnd("v4", "v3") ret = c.narrow(self.domains) self.assertEqual(ret, 0) def test_EndsAfterEnd_ConsistencyFailure(self): c = EndsAfterEnd("v2", "v3") self.assertRaises(ConsistencyFailure, c.narrow, self.domains) class DistributorTC(TestCase): def setUp(self): self.d = FiniteIntervalDistributor() def test_DistributeDifferentLengths(self): d1 = FiniteIntervalDomain(0, 5, 3, 5) d2 = FiniteIntervalDomain(0, 20, 1) domains = { "v1": d1, "v2": d2, } dom1, dom2 = self.d.distribute(domains) self.assertEqual(dom1["v2"], dom2["v2"]) self.assertEqual(dom1["v2"], d2) self.assertNotEqual(dom1["v1"], d1) self.assertNotEqual(dom2["v1"], d1) self.assertEqual(dom1["v1"]._max_length, d1._min_length) self.assertEqual(dom2["v1"]._min_length, d1._min_length + d1._resolution) self.assertEqual(d1.size(), dom1["v1"].size() + dom2["v1"].size()) def test_DistributeSameLengths(self): d1 = FiniteIntervalDomain(lowestMin=0, highestMax=5, min_length=4) d2 = FiniteIntervalDomain(lowestMin=0, highestMax=20, min_length=1) domains = { "v1": d1, "v2": d2, } dom1, dom2 = self.d.distribute(domains) self.assertEqual(dom1["v2"], dom2["v2"]) self.assertEqual(dom1["v2"], d2) self.assertNotEqual(dom1["v1"], d1) self.assertNotEqual(dom2["v1"], d1) self.assertEqual(dom1["v1"].size(), 1) self.assertEqual(dom1["v1"].highestMax, d1._min_length + d1.lowestMin) self.assertEqual(dom2["v1"].lowestMin, d1._resolution + d1.lowestMin) self.assertEqual(d1.size(), dom1["v1"].size() + dom2["v1"].size()) class PlannerTC(TestCase): def setUp(self): self.d = FiniteIntervalDistributor() self.verbose = 1 def solve_repo1(self, constraints): dom1 = FiniteIntervalDomain(0, 15, 5) dom2 = FiniteIntervalDomain(0, 15, 5) dom3 = FiniteIntervalDomain(0, 15, 5) repo = Repository( ["A", "B", "C"], {"A": dom1, "B": dom2, "C": dom3}, constraints, printer=quiet_printer, ) s = Solver(self.d, printer=quiet_printer) answers = list(s.solve_all(repo, verbose=self.verbose)) self.assertEqual(len(answers), 2) # import pprint # pprint.pprint( list(answers) ) def test_pb1(self): constraints = [ StartsAfterEnd("B", "A"), StartsAfterEnd("C", "A"), NoOverlap("B", "C"), ] self.solve_repo1(constraints) def test_pb2(self): constraints = [ EndsBeforeStart("A", "B"), EndsBeforeStart("A", "C"), NoOverlap("B", "C"), ] self.solve_repo1(constraints) def solve_repo2(self, constraints): dom1 = FiniteIntervalDomain(0, 20, 5) dom2 = FiniteIntervalDomain(0, 20, 5) dom3 = FiniteIntervalDomain(0, 20, 10) dom4 = FiniteIntervalDomain(0, 20, 5) repo = Repository( ["A", "B", "C", "D"], {"A": dom1, "B": dom2, "C": dom3, "D": dom4}, constraints, printer=quiet_printer, ) s = Solver(self.d, printer=quiet_printer) answers = list(s.solve_all(repo, verbose=1)) self.assertEqual(len(answers), 6) expected = [ { "A": Interval(0.00, 5.00), "B": Interval(5.00, 10.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, { "A": Interval(0.00, 5.00), "B": Interval(6.00, 11.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, { "A": Interval(0.00, 5.00), "B": Interval(7.00, 12.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, { "A": Interval(0.00, 5.00), "B": Interval(8.00, 13.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, { "A": Interval(0.00, 5.00), "B": Interval(9.00, 14.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, { "A": Interval(0.00, 5.00), "B": Interval(10.00, 15.00), "C": Interval(5.00, 15.00), "D": Interval(15.00, 20.00), }, ] self.assertEqual(expected, answers) def test_pb3(self): constraints = [ StartsAfterEnd("B", "A"), StartsAfterEnd("C", "A"), StartsAfterEnd("D", "B"), StartsAfterEnd("D", "C"), ] self.solve_repo2(constraints) def test_pb4(self): constraints = [ StartsAfterEnd("B", "A"), StartsAfterEnd("C", "A"), StartsAfterEnd("D", "B"), StartsAfterEnd("D", "C"), StartsAfterEnd("D", "A"), ] self.solve_repo2(constraints) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_propagation.py0000666000000000000000000001302514554256055020636 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Unit testing for constraint propagation module""" import unittest import os from logilab.common.testlib import TestCase from logilab.constraint.propagation import Repository, ConsistencyFailure, Solver from logilab.constraint import fd from logilab.constraint.distributors import DefaultDistributor class Repository_TC(TestCase): def setUp(self): self.domains = {} self.variables = list("abcdef") for v in self.variables: self.domains[v] = fd.FiniteDomain(range(6)) self.repo = Repository(self.variables, self.domains) def testVCGDraw(self): for v1 in self.variables: for v2 in self.variables: if v1 < v2: self.repo.addConstraint( fd.make_expression((v1, v2), f"{v1} < {v2}") ) try: try: self.repo.vcg_draw("toto.vcg") except OSError as exc: self.fail( "This test cannot run in the testing environment" "because I cannot write the file.\n" "The error message was: \n%s" % exc ) finally: os.unlink("toto.vcg") def testGetDomains(self): doms = self.repo.getDomains() self.assertEqual(doms, self.domains) def testDistribute(self): d = [] for distributed in self.repo.distribute(DefaultDistributor()): d.append(distributed) self.assertEqual(len(d), 2) def testConsistencyNoConstraint(self): self.repo.consistency() for v, dom in self.repo.getDomains().items(): self.assertEqual(dom.size(), 6) def testConsistency(self): for v1 in self.variables: for v2 in self.variables: if v1 < v2: self.repo.addConstraint( fd.make_expression((v1, v2), f"{v1} < {v2}") ) self.repo.consistency() for v, dom in self.repo.getDomains().items(): self.assertEqual(dom.size(), 1) def testInconsistency(self): self.repo.addConstraint(fd.make_expression(("a", "b"), "a < b")) self.repo.addConstraint(fd.make_expression(("a", "b"), "a > b")) try: self.repo.consistency() self.fail("No ConsistencyFailure raised") except ConsistencyFailure: pass class Sover_TC(TestCase): def setUp(self): self.solver = Solver() self.domains = {} self.variables = list("abcdef") for v in self.variables: self.domains[v] = fd.FiniteDomain(list(range(6))) self.repo = Repository(self.variables, self.domains) for v1 in self.variables: for v2 in self.variables: if v1 < v2: self.repo.addConstraint( fd.make_expression((v1, v2), f"{v1} < {v2}") ) def testSolveOne(self): solution = self.solver.solve_one(self.repo) self.assertEqual(solution, {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5}) def testSolve(self): solutions = self.solver.solve(self.repo) self.assertEqual(solutions, [{"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5}]) def testSolveAll(self): solutions = [] for s in self.solver.solve_all(self.repo): solutions.append(s) self.assertEqual(solutions, [{"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5}]) def testNolutionSolve(self): self.repo.addConstraint(fd.make_expression(("a", "b"), "b < a")) solutions = self.solver.solve(self.repo) self.assertEqual(solutions, []) class SolverBest_TC(TestCase): def setUp(self): self.solver = Solver() self.domains = {} self.variables = list("abc") for v in self.variables: self.domains[v] = fd.FiniteDomain(range(6)) self.repo = Repository(self.variables, self.domains) for v1 in self.variables: for v2 in self.variables: if v1 < v2: self.repo.addConstraint( fd.make_expression((v1, v2), f"{v1} < {v2}") ) def costFunc(self, a, b, c): return -(a * a + b * b + c * c) def testSolveBest(self): solutions = [] for s in self.solver.solve_best(self.repo, self.costFunc): solutions.append(s) costs = [self.costFunc(**sol[0]) for sol in solutions] sorted_costs = costs[:] sorted_costs.sort() sorted_costs.reverse() self.assertEqual(costs, sorted_costs) self.assertEqual(costs, [s[1] for s in solutions]) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/test/test_validation.py0000666000000000000000000000612014554256055020443 0ustar00rootroot# copyright 2002-2021 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-constraint. # # logilab-constraint is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # logilab-constraint is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-constraint. If not, see . """Validation testing for constraint propagation module""" import sys from six.moves import StringIO from logilab.common.testlib import TestCase, unittest_main, Tags from logilab.constraint import fd, Repository, Solver from logilab.constraint.propagation import quiet_printer from logilab.constraint.distributors import EnumeratorDistributor class Queens8_TC(TestCase): tags = Tags("slow") size = 8 nb_sols = 92 verbose = 0 def setUp(self): variables = [] domains = {} constraints = [] for i in range(self.size): name = "Q%d" % i variables.append(name) domains[name] = fd.FiniteDomain([(i, j) for j in range(self.size)]) for q1 in variables: for q2 in variables: if q1 < q2: c = fd.make_expression( (q1, q2), "%(q1)s[0] < %(q2)s[0] and " "%(q1)s[1] != %(q2)s[1] and " "abs(%(q1)s[0]-%(q2)s[0]) != " "abs(%(q1)s[1]-%(q2)s[1])" % {"q1": q1, "q2": q2}, ) constraints.append(c) self.repo = Repository(variables, domains, constraints, printer=quiet_printer) sys.stdout = StringIO() def tearDown(self): sys.stdout = sys.__stdout__ def testQueensWithEnumerator(self): solver = Solver(EnumeratorDistributor(), printer=quiet_printer) solutions = solver.solve(self.repo, verbose=self.verbose) self.assertEqual(len(solutions), self.nb_sols) def testQueensWithDefaultDistributor(self): solver = Solver(printer=quiet_printer) solutions = solver.solve(self.repo, verbose=self.verbose) self.assertEqual(len(solutions), self.nb_sols) class Queens4_TC(Queens8_TC): size = 4 nb_sols = 2 class Queens5_TC(Queens8_TC): size = 5 nb_sols = 10 class Queens6_TC(Queens8_TC): size = 6 nb_sols = 4 class Queens7_TC(Queens8_TC): size = 7 nb_sols = 40 class Queens6Verbose_TC(Queens6_TC): verbose = 3 class Queens9_TC(Queens8_TC): size = 9 nb_sols = 352 class Queens10_TC(Queens8_TC): size = 10 nb_sols = 724 if __name__ == "__main__": unittest_main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1706122285.0 logilab-constraint-1.0/tox.ini0000666000000000000000000000435314554256055015242 0ustar00rootroot[tox] envlist=py3,py3-from-forge,yamllint,black,flake8,check-manifest [testenv] deps = pytest git+https://github.com/psycojoker/pytest-capture-deprecatedwarnings commands = {envpython} -m pytest {posargs:test} [testenv:py3-from-forge] deps = hg-evolve # to hide some warnings pytest git+https://github.com/Psycojoker/pytest-capture-deprecatedwarnings commands = pip install -U hg+https://forge.extranet.logilab.fr/open-source/logilab-common {envpython} -m pytest {posargs:test} [testenv:pypi-publish] basepython = python3 skip_install = true allowlist_externals = rm deps = twine passenv = TWINE_USERNAME TWINE_PASSWORD commands = rm -rf build dist .egg .egg-info python3 setup.py sdist bdist_wheel twine check dist/* twine upload --skip-existing dist/* [testenv:deb-publish] passenv = JENKINS_USER JENKINS_TOKEN basepython = python3 skip_install = true allowlist_externals = rm sh hg python3 deps = httpie commands = hg clean --all --dirs --files rm -rf build dist .egg .egg-info python3 setup.py sdist sh -c "PACKAGE_NAME=$(python3 setup.py --name) && VERSION=$(python3 setup.py --version) && \ cd dist && \ tar xf $PACKAGE_NAME-$VERSION.tar.gz && \ cd $PACKAGE_NAME-$VERSION && \ cp -a {toxinidir}/debian . && \ mk-origtargz --rename ../$PACKAGE_NAME-$VERSION.tar.gz && \ dpkg-buildpackage -us -uc --no-check-builddeps --build=source " sh -c "cd dist && dcmd zip latest.zip *.changes" http -f POST https://{env:JENKINS_USER}:{env:JENKINS_TOKEN}@jenkins.intra.logilab.fr/job/pkg-from-dsc/buildWithParameters DIST=buster source.zip@dist/latest.zip REPO=buster PUBLISH=true [testenv:yamllint] skip_install = true deps = yamllint commands = yamllint . [testenv:black] basepython = python3 skip_install = true deps = black >= 22.1.0 commands = black -t py37 --check . [testenv:black-run] basepython = python3 skip_install = true deps = black >= 21.12b0 commands = black -t py37 . [testenv:flake8] skip_install = true deps = flake8 >= 3.6 commands = flake8 --show-source {posargs} [flake8] basepython = python3 format = pylint ignore = W503, E203, E731, E231 max-line-length = 100 [testenv:check-manifest] skip_install = true deps = check-manifest commands = {envpython} -m check_manifest {toxinidir}