python-glpk-0.4.52/ChangeLog0000644000175000017500000000170412214561540013776 0ustar jppjpp2013-09-13 Joao Pedro Pedroso * updated interface to GLPK version 4.52 2010-04-25 Joao Pedro Pedroso * solved some issues related to debianization 2010-04-25 Joao Pedro Pedroso * bug corrections on the python Gnu MathProg's parser 2010-04-25 Joao Pedro Pedroso * implemented support for modifying glpk model's data in python * updated interface to GLPK version 4.43 * cleaned up code for this version 2009-02-10 Joao Pedro Pedroso * updated interface to GLPK version 4.36 * changed main class name in glpk.py from 'lpx' to 'glpk' * now uses file glpk.h from the glpk distribution; 2007-05-28 Joao Pedro Pedroso * updated interface to GLPK version 4.16 2007-04-19 Joao Pedro Pedroso * updated interface to GLPK version 4.15 2007-04-01 Joao Pedro Pedroso * version 0.1 released, for GLPK version 4.12 python-glpk-0.4.52/COPYING0000644000175000017500000004330411222343023013251 0ustar jppjpp GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 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. 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 Library 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 St, 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 Library General Public License instead of this License. python-glpk-0.4.52/debian/0000755000175000017500000000000012224564027013450 5ustar jppjpppython-glpk-0.4.52/debian/changelog0000644000175000017500000000642312224562226015326 0ustar jppjpppython-glpk (0.4.52-1) experimental; urgency=low * updated interface to GLPK version 4.52 * Bug fix: "glpk.glp_printf() fails", thanks to Xypron (Closes: #597017) [printf cannot be implemented due to a limitation in swig; function glp_printf is no longer available from python]. * Bug fix: "FTBFS against glpk 4.51-1", thanks to Sebastien Villemot (Closes: #714211). -- Joao Pedro Pedroso Mon, 02 Sep 2013 13:49:30 +0100 python-glpk (0.4.45-1) unstable; urgency=low * updated interface to GLPK version 4.45 (Closes: #638649). -- Joao Pedro Pedroso Mon, 29 Aug 2011 14:02:43 +0100 python-glpk (0.4.43-2) unstable; urgency=low * Corrected debian/control file (Closes: #573696). * Corrected debian/control file (Closes: #578424). -- Joao Pedro Pedroso Tue, 18 May 2010 10:03:38 +0100 python-glpk (0.4.43-1) unstable; urgency=low * Initial release: solved some issues related to debianization. * Cannot be reproduced with current version of glpk (Closes: #577405). * Dependencies fixed; now depends on glpk 4.43 (Closes: #578424). * Cannot be reproduced (Closes: #548267). -- Joao Pedro Pedroso Wed, 12 May 2010 11:53:48 +0100 python-glpk (0.3.43-4) unstable; urgency=low * added dependency to python-ply -- Joao Pedro Pedroso Tue, 4 May 2010 11:30:15 +0100 python-glpk (0.3.43-3) unstable; urgency=low * using a modified local copy of glpk.h for compiling in 64 bit machines -- Joao Pedro Pedroso Tue, 3 May 2010 10:30:15 +0100 python-glpk (0.3.43-2) unstable; urgency=low * bug corrections on the python Gnu MathProg's parser -- Joao Pedro Pedroso Tue, 29 Apr 2010 17:30:15 +0100 python-glpk (0.3.43-1) unstable; urgency=low * implemented support for modifying glpk model's data in python * updated interface to GLPK version 4.43 * cleaned up code for this version -- Joao Pedro Pedroso Tue, 20 Apr 2010 18:30:15 +0100 python-glpk (0.1.38-1) unstable; urgency=low * Version compatible with glpk v4.38 -- Joao Pedro Pedroso Sat, 01 Aug 2009 21:14:15 +0100 python-glpk (0.1.16-4) unstable; urgency=low * debian/control: - changed section to 'math' -- Jan Alonzo Tue, 29 May 2007 04:40:00 +1000 python-glpk (0.1.16-3) unstable; urgency=low * debian/changelog: - Copy maintainer from control file to make it lint-free. -- Jan Alonzo Tue, 29 May 2007 04:30:00 +1000 python-glpk (0.1.16-2) unstable; urgency=low * debian/control: - Build-Depends on versioned make >= 3.8 - Build-Depends on debhelper 5.0.37.2 as per lintian suggestion - Build-Depends on libglpk-dev greater or equal to 4.16 -- Jan Alonzo Tue, 29 May 2007 04:23:29 +1000 python-glpk (0.1.16-1) unstable; urgency=low * new upstream version 0.1.16 -- Jan Alonzo Tue, 29 May 2007 02:37:29 +1000 python-glpk (0.1.15-1) unstable; urgency=low * new upstream version 0.1.15 -- Jan Alonzo Tue, 22 May 2007 01:27:25 +1000 python-glpk (0.1-1) unstable; urgency=low * Initial release (Closes: #400690) -- Jan Alonzo Fri, 16 Mar 2007 20:03:20 +1100 python-glpk-0.4.52/debian/compat0000644000175000017500000000000211372504302014637 0ustar jppjpp7 python-glpk-0.4.52/debian/control0000644000175000017500000000203512221033754015046 0ustar jppjppSource: python-glpk Section: python Priority: optional Maintainer: Joao Pedro Pedroso Build-Depends: debhelper (>= 7.0.50~), cdbs (>= 0.4.90~), python-all-dev (>= 2.6.6-3~), swig, make (>= 3.8), libglpk-dev (>= 4.52), libglpk-dev (<< 4.53) Standards-Version: 3.9.4 X-Python-Version: >= 2.6 Homepage: http://www.dcc.fc.up.pt/~jpp/code/python-glpk Package: python-glpk Architecture: any Depends: ${python:Depends}, ${shlibs:Depends}, ${misc:Depends}, libglpk0 (>= 4.45), libglpk0 (<< 4.53), python-ply (>= 3.4) Provides: ${python:Provides} Description: Python bindings to the GNU Linear Programming Kit GLPK (GNU Linear Programming Kit) is intended for solving large-scale linear programming (LP), mixed integer programming (MIP), and other related problems. It is a set of routines written in ANSI C and organized in the form of a callable library. . GLPK supports the GNU MathProg language, which is a subset of the AMPL language. GLPK also supports the standard MPS and LP formats. . This is the Python bindings to GLPK. . python-glpk-0.4.52/debian/copyright0000644000175000017500000000245011372531554015406 0ustar jppjppThis work was packaged for Debian by: Joao Pedro Pedroso on Wed, 12 May 2010 11:53:48 +0100 It was downloaded from: Upstream Author: Joao Pedro Pedroso Filipe Brandao Copyright: License: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". The Debian packaging is: Copyright (C) 2010 Joao Pedro Pedroso and is licensed under the GPL version 3, see above. python-glpk-0.4.52/debian/docs0000644000175000017500000000001311372506445014320 0ustar jppjppreadme.txt python-glpk-0.4.52/debian/examples0000644000175000017500000000001311372505771015207 0ustar jppjppexamples/* python-glpk-0.4.52/debian/rules0000755000175000017500000000033312216351703014523 0ustar jppjpp#!/usr/bin/make -f DEB_COMPRESS_EXCLUDE := example.mps DEB_SRCDIR := src include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk include /usr/share/cdbs/1/class/makefile.mk python-glpk-0.4.52/debian/source/0000755000175000017500000000000011372504302014741 5ustar jppjpppython-glpk-0.4.52/debian/source/format0000644000175000017500000000001411372504302016147 0ustar jppjpp3.0 (quilt) python-glpk-0.4.52/examples/0000755000175000017500000000000011365516202014041 5ustar jppjpppython-glpk-0.4.52/examples/diet.py0000644000175000017500000000201311365332244015336 0ustar jppjppfrom glpk import * # create an LP as an instance of class "glpk", # based on the model "diet.mod" (coming in glpk's "examples") problem = glpk("models/diet.mod") # solve problem.solve() print "\n\nsolution:", problem.solution() # define/modify problem data: # "F" and "a" are, respectively, a "set" and a "param" in "diet.mod"; # now, they can be accessed in Python as members of the "glpk" instance problem.F += ['Bacalhau'] # add a new food problem.a['Bacalhau','Calorie'] = 87.3 # nutrients problem.a['Bacalhau','Protein'] = 98.7 problem.a['Bacalhau','Calcium'] = 17.3 problem.a['Bacalhau','Iron'] = 12.3 problem.a['Bacalhau','Vitamin-A'] = 12.3 # update and solve problem.update() problem.solve() print "\n\nsolution:", problem.solution() # one more update problem.F.remove('Bacalhau') # remove food for key in problem.a.keys(): if 'Bacalhau' in key: del problem.a[key] # update and solve problem.update() problem.solve() print "\n\nsolution:", problem.solution() python-glpk-0.4.52/examples/example.mod0000644000175000017500000000022511234615370016175 0ustar jppjppvar x >=0 integer; var y >= 0; maximize z: x + y; subject to r: x + y <= 10; subject to s: x + 10*y <= 1; subject to t: 10*x + y <= 1; end; python-glpk-0.4.52/examples/example.mps0000644000175000017500000001010111234615370016207 0ustar jppjpp*NAME: flugpl *ROWS: 18 *COLUMNS: 18 *INTEGER: 11 *NONZERO: 46 *BEST SOLN: 1201500 (opt) *LP SOLN: 1167185.73 *SOURCE: Harvey M. Wagner * John W. Gregory (Cray Research) * E. Andrew Boyd (Rice University) *APPLICATION: airline model *COMMENTS: no integer variables are binary * * NAME FLUGPL ROWS N KOSTEN E ANZ1 G STD1 L UEB1 E ANZ2 G STD2 L UEB2 E ANZ3 G STD3 L UEB3 E ANZ4 G STD4 L UEB4 E ANZ5 G STD5 L UEB5 E ANZ6 G STD6 L UEB6 COLUMNS STM1 KOSTEN 2700 ANZ1 1 STM1 STD1 150 UEB1 -20 STM1 ANZ2 0.9 MARK0000 'MARKER' 'INTORG' ANM1 KOSTEN 1500 STD1 -100 ANM1 ANZ2 1 MARK0001 'MARKER' 'INTEND' UE1 KOSTEN 30 STD1 1 UE1 UEB1 1 MARK0002 'MARKER' 'INTORG' STM2 KOSTEN 2700 ANZ2 -1 STM2 STD2 150 UEB2 -20 STM2 ANZ3 0.9 ANM2 KOSTEN 1500 STD2 -100 ANM2 ANZ3 1 MARK0003 'MARKER' 'INTEND' UE2 KOSTEN 30 STD2 1 UE2 UEB2 1 MARK0004 'MARKER' 'INTORG' STM3 KOSTEN 2700 ANZ3 -1 STM3 STD3 150 UEB3 -20 STM3 ANZ4 0.9 ANM3 KOSTEN 1500 STD3 -100 ANM3 ANZ4 1 MARK0005 'MARKER' 'INTEND' UE3 KOSTEN 30 STD3 1 UE3 UEB3 1 MARK0006 'MARKER' 'INTORG' STM4 KOSTEN 2700 ANZ4 -1 STM4 STD4 150 UEB4 -20 STM4 ANZ5 0.9 ANM4 KOSTEN 1500 STD4 -100 ANM4 ANZ5 1 MARK0007 'MARKER' 'INTEND' UE4 KOSTEN 30 STD4 1 UE4 UEB4 1 MARK0008 'MARKER' 'INTORG' STM5 KOSTEN 2700 ANZ5 -1 STM5 STD5 150 UEB5 -20 STM5 ANZ6 0.9 ANM5 KOSTEN 1500 STD5 -100 ANM5 ANZ6 1 MARK0009 'MARKER' 'INTEND' UE5 KOSTEN 30 STD5 1 UE5 UEB5 1 MARK0010 'MARKER' 'INTORG' STM6 KOSTEN 2700 ANZ6 -1 STM6 STD6 150 UEB6 -20 ANM6 KOSTEN 1500 STD6 -100 MARK0011 'MARKER' 'INTEND' UE6 KOSTEN 30 STD6 1 UE6 UEB6 1 RHS RR ANZ1 60 STD1 8000 RR STD2 9000 STD3 8000 RR STD4 10000 STD5 9000 RR STD6 12000 BOUNDS UP BB ANM1 18 LO BB STM2 57 UP BB STM2 75 UP BB ANM2 18 LO BB STM3 57 UP BB STM3 75 UP BB ANM3 18 LO BB STM4 57 UP BB STM4 75 UP BB ANM4 18 LO BB STM5 57 UP BB STM5 75 UP BB ANM5 18 LO BB STM6 57 UP BB STM6 75 UP BB ANM6 18 ENDATA python-glpk-0.4.52/examples/example.py0000644000175000017500000000031411365014245016044 0ustar jppjppimport glpk print "starting..." example = glpk.glpk("example.mod") example.update() example.solve() print "solution:", example.solution() print "solution is also here: x =", example.x, "y =", example.y python-glpk-0.4.52/examples/example_refman.py0000644000175000017500000000300311364671233017377 0ustar jppjppfrom glpk.glpkpi import * size = 1000+1 ia = intArray(size) ja = intArray(size) ar = doubleArray(size) prob = glp_create_prob() glp_set_prob_name(prob, "sample") glp_set_obj_dir(prob, GLP_MAX) glp_add_rows(prob, 3) glp_set_row_name(prob, 1, "p") glp_set_row_bnds(prob, 1, GLP_UP, 0.0, 100.0) glp_set_row_name(prob, 2, "q") glp_set_row_bnds(prob, 2, GLP_UP, 0.0, 600.0) glp_set_row_name(prob, 3, "r") glp_set_row_bnds(prob, 3, GLP_UP, 0.0, 300.0) glp_add_cols(prob, 3) glp_set_col_name(prob, 1, "x1") glp_set_col_bnds(prob, 1, GLP_LO, 0.0, 0.0) glp_set_obj_coef(prob, 1, 10.0) glp_set_col_name(prob, 2, "x2") glp_set_col_bnds(prob, 2, GLP_LO, 0.0, 0.0) glp_set_obj_coef(prob, 2, 6.0) glp_set_col_name(prob, 3, "x3") glp_set_col_bnds(prob, 3, GLP_LO, 0.0, 0.0) glp_set_obj_coef(prob, 3, 4.0) ia[1] = 1; ja[1] = 1; ar[1] = 1.0 # /* a[1,1] = 1 */ ia[2] = 1; ja[2] = 2; ar[2] = 1.0 # /* a[1,2] = 1 */ ia[3] = 1; ja[3] = 3; ar[3] = 1.0 # /* a[1,3] = 1 */ ia[4] = 2; ja[4] = 1; ar[4] = 10.0 # /* a[2,1] = 10 */ ia[5] = 3; ja[5] = 1; ar[5] = 2.0 # /* a[3,1] = 2 */ ia[6] = 2; ja[6] = 2; ar[6] = 4.0 # /* a[2,2] = 4 */ ia[7] = 3; ja[7] = 2; ar[7] = 2.0 # /* a[3,2] = 2 */ ia[8] = 2; ja[8] = 3; ar[8] = 5.0 # /* a[2,3] = 5 */ ia[9] = 3; ja[9] = 3; ar[9] = 6.0 # /* a[3,3] = 6 */ glp_load_matrix(prob, 9, ia, ja, ar) glp_simplex(prob, None) Z = glp_get_obj_val(prob) x1 = glp_get_col_prim(prob, 1) x2 = glp_get_col_prim(prob, 2) x3 = glp_get_col_prim(prob, 3) print "\nZ = %g; x1 = %g; x2 = %g; x3 = %g\n" %(Z, x1, x2, x3) del prob python-glpk-0.4.52/examples/models/0000755000175000017500000000000011365056743015335 5ustar jppjpppython-glpk-0.4.52/examples/models/diet.mod0000644000175000017500000000705511365051145016761 0ustar jppjpp# STIGLER'S NUTRITION MODEL # # This model determines a least cost diet which meets the daily # allowances of nutrients for a moderately active man weighing 154 lbs. # # References: # Dantzig G B, "Linear Programming and Extensions." # Princeton University Press, Princeton, New Jersey, 1963, # Chapter 27-1. set N; /* nutrients */ set F; /* foods */ param b{N}; /* required daily allowances of nutrients */ param a{F,N}; /* nutritive value of foods (per dollar spent) */ var x{f in F} >= 0; /* dollars of food f to be purchased daily */ s.t. nb{n in N}: sum{f in F} a[f,n] * x[f] = b[n]; /* nutrient balance (units) */ minimize cost: sum{f in F} x[f]; /* total food bill (dollars) */ data; param : N : b := Calorie 3 /* thousands */ Protein 70 /* grams */ Calcium 0.8 /* grams */ Iron 12 /* milligrams */ Vitamin-A 5 /* thousands IUs */ Vitamin-B1 1.8 /* milligrams */ Vitamin-B2 2.7 /* milligrams */ Niacin 18 /* milligrams */ Vitamin-C 75 /* milligrams */ ; set F := Wheat Cornmeal Cannedmilk Margarine Cheese Peanut-B Lard Liver Porkroast Salmon Greenbeans Cabbage Onions Potatoes Spinach Sweet-Pot Peaches Prunes Limabeans Navybeans; param a default 0 : Calorie Protein Calcium Iron Vitamin-A Vitamin-B1 := # (1000) (g) (g) (mg) (1000IU) (mg) Wheat 44.7 1411 2.0 365 . 55.4 Cornmeal 36 897 1.7 99 30.9 17.4 Cannedmilk 8.4 422 15.1 9 26 3 Margarine 20.6 17 .6 6 55.8 .2 Cheese 7.4 448 16.4 19 28.1 .8 Peanut-B 15.7 661 1 48 . 9.6 Lard 41.7 . . . .2 . Liver 2.2 333 .2 139 169.2 6.4 Porkroast 4.4 249 .3 37 . 18.2 Salmon 5.8 705 6.8 45 3.5 1 Greenbeans 2.4 138 3.7 80 69 4.3 Cabbage 2.6 125 4 36 7.2 9 Onions 5.8 166 3.8 59 16.6 4.7 Potatoes 14.3 336 1.8 118 6.7 29.4 Spinach 1.1 106 . 138 918.4 5.7 Sweet-Pot 9.6 138 2.7 54 290.7 8.4 Peaches 8.5 87 1.7 173 86.8 1.2 Prunes 12.8 99 2.5 154 85.7 3.9 Limabeans 17.4 1055 3.7 459 5.1 26.9 Navybeans 26.9 1691 11.4 792 . 38.4 : Vitamin-B2 Niacin Vitamin-C := # (mg) (mg) (mg) Wheat 33.3 441 . Cornmeal 7.9 106 . Cannedmilk 23.5 11 60 Margarine . . . Cheese 10.3 4 . Peanut-B 8.1 471 . Lard .5 5 . Liver 50.8 316 525 Porkroast 3.6 79 . Salmon 4.9 209 . Greenbeans 5.8 37 862 Cabbage 4.5 26 5369 Onions 5.9 21 1184 Potatoes 7.1 198 2522 Spinach 13.8 33 2755 Sweet-Pot 5.4 83 1912 Peaches 4.3 55 57 Prunes 4.3 65 257 Limabeans 38.2 93 . Navybeans 24.6 217 . ; end; python-glpk-0.4.52/examples/models/multi.dat0000644000175000017500000000224011252033013017133 0ustar jppjppdata; set ORIG := GARY CLEV PITT ; set DEST := FRA DET LAN WIN STL FRE LAF ; set PROD := bands coils plate ; param supply (tr): GARY CLEV PITT := bands 4000e-1 700 800 coils 800 1600 1800 plate 200 300 300 ; param demand (tr): FRA DET LAN WIN STL FRE LAF := bands 300 300 100 75 650 225 250 coils 500 750 400 250 950 850 500 plate 100 100 0 50 200 100 250 ; param limit default 625 ; param cost := [*,*,bands]: FRA DET LAN WIN STL FRE LAF := GARY 30 10 8 10 11 71 6 CLEV 22 7 10 7 21 82 13 PITT 19 11 12 10 25 83 15 [*,*,coils]: FRA DET LAN WIN STL FRE LAF := GARY 39 14 11 14 16 82 8 CLEV 27 9 12 9 26 95 17 PITT 24 14 17 13 28 99 20 [*,*,plate]: FRA DET LAN WIN STL FRE LAF := GARY 41 15 12 16 17 86 8 CLEV 29 9 13 9 28 99 18 PITT 26 14 17 13 31 104 20 ; python-glpk-0.4.52/examples/models/multi.mod0000644000175000017500000000150207474157132017166 0ustar jppjppset ORIG; # origins set DEST; # destinations set PROD; # products param supply {ORIG,PROD} >= 0; # amounts available at origins param demand {DEST,PROD} >= 0; # amounts required at destinations check {p in PROD}: sum {i in ORIG} supply[i,p] = sum {j in DEST} demand[j,p]; param limit {ORIG,DEST} >= 0; param cost {ORIG,DEST,PROD} >= 0; # shipment costs per unit var Trans {ORIG,DEST,PROD} >= 0; # units to be shipped minimize Total_Cost: sum {i in ORIG, j in DEST, p in PROD} cost[i,j,p] * Trans[i,j,p]; subject to Supply {i in ORIG, p in PROD}: sum {j in DEST} Trans[i,j,p] = supply[i,p]; subject to Demand {j in DEST, p in PROD}: sum {i in ORIG} Trans[i,j,p] = demand[j,p]; subject to Multi {i in ORIG, j in DEST}: sum {p in PROD} Trans[i,j,p] <= limit[i,j]; python-glpk-0.4.52/examples/models/net3.dat0000644000175000017500000000106611364130736016675 0ustar jppjppdata; set D_CITY := NE SE ; set W_CITY := BOS EWR BWI ATL MCO ; set DW_LINKS := (NE,BOS) (NE,EWR) (NE,BWI) (SE,EWR) (SE,BWI) (SE,ATL) (SE,MCO); param p_supply default 450 ; param w_demand := BOS 90, EWR 120, BWI 120, ATL 70, MCO 50; param: pd_cost pd_cap := NE 2.5 250 SE 3.5 250 ; param: dw_cost dw_cap := NE BOS 1.7 100 NE EWR 0.7 100 NE BWI 1.3 100 SE EWR 1.3 100 SE BWI 0.8 100 SE ATL 0.2 100 SE MCO 2.1 100 ; python-glpk-0.4.52/examples/models/net3.mod0000644000175000017500000000175411250306102016672 0ustar jppjppset D_CITY; set W_CITY; set DW_LINKS within (D_CITY cross W_CITY); param p_supply >= 0; # amount available at plant param w_demand {W_CITY} >= 0; # amounts required at warehouses check: p_supply = sum {j in W_CITY} w_demand[j]; param pd_cost {D_CITY} >= 0; # shipment costs/1000 packages param dw_cost {DW_LINKS} >= 0; param pd_cap {D_CITY} >= 0; # max packages that can be shipped param dw_cap {DW_LINKS} >= 0; var PD_Ship {i in D_CITY} >= 0, <= pd_cap[i]; var DW_Ship {(i,j) in DW_LINKS} >= 0, <= dw_cap[i,j]; # packages to be shipped minimize Total_Cost: sum {i in D_CITY} pd_cost[i] * PD_Ship[i] + sum {(i,j) in DW_LINKS} dw_cost[i,j] * DW_Ship[i,j]; subject to P_Bal: sum {i in D_CITY} PD_Ship[i] = p_supply; subject to D_Bal {i in D_CITY}: PD_Ship[i] = sum {(i,j) in DW_LINKS} DW_Ship[i,j]; subject to W_Bal {j in W_CITY}: sum {(i,j) in DW_LINKS} DW_Ship[i,j] = w_demand[j]; display dw_cost; python-glpk-0.4.52/examples/models/plan.lp0000644000175000017500000000234611222343023016607 0ustar jppjpp\* plan.lp *\ Minimize value: .03 bin1 + .08 bin2 + .17 bin3 + .12 bin4 + .15 bin5 + .21 alum + .38 silicon Subject To yield: bin1 + bin2 + bin3 + bin4 + bin5 + alum + silicon = 2000 fe: .15 bin1 + .04 bin2 + .02 bin3 + .04 bin4 + .02 bin5 + .01 alum + .03 silicon <= 60 cu: .03 bin1 + .05 bin2 + .08 bin3 + .02 bin4 + .06 bin5 + .01 alum <= 100 mn: .02 bin1 + .04 bin2 + .01 bin3 + .02 bin4 + .02 bin5 <= 40 mg: .02 bin1 + .03 bin2 + .01 bin5 <= 30 al: .70 bin1 + .75 bin2 + .80 bin3 + .75 bin4 + .80 bin5 + .97 alum >= 1500 si1: .02 bin1 + .06 bin2 + .08 bin3 + .12 bin4 + .02 bin5 + .01 alum + .97 silicon >= 250 si2: .02 bin1 + .06 bin2 + .08 bin3 + .12 bin4 + .02 bin5 + .01 alum + .97 silicon <= 300 Bounds bin1 <= 200 bin2 <= 2500 400 <= bin3 <= 800 100 <= bin4 <= 700 bin5 <= 1500 End \* eof *\ python-glpk-0.4.52/examples/models/samp1.mps0000644000175000017500000000171011222343023017054 0ustar jppjppNAME SAMP1 ROWS N Z G R1 G R2 G R3 COLUMNS X1 R1 2.0 R2 1.0 X1 R3 5.0 Z 3.0 MARK0001 'MARKER' 'INTORG' X2 R1 -1.0 R2 -1.0 X2 R3 3.0 Z 7.0 X3 R1 1.0 R2 -6.0 X3 Z -1.0 MARK0002 'MARKER' 'INTEND' X4 R1 -1.0 R2 4.0 X4 R3 1.0 Z 1.0 RHS RHS1 R1 1.0 RHS1 R2 8.0 RHS1 R3 5.0 BOUNDS UP BND1 X1 4.0 LO BND1 X2 2.0 UP BND1 X2 5.0 UP BND1 X3 1.0 LO BND1 X4 3.0 UP BND1 X4 8.0 ENDATA python-glpk-0.4.52/examples/models/steel.dat0000644000175000017500000000022711253216140017125 0ustar jppjpp set PROD := bands coils; param: rate profit market := bands 200 25 6000 coils 140 30 4000 ; param avail := 40; python-glpk-0.4.52/examples/models/steel.mod0000644000175000017500000000112211364132646017142 0ustar jppjppset PROD; # products param rate {PROD} > 0; # tons produced per hour param avail >= 0; # hours available in week param profit {PROD}; # profit per ton param market {PROD} >= 0; # limit on tons sold in week var Make {p in PROD} >= 0, <= market[p]; # tons produced maximize total_profit: sum {p in PROD} profit[p] * Make[p]; # Objective: total profits from all products Time: sum {p in PROD} (1/rate[p]) * Make[p] <= avail; # Constraint: total of hours used by all # products may not exceed hours available python-glpk-0.4.52/examples/test.py0000644000175000017500000000546311365047132015403 0ustar jppjppfrom glpk import * def problem0(): print "\n>>problem 0:\n" problem = glpk("models/samp1.mps") problem.solve() print problem.solution() problem = glpk("models/plan.lp") problem.solve() print problem.solution() def problem1(): print "\n>>problem 1:\n" problem = glpk("models/net3.mod","models/net3.dat") problem.solve() sol1 = problem.solution() problem.pd_cap['NE'] = 10000 problem.dw_cap['NE', 'BOS'] = 50 problem.p_supply = 450 problem.update() problem.solve() sol2 = problem.solution() print "solution1:", sol1 print "solution2:", sol2 def problem2(): print "\n>>problem 2:\n" problem = glpk("models/multi.mod","models/multi.dat") problem.update() problem.solve() print problem.supply['GARY','bands'] print "solution:", problem.solution() def problem3(): print "\n>>problem 3:\n" problem = glpk("models/steel.mod","models/steel.dat") problem.update() problem.solve() print "solution:", problem.solution() print "problem.total_profit =", problem.total_profit print "problem.Make =", problem.Make def problem4(): print "\n>>problem 4:\n" problem = glpk("models/steel.mod") problem.PROD = ['bands', 'coils'] problem.rate['bands'] = 200 problem.rate['coils'] = 140 problem.profit['bands'] = 25 problem.profit['coils'] = 30 problem.market['bands'] = 6000 problem.market['coils'] = 4000 problem.avail = 40 problem.update() problem.solve() print "problem.solution() =", problem.solution() print "problem.sets() =", problem.sets() print "problem.parameters() =", problem.parameters() print "problem.variables() =", problem.variables() print "problem.constraints() =", problem.constraints() print "problem.objectives() =", problem.objectives() print "problem.Make =", problem.Make print "problem.Make['bands'] =", problem.Make['bands'] print "problem.Make['bands'].value() =", problem.Make['bands'].value() print "problem.total_profit =", problem.total_profit print "problem.total_profit.value() =", problem.total_profit.value() problem.Make >= 10 problem.Make['coils'] <= 100 0 <= problem.total_profit <= 100000 problem.Make <= 15 problem.Make['bands'] <= 10 print problem.Make['bands']._bounds() #problem.Time <= 10 print "problem.total_profit =", problem.total_profit problem.solve() #print "problem.Make.bounds() =", problem.Make._bounds() #print "problem.Make['coils'].bounds() =", problem.Make['coils']._bounds() #print "problem.Make['bands'].bounds() =", problem.Make['bands']._bounds() print "problem.solution() =", problem.solution() if __name__ == "__main__": problem0() problem1() problem2() problem3() problem4() python-glpk-0.4.52/Makefile0000644000175000017500000000103112214102741013647 0ustar jppjppDIR := $(shell basename `pwd`) VER := '0.4.52' all: clean debuild clean ( cd .. && pwd && tar zcvf $(DIR).tar.gz $(DIR)/* ) ( cd .. && cp $(DIR).tar.gz python-glpk_$(VER).orig.tar.gz ) debuild pub: all cp -p ../python-glpk_$(VER).orig.tar.gz ~/public_html/code/python-glpk cp -p ../python-glpk_$(VER)-*.deb ~/public_html/code/python-glpk start: clean rm -rf debian ( cd .. && pwd && tar zcvf $(DIR).tar.gz $(DIR)/* ) cp -p ../$(DIR).tar.gz ../$(DIR).orig.tar.gz clean: make -C src clean .PHONY: install new deb web clean python-glpk-0.4.52/readme.txt0000644000175000017500000000033311253725470014225 0ustar jppjppSimple interface for using GLPK in Python. This requires GLPK to be installed, and uses the SWIG package for producing the API. Notice that the glpk's C keyword 'in' is renamed '_in' in Python, for avoiding conflict. python-glpk-0.4.52/src/0000755000175000017500000000000012221034160013000 5ustar jppjpppython-glpk-0.4.52/src/ChangeLog0000644000175000017500000000170412214561771014573 0ustar jppjpp2013-09-13 Joao Pedro Pedroso * updated interface to GLPK version 4.52 2010-04-25 Joao Pedro Pedroso * solved some issues related to debianization 2010-04-25 Joao Pedro Pedroso * bug corrections on the python Gnu MathProg's parser 2010-04-25 Joao Pedro Pedroso * implemented support for modifying glpk model's data in python * updated interface to GLPK version 4.43 * cleaned up code for this version 2009-02-10 Joao Pedro Pedroso * updated interface to GLPK version 4.36 * changed main class name in glpk.py from 'lpx' to 'glpk' * now uses file glpk.h from the glpk distribution; 2007-05-28 Joao Pedro Pedroso * updated interface to GLPK version 4.16 2007-04-19 Joao Pedro Pedroso * updated interface to GLPK version 4.15 2007-04-01 Joao Pedro Pedroso * version 0.1 released, for GLPK version 4.12 python-glpk-0.4.52/src/Makefile0000644000175000017500000000045211365034307014454 0ustar jppjppall: make -C swig all cp swig/glpkpi.py python/glpkpi.py python setup.py build install: all python setup.py install clean: make -C swig clean rm -rf build rm -f *.pyc *.pyo _glpkpi.so glpkpi.py rm -f python/*.pyc python/*.pyo python/_glpkpi.so python/glpkpi.py .PHONY: all install clean python-glpk-0.4.52/src/python/0000755000175000017500000000000012221034160014321 5ustar jppjpppython-glpk-0.4.52/src/python/__init__.py0000644000175000017500000003565211372025056016457 0ustar jppjpp""" Filename: glpk.py (define a class for calling GLPK from Python) -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. """ from model_objects import * from glpk_parser import * from glpkpi import * from array import * import sys import os import tempfile LOG = False VERBOSE = False DEBUG = False GLPK_VERSION = glp_version(); class glpk: def __init__(self, mod_file = None, dat_file = None): ### # parameter structure: NOT USED YET self._parm = glp_smcp(); glp_init_smcp(self._parm); #self._parm.msg_lev = GLP_MSG_OFF; # silent modes #self._parm.msg_lev = GLP_MSG_ALL; self._parm.msg_lev = GLP_MSG_ERR; #self._parm.meth = GLP_DUAL; self._parm.meth = GLP_DUALP; #self._parm.meth = GLP_PRIMAL; self._tran = None self._lp = None self._type = {} self._model = "" self._ptype = None self._bounds = {} self._ready = False if mod_file == None: if VERBOSE: print "creating problem -- no file associated" self._lp = glp_create_prob(); elif mod_file.find(".mps") != -1: if VERBOSE: print "creating problem from mps file" self._ptype = "mps" self._lp = glp_create_prob(); ret = glp_read_mps(self._lp, GLP_MPS_FILE, None, mod_file);# !self._parm if ret != 0: print "Error reading model", mod_file raise IOError self._read_variables() elif mod_file.find(".lp") != -1: if VERBOSE: print "creating problem from lp file" self._ptype = "lp" self._lp = glp_create_prob(); ret = glp_read_lp(self._lp, None, mod_file);# !self._parm self._read_variables() elif mod_file.find(".mod") != -1: if VERBOSE: print "creating problem from mod file" self._ptype = "mod" t = mod_file.rfind('.') if t<0: name = mod_file else: name = mod_file[:t] f, tmp_file = tempfile.mkstemp() # genereate a temporary model file parser = glpk_parser(mod_file, dat_file) parser.generate_model(tmp_file) if VERBOSE: print "temporary model file '%s' created" % (tmp_file) # read model mod_file = tmp_file self._lp = glp_create_prob(); self._tran = glp_mpl_alloc_wksp(); ret = glp_mpl_read_model(self._tran, mod_file, 0); if ret != 0: print "Error reading model", mod_file raise IOError # load data #glp_term_out(GLP_OFF); f, output = tempfile.mkstemp() os.close(f) ret = glp_mpl_generate(self._tran, output) if ret != 0: print "Error generating model" raise IOError load_data(parser, output, self) if not DEBUG: os.remove(output) os.remove(tmp_file) #glp_term_out(GLP_ON); self._cols = self._rows = None def _delete(self): if self._tran and glp_mpl_free_wksp: glp_mpl_free_wksp(self._tran); if self._lp and glp_delete_prob: glp_delete_prob(self._lp); def _reload(self): if self._ptype != 'mod': return self._delete() # read model s = self._dump() f, mod_file = tempfile.mkstemp() os.write(f, s) os.close(f) self._lp = glp_create_prob(); self._tran = glp_mpl_alloc_wksp(); ret = glp_mpl_read_model(self._tran, mod_file, 0); if ret != 0: print "Error reading model", mod_file raise IOError #if not VERBOSE: glp_term_out(GLP_OFF); ret = glp_mpl_generate(self._tran, None); if ret != 0: print "Error generating model" raise IOError glp_mpl_build_prob(self._tran, self._lp); #if not VERBOSE: glp_term_out(GLP_ON); if not DEBUG: os.remove(mod_file) def _dump(self): if self._ptype != 'mod': return s = self._model+"\ndata;\n" for name in self._sets_names: if type(self[name])!=dict: val = str(self[name]).strip('[]') s += "set %s := %s;\n" % (name,val) else: for subname in sorted(self[name]): if type(subname)==str: sname = '\''+subname+'\'' elif type(subname)!=tuple: sname = str(subname) else: sname = str(subname).strip('()') val = str(self[name][subname]).strip('[]') s += "set %s[%s] := %s;\n" % (name,sname,val) for name in self._params_names: if type(self[name])!=dict: if name not in self._default or self[name] != None: s += "param %s := %s;\n" % (name,self[name]) else: val = self[name] if val==None: val = "" s += "param %s default %s := %s;\n" % (name,self._default[name],val) else: if name not in self._default: s += "param %s :=" % (name) else: s += "param %s default %s :=" % (name,self._default[name]) for subname in sorted(self[name]): if type(subname)==str: sname = '\''+subname+'\'' elif type(subname)!=tuple: sname = str(subname) else: sname = str(subname).strip('()') s += " [%s] %s" % (sname,self[name][subname]) s += ";\n" s += "end;\n" return s def _get_col_bnds(self, i): lb = glp_get_col_lb(self._lp, i); ub = glp_get_col_ub(self._lp, i); tp = glp_get_col_type(self._lp, i); bnds = (None, None) if tp == GLP_LO: bnds = (('>=',lb),None) elif tp == GLP_UP: bnds = (None,('<=',ub)) elif tp == GLP_DB: bnds =(('>=',lb),('<=',ub)) elif tp == GLP_FX: bnds = ('=',lb) return bnds def _get_row_bnds(self, i): lb = glp_get_row_lb(self._lp, i); ub = glp_get_row_ub(self._lp, i); tp = glp_get_row_type(self._lp, i); bnds = (None, None) if tp == GLP_LO: bnds = (('>=',lb),None) elif tp == GLP_UP: bnds = (None,('<=',ub)) elif tp == GLP_DB: bnds =(('>=',lb),('<=',ub)) elif tp == GLP_FX: bnds = ('=',lb) return bnds def _get_bounds(self, name): rows = self._rows cols = self._cols if name in rows: p = rows[name] if len(p)!=1: return None return self._get_row_bnds(p[0]) elif name in cols: p = cols[name] if len(p)!=1: return None return self._get_col_bnds(p[0]) else: return None def _read_variables(self): bounds = self._default_bounds = {} cols = self._cols = {} for i in xrange(1,glp_get_num_cols(self._lp)+1): name = glp_get_col_name(self._lp, i) tname = name[:max(0,name.find('['))] bounds[name] = self._get_col_bnds(i) cols[name] = [i] if tname != "": if tname not in self._cols: cols[tname] = [i] else: cols[tname].append(i) rows = self._rows = {} for i in xrange(1,glp_get_num_rows(self._lp)+1): name = glp_get_row_name(self._lp, i) tname = name[:max(0,name.find('['))] bounds[name] = self._get_row_bnds(i) rows[name] = [i] if tname != "": if tname not in self._cols: rows[tname] = [i] else: rows[tname].append(i) def _apply_bounds(self): rows = self._rows cols = self._cols types = { (None,None): GLP_FR, ('>=',None): GLP_LO, (None,'<='): GLP_UP, ('>=','<='): GLP_DB, ('='): GLP_FX } def conv(bnds): if bnds[0] == '=': return GLP_FX, bnds[1], bnds[1] else: l, lb = bnds[0], None if l != None: l,lb = l u, ub = bnds[1], None if u != None: u, ub = u if lb == None: lb = 0.0 if ub == None: ub = 0.0 return types[l,u], lb, ub for name in sorted(self._bounds): bnds = self._bounds[name] if len(bnds)==2 and name in self._default_bounds: dbnds = self._default_bounds[name] if dbnds[0]!='=': if bnds[0]==None: bnds = dbnds[0], bnds[1] if bnds[1]==None: bnds = bnds[0], dbnds[1] tp, lb, ub = conv(bnds) if name in cols: for i in cols[name]: glp_set_col_bnds(self._lp, i, tp, lb, ub); elif name in rows: for i in rows[name]: glp_set_row_bnds(self._lp, i, tp, lb, ub); else: print 'model object not found!' def _set_bounds(self, varname,(_type,_value)): dic = self._bounds if varname in dic: bnds = dic[varname] if bnds[0] == '=': bnds = (None, None) else: bnds = dic[varname] = (None, None) if _type == '=': bnds = ('=', _value) elif _type == '<=': bnds = (bnds[0], (_type,_value)) elif _type == '>=': bnds = ((_type,_value), bnds[1]) dic[varname] = bnds def _rm_bounds(self, varname): dic = self._bounds if varname in dic: del dic[varname] def _instantiate_solution(self): sol = {} name = glp_get_obj_name(self._lp) if glp_get_num_int(self._lp) == 0: # problem is continuous value = glp_get_obj_val(self._lp) sol[name] = value for i in xrange(1,glp_get_num_cols(self._lp)+1): name = glp_get_col_name(self._lp, i) value = glp_get_col_prim(self._lp, i) sol[name] = value else: # problem is MIP value = glp_mip_obj_val(self._lp) sol[name] = value for i in xrange(1,glp_get_num_cols(self._lp)+1): name = glp_get_col_name(self._lp, i) if glp_get_col_kind(self._lp, i) == GLP_CV: value = glp_mip_col_val(self._lp, i) elif glp_get_col_kind(self._lp, i) in [GLP_IV, GLP_BV]: # to avoid finite precision problems: value = int(round(glp_mip_col_val(self._lp, i),0)) else: print "unkown col kind" raise AttributeError sol[name] = value self._sol = sol load_solution(sol, self) def __del__(self): print "deleting glpk object" self._delete() def __getitem__(self, name): return self.__dict__[name] def __setitem__(self, name, value): self.__dict__[name] = value def __setattr__(self, name, value): self.__dict__[name] = value def __iter__(self): for name in self.__dict__: if name in self._type: yield name # interface def update(self): self._dump() self._reload() self._ready = True def solution(self): try: return self._sol except: return None def sets(self): try: return self._sets_names except: return None def parameters(self): try: return self._params_names except: return None def variables(self): try: return self._vars_names except: return None def constraints(self): try: return self._constraints_names except: return None def objectives(self): try: return self._objectives_names except: return None def typeof(self, obj): try: return self._type[obj] except: return None def solve(self, instantiate = True, bounds = True): #glp_term_out(GLP_OFF); if not self._ready: self.update() #glp_term_out(GLP_ON); if self._cols == None or self._rows == None: self._read_variables() if bounds: self._apply_bounds() if glp_get_num_int(self._lp) == 0: # problem is continuous res = glp_simplex(self._lp, self._parm) # self._parm !!! else: # problem is MIP if self._tran: glp_mpl_build_prob(self._tran, self._lp); res = glp_simplex(self._lp, self._parm); # ??? should use dual simplex ??? glp_intopt(self._lp, None); if self._tran: ret = glp_mpl_postsolve(self._tran, self._lp, GLP_MIP); if ret != 0: print "Error on postsolving model" raise AttributeError if instantiate: self._instantiate_solution() if res != 0: return None else: return glp_get_obj_val(self._lp); python-glpk-0.4.52/src/python/glpk_lex.py0000644000175000017500000000442211372025056016514 0ustar jppjpp""" Filename: glpk_lex.py (Python lexer for GnuMathProg language) -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. """ import ply.lex as lex import re reserved = {} # List of token names. This is always required tokens = [ 'LPAREN', 'RPAREN', 'LBRACK', 'RBRACK', 'STRING', 'INTEGER', 'FLOAT', 'PROMPT', ] + list(reserved.values()) # Regular expression rules for simple tokens t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACK = r'\[' t_RBRACK = r'\]' t_PROMPT = r'>>>' literals = ":;=," def t_STRING(t): r'''[a-zA-Z_0-9]*[a-zA-Z_+][a-zA-Z_\+\-0-9]* | [a-zA-Z_][a-zA-Z_\+\-0-9]* | [a-zA-Z_\+\-0-9]*[a-zA-Z_] | \'([^\']|\'\')*\' | \"([^\"]|\"\")*\" ''' t.value = t.value.strip('\'\"\n') t.value = t.value.replace('\'','') t.value = t.value.replace('\"','') return t def t_FLOAT(t): r'''[\+\-]?[0-9]*[\.]?[0-9]*([eE][\-\+]?[0-9]+) | [\+\-]?[0-9]*\.[0-9]+''' t.value = float(t.value) return t def t_INTEGER(t): r'[\+\-]?\d+' t.value = int(t.value) return t # Define a rule so we can track line numbers def t_NEWLINE(t): r'\n+' t.lexer.lineno += len(t.value) # A string containing ignored characters t_ignore = ' \r\t,' # Error handling rule def t_error(t): print "Illegal character %s" % repr(t.value[0]) t.lexer.skip(1) # Build the lexer lexer = lex.lex() #lexer = lex.lex(optimize=1) python-glpk-0.4.52/src/python/glpk_parser.py0000644000175000017500000002361611372025056017226 0ustar jppjpp""" Filename: glpk_lex.py (Python parser for GnuMathProg language) -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. """ import re import ply.lex as lex import ply.yacc as yacc # Get the token map from the lexer. from glpk_lex import * from model_objects import * class regexcache: def __init__(self): self.cache = {} def __getitem__(self, pattern): if pattern not in self.cache: rgx = re.compile(pattern,re.X) self.cache[pattern] = rgx else: rgx = self.cache[pattern] return rgx regex = regexcache() non_scolon = r'''(?:(?:\".*?\"|\'.*?\'|[^;])*;)''' class glpk_parser: def __init__(self, mod_file, dat_file = None): try: fmod = open(mod_file) self.mod = fmod.read() except: self.mod = "" try: fdat = open(dat_file) self.dat = fdat.read() except: self.dat = None self.parse() def __getitem__(self, name): return self.__dict__[name] def __setitem__(self, name, value): self.__dict__[name] = value def parse_data_decls(self, ldat): defaults = {} # parameters default values pattern = r'(param)\s+(\w+)\s*((default)\s*(\w*))?' rgx_param = regex[pattern] pattern = r'(param)\s*((default)\s*([^\s]))?\s*(:[^:]*)?:([^:]*):' rgx_param_tab = regex[pattern] for decl in ldat: m = rgx_param_tab.match(decl) if m != None: lst = m.group(6).split() for name in lst: defval = m.group(4) if defval: defaults[name] = defval continue m = rgx_param.match(decl) if m != None: name = m.group(2) defval = m.group(5) if defval: defaults[name] = defval continue self.default_values = defaults def parse_model_decls(self, lmod): types = {} # set/param/var values = {} # {}/None names = [] pattern = r'''(?:(set|param|var|subject\s*to|s.t.|minimize|maximize)\s+)? (\w*)\s*(\"(?:[^\"]|\"\")*\"|\'(?:[^\']|\'\')*\')? \s*(\{[^}]*\})?.*''' rgx = regex[pattern] for decl in lmod: m = rgx.match(decl) if m != None: _type = m.group(1) if _type == None: _type = 's.t.' _name = m.group(2) _domain = m.group(4) names.append(_name) if _type == 's.t.': types[_name] = 'constraint' if _type.startswith('subject'): types[_name] = 'constraint' elif _type in ['maximize','minimize']: types[_name] = 'objective' elif _type == 'set' and ':=' in decl: types[_name] = 'setx' else: types[_name] = _type if _domain!=None: values[_name] = {} else: values[_name] = None self.names = names self.types = types self.values = values def parse(self): mod = self.mod dat = self.dat lmod = [] ldat = [] # remove comments (#... and /*...*/) pattern = r'''(\".*?\"|\'.*?\'|/\*.*?\*/|\#.*)''' rgx = regex[pattern] def comrepl(match): s = match.group(0) if s[0] in '/#': return '' else: return s mod = rgx.sub(comrepl,mod) if dat != None: dat = rgx.sub(comrepl,dat) # parse model file pattern = r'[A-Za-z_]'+ non_scolon rgx = regex[pattern] tmod = rgx.findall(mod) # read data section i, n = 0, len(tmod) set_dacls = {} param_decls = {} while i < n: if tmod[i].startswith('data'): i += 1 ldat = [] while i < n and not tmod[i].startswith('end'): ldat.append(tmod[i]) i += 1 i += 1 else: if tmod[i].replace(' ','') != 'end;': lmod.append(tmod[i]) i += 1 # parse data file if dat != None: pattern = r'''set(?:(?:\".*?\"|\'.*?\'|[^;])*;) | param(?:(?:\".*?\"|\'.*?\'|[^;])*;)''' rgx = regex[pattern] ldat = rgx.findall(dat) # parse model decls self.parse_model_decls(lmod) # parse data decls self.parse_data_decls(ldat) # store model s = "" for decl in lmod: s += decl+'\n' self.model = s self.lmod = lmod self.ldat = ldat def generate_model(self, filename): s = "" lmod = self.lmod ldat = self.ldat types = self.types for x in lmod: if x.startswith('set') or x.startswith('var') or x.startswith('param'): s += x+'\n' for x in types: if types[x] in ['set','setx','param']: s += "display %s;\n" % x s += "data;\n" for decl in ldat: s += decl+'\n' s += "end;" f = open(filename, "w") print >>f, s def load_data(parser, outputfile, glpkobj): text = open(outputfile).read() pattern = r'''Display\sstatement\sat\sline\s[0-9]+ | \w+\shas\sempty\scontent | \w+\sis\sempty''' rgx = regex[pattern] text = rgx.sub('', text) rgx = regex[r'(\w+)\s*(\=|\:)'] text = rgx.sub(r'>>> \1 \2', text) rgx = regex[r'(\w+)\s*(\[.*?\])\s*(\=|\:)'] text = rgx.sub(r'>>> \1\2 \3', text) lst = yacc.parse(text) for x in parser.names: _type = parser.types[x] _value = parser.values[x] glpkobj._type[x] = _type if _type == 'var': glpkobj[x] = var(glpkobj, x, _value) elif _type == 'constraint': glpkobj[x] = constraint(glpkobj, x, _value) elif _type == 'objective': glpkobj[x] = objective(glpkobj, x, _value) else: glpkobj[x] = _value for (_name, _ind, _val) in lst: if _ind == None: glpkobj[_name] = _val else: glpkobj[_name][_ind] = _val glpkobj._model = parser.model glpkobj._default = parser.default_values glpkobj._sets_names = [] glpkobj._vars_names = [] glpkobj._params_names = [] glpkobj._constraints_names = [] glpkobj._objectives_names = [] for x in parser.names: typ = parser.types[x] if typ == 'set': glpkobj._sets_names.append(x) elif typ == 'param': glpkobj._params_names.append(x) elif typ == 'var': glpkobj._vars_names.append(x) elif typ == 'constraint': glpkobj._constraints_names.append(x) elif typ == 'objective': glpkobj._objectives_names.append(x) def load_solution(solution, glpkobj): s = "" for x in solution: s += ">>> %s = %s\n" % (x,float(solution[x])) lst = yacc.parse(s) for (_name, _ind, _val) in lst: if _ind == None: try: glpkobj[_name]._value = _val except: glpkobj[_name] = var(glpkobj, _name, _val) else: glpkobj[_name][_ind]._value = _val def p_data(p): '''data : data decl |''' if len(p) == 1: p[0] = [] else: p[0] = p[1] p[0].append(p[2]) def p_decl(p): '''decl : PROMPT set | PROMPT param''' p[0] = p[2] def p_name(p): '''name : STRING | STRING tuple''' if len(p) == 2: p[0] = (p[1],None) else: if len(p[2])==1: p[2] = p[2][0] p[0] = (p[1],p[2]) def p_set(p): '''set : name ':' list''' p[0] = (p[1][0],p[1][1],p[3]) def p_param(p): '''param : name '=' record''' p[0] = (p[1][0],p[1][1],p[3]) def p_list(p): '''list : record | list record''' if len(p)==2: p[0] = [p[1]] else: p[0] = p[1] p[0].append(p[2]) def p_tuple(p): '''tuple : LPAREN list RPAREN | LBRACK list RBRACK''' p[0] = tuple(p[2]) def p_record(p): '''record : FLOAT | INTEGER | STRING | tuple''' p[0] = p[1] def p_error(p): # Error rule for syntax errors print "[",p,"]" print "<",p.value,">" print "Syntax error in input!" import sys sys.exit(0) def show_tokens(): while True: tok = lexer.token() if not tok: break print tok # Build the parser yacc.yacc(write_tables=0, debug=0) python-glpk-0.4.52/src/python/model_objects.py0000644000175000017500000001063611372025056017524 0ustar jppjpp""" Filename: model_objects.py (tools for processing GnuMathProg language) -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. """ def name_to_index(name): if type(name)==tuple: s = '' for i in range(len(name)): if i>0: s += ',' if type(name[i])==str: if ',' not in name[i]: t = name[i] else: t = "'%s'" % (name[i]) else: t = str(name[i]) s += t return s else: return name def join_bounds(cur, new): if cur == None: return new if new == None: return cur if new[0] == '=': return new else: cur = list(cur) if cur[0] == '=': cur = (None, None) if new[0] != None: cur[0] = new[0] if new[1] != None: cur[1] = new[1] return tuple(cur) class var: def __init__(self, prob, name, value = None, bnds = None): self._prob = prob self._name = name self._subvars = None if type(value) != dict: self._value = value else: self._subvars = value def value(self): return self._value def _bounds(self): try: bnds = self._prob._bounds[self._name] except: bnds = None return bnds def _clear(self): self._prob._rm_bounds(self._name) def __del__(self): self.clear() def _set_bounds(self, bounds): self._prob._set_bounds(self._name, bounds) if self._subvars: for x in self: self[x]._set_bounds(bounds) def __eq__(self, value): self._set_bounds(('=', value)) for x in self: self[x] == value return nothing() def __ge__(self, value): self._set_bounds(('>=', value)) return nothing() def __le__(self, value): self._set_bounds(('<=', value)) return nothing() def __str__(self): if self._subvars == None: return '(var:'+str(self._value)+')' else: return '(var:'+str(self._subvars)+')' def __repr__(self): return str(self) def __getitem__(self, name): if self._subvars == None: return name = name_to_index(name) itemname = "%s[%s]" % (self._name, name) if name not in self._subvars: _var = var(self._prob, itemname) self._subvars[name] = _var else: _var = self._subvars[name] return _var def __setitem__(self, name, value): if self._subvars == None: return name = name_to_index(name) itemname = "%s[%s]" % (self._name, name) new_var = var(self._prob, itemname) self._subvars[name] = new_var new_var == value def __iter__(self): if self._subvars == None: return for x in self._subvars: yield x class constraint(var): def __str__(self): if self._subvars == None: return '(constraint:'+str(self._value)+')' else: return '(constraint:'+str(self._subvars)+')' class objective(var): def __str__(self): if self._subvars == None: return '(objective:'+str(self._value)+')' else: return '(objective:'+str(self._subvars)+')' class nothing: def __repr__(self): return '' python-glpk-0.4.52/src/python/parsetab.py0000644000175000017500000000610311245751140016505 0ustar jppjpp # parsetab.py # This file is automatically generated. Do not edit. _lr_method = 'LALR' _lr_signature = '\xf2,\xacM\x91,\x8de~=\xcfh\x86e\x97b' _lr_action_items = {'RBRACK':([13,14,15,17,19,20,22,23,24,],[-15,-16,-13,-14,-9,23,-10,-12,-11,]),'PROMPT':([0,1,2,4,6,13,14,15,16,17,18,19,22,23,24,],[-2,3,-1,-3,-4,-15,-16,-13,-8,-14,-7,-9,-10,-12,-11,]),'STRING':([3,8,9,11,12,13,14,15,17,18,19,20,21,22,23,24,],[7,13,13,13,13,-15,-16,-13,-14,13,-9,13,13,-10,-12,-11,]),'RPAREN':([13,14,15,17,19,21,22,23,24,],[-15,-16,-13,-14,-9,24,-10,-12,-11,]),'FLOAT':([8,9,11,12,13,14,15,17,18,19,20,21,22,23,24,],[15,15,15,15,-15,-16,-13,-14,15,-9,15,15,-10,-12,-11,]),'LBRACK':([7,8,9,11,12,13,14,15,17,18,19,20,21,22,23,24,],[11,11,11,11,11,-15,-16,-13,-14,11,-9,11,11,-10,-12,-11,]),'LPAREN':([7,8,9,11,12,13,14,15,17,18,19,20,21,22,23,24,],[12,12,12,12,12,-15,-16,-13,-14,12,-9,12,12,-10,-12,-11,]),'INTEGER':([8,9,11,12,13,14,15,17,18,19,20,21,22,23,24,],[17,17,17,17,-15,-16,-13,-14,17,-9,17,17,-10,-12,-11,]),':':([5,7,10,23,24,],[9,-5,-6,-12,-11,]),'=':([5,7,10,23,24,],[8,-5,-6,-12,-11,]),'$end':([0,1,2,4,6,13,14,15,16,17,18,19,22,23,24,],[-2,0,-1,-3,-4,-15,-16,-13,-8,-14,-7,-9,-10,-12,-11,]),} _lr_action = { } for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _lr_action.has_key(_x): _lr_action[_x] = { } _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'decl':([1,],[2,]),'set':([3,],[4,]),'name':([3,],[5,]),'tuple':([7,8,9,11,12,18,20,21,],[10,14,14,14,14,14,14,14,]),'list':([9,11,12,],[18,20,21,]),'param':([3,],[6,]),'record':([8,9,11,12,18,20,21,],[16,19,19,19,22,22,22,]),'data':([0,],[1,]),} _lr_goto = { } for _k, _v in _lr_goto_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _lr_goto.has_key(_x): _lr_goto[_x] = { } _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S'",1,None,None,None), ('data',2,'p_data','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',194), ('data',0,'p_data','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',195), ('decl',2,'p_decl','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',203), ('decl',2,'p_decl','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',204), ('name',1,'p_name','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',208), ('name',2,'p_name','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',209), ('set',3,'p_set','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',216), ('param',3,'p_param','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',220), ('list',1,'p_list','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',224), ('list',2,'p_list','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',225), ('tuple',3,'p_tuple','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',233), ('tuple',3,'p_tuple','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',234), ('record',1,'p_record','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',238), ('record',1,'p_record','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',239), ('record',1,'p_record','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',240), ('record',1,'p_record','/home/fdabrandao/Desktop/myglpk/glpk_parser.py',241), ] python-glpk-0.4.52/src/readme.txt0000644000175000017500000000030611365056430015011 0ustar jppjppFor installing, please type 'make install'. Notice that 'python setup.py install' is not enough for building all the required files, as 'swig' is not (yet?) properly supported by python distutils. python-glpk-0.4.52/src/setup.py0000644000175000017500000000230112211111336014506 0ustar jppjppfrom distutils.core import setup, Extension # Directory containing libglpk GLPK_LIB_DIR = '/usr/lib' # Directory containing glpk.h GLPK_INC_DIR = '/usr/include' glpkpi = Extension('_glpkpi', libraries = ['glpk'], include_dirs = [ GLPK_INC_DIR ], library_dirs = [ GLPK_LIB_DIR ], sources = ['swig/glpkpi_wrap.c', 'swig/glpkpi.c'] ) extmods = [glpkpi]; setup (name = 'glpk', description = 'python-glpk package', version = '0.4.52', long_description = """ Python-glpk is a free software package providing bindings in the Python programming language for the GLPK linear and integer optimization package. Its main purpose is to make the development of software for optimization applications straightforward by building on Python's extensive standard library and on the strengths of Python as a high-level programming language.""", author = 'J.P. Pedroso and F. Brandao', author_email = 'jpp@fc.up.pt, fdabrandao@gmail.com', url = 'http://www.dcc.fc.up.pt/~jpp/code/python-glpk', license = 'GNU GPL version 3', ext_package = "glpk", ext_modules = extmods, package_dir = {"glpk": "python"}, packages = ["glpk"]) python-glpk-0.4.52/src/swig/0000755000175000017500000000000012221034160013751 5ustar jppjpppython-glpk-0.4.52/src/swig/COPYING0000644000175000017500000004330411222343023015011 0ustar jppjpp GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 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. 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 Library 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 St, 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 Library General Public License instead of this License. python-glpk-0.4.52/src/swig/glpk.h0000644000175000017500000010735312210625064015077 0ustar jppjpp/* glpk.h */ /*********************************************************************** * This code is part of GLPK (GNU Linear Programming Kit). * * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, * 2009, 2010, 2011, 2013 Andrew Makhorin, Department for Applied * Informatics, Moscow Aviation Institute, Moscow, Russia. All rights * reserved. E-mail: . * * GLPK is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GLPK 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 GLPK. If not, see . ***********************************************************************/ #ifndef GLPK_H #define GLPK_H #include #include #ifdef __cplusplus extern "C" { #endif /* library version numbers: */ #define GLP_MAJOR_VERSION 4 #define GLP_MINOR_VERSION 52 typedef struct glp_prob glp_prob; /* LP/MIP problem object */ /* optimization direction flag: */ #define GLP_MIN 1 /* minimization */ #define GLP_MAX 2 /* maximization */ /* kind of structural variable: */ #define GLP_CV 1 /* continuous variable */ #define GLP_IV 2 /* integer variable */ #define GLP_BV 3 /* binary variable */ /* type of auxiliary/structural variable: */ #define GLP_FR 1 /* free (unbounded) variable */ #define GLP_LO 2 /* variable with lower bound */ #define GLP_UP 3 /* variable with upper bound */ #define GLP_DB 4 /* double-bounded variable */ #define GLP_FX 5 /* fixed variable */ /* status of auxiliary/structural variable: */ #define GLP_BS 1 /* basic variable */ #define GLP_NL 2 /* non-basic variable on lower bound */ #define GLP_NU 3 /* non-basic variable on upper bound */ #define GLP_NF 4 /* non-basic free (unbounded) variable */ #define GLP_NS 5 /* non-basic fixed variable */ /* scaling options: */ #define GLP_SF_GM 0x01 /* perform geometric mean scaling */ #define GLP_SF_EQ 0x10 /* perform equilibration scaling */ #define GLP_SF_2N 0x20 /* round scale factors to power of two */ #define GLP_SF_SKIP 0x40 /* skip if problem is well scaled */ #define GLP_SF_AUTO 0x80 /* choose scaling options automatically */ /* solution indicator: */ #define GLP_SOL 1 /* basic solution */ #define GLP_IPT 2 /* interior-point solution */ #define GLP_MIP 3 /* mixed integer solution */ /* solution status: */ #define GLP_UNDEF 1 /* solution is undefined */ #define GLP_FEAS 2 /* solution is feasible */ #define GLP_INFEAS 3 /* solution is infeasible */ #define GLP_NOFEAS 4 /* no feasible solution exists */ #define GLP_OPT 5 /* solution is optimal */ #define GLP_UNBND 6 /* solution is unbounded */ typedef struct { /* basis factorization control parameters */ int msg_lev; /* (reserved) */ int type; /* factorization type: */ #define GLP_BF_FT 1 /* LUF + Forrest-Tomlin */ #define GLP_BF_BG 2 /* LUF + Schur compl. + Bartels-Golub */ #define GLP_BF_GR 3 /* LUF + Schur compl. + Givens rotation */ int lu_size; /* luf.sv_size */ double piv_tol; /* luf.piv_tol */ int piv_lim; /* luf.piv_lim */ int suhl; /* luf.suhl */ double eps_tol; /* luf.eps_tol */ double max_gro; /* luf.max_gro */ int nfs_max; /* fhv.hh_max */ double upd_tol; /* fhv.upd_tol */ int nrs_max; /* lpf.n_max */ int rs_size; /* lpf.v_size */ double foo_bar[38]; /* (reserved) */ } glp_bfcp; typedef struct { /* simplex method control parameters */ int msg_lev; /* message level: */ #define GLP_MSG_OFF 0 /* no output */ #define GLP_MSG_ERR 1 /* warning and error messages only */ #define GLP_MSG_ON 2 /* normal output */ #define GLP_MSG_ALL 3 /* full output */ #define GLP_MSG_DBG 4 /* debug output */ int meth; /* simplex method option: */ #define GLP_PRIMAL 1 /* use primal simplex */ #define GLP_DUALP 2 /* use dual; if it fails, use primal */ #define GLP_DUAL 3 /* use dual simplex */ int pricing; /* pricing technique: */ #define GLP_PT_STD 0x11 /* standard (Dantzig rule) */ #define GLP_PT_PSE 0x22 /* projected steepest edge */ int r_test; /* ratio test technique: */ #define GLP_RT_STD 0x11 /* standard (textbook) */ #define GLP_RT_HAR 0x22 /* two-pass Harris' ratio test */ double tol_bnd; /* spx.tol_bnd */ double tol_dj; /* spx.tol_dj */ double tol_piv; /* spx.tol_piv */ double obj_ll; /* spx.obj_ll */ double obj_ul; /* spx.obj_ul */ int it_lim; /* spx.it_lim */ int tm_lim; /* spx.tm_lim (milliseconds) */ int out_frq; /* spx.out_frq */ int out_dly; /* spx.out_dly (milliseconds) */ int presolve; /* enable/disable using LP presolver */ double foo_bar[36]; /* (reserved) */ } glp_smcp; typedef struct { /* interior-point solver control parameters */ int msg_lev; /* message level (see glp_smcp) */ int ord_alg; /* ordering algorithm: */ #define GLP_ORD_NONE 0 /* natural (original) ordering */ #define GLP_ORD_QMD 1 /* quotient minimum degree (QMD) */ #define GLP_ORD_AMD 2 /* approx. minimum degree (AMD) */ #define GLP_ORD_SYMAMD 3 /* approx. minimum degree (SYMAMD) */ double foo_bar[48]; /* (reserved) */ } glp_iptcp; typedef struct glp_tree glp_tree; /* branch-and-bound tree */ typedef struct { /* integer optimizer control parameters */ int msg_lev; /* message level (see glp_smcp) */ int br_tech; /* branching technique: */ #define GLP_BR_FFV 1 /* first fractional variable */ #define GLP_BR_LFV 2 /* last fractional variable */ #define GLP_BR_MFV 3 /* most fractional variable */ #define GLP_BR_DTH 4 /* heuristic by Driebeck and Tomlin */ #define GLP_BR_PCH 5 /* hybrid pseudocost heuristic */ int bt_tech; /* backtracking technique: */ #define GLP_BT_DFS 1 /* depth first search */ #define GLP_BT_BFS 2 /* breadth first search */ #define GLP_BT_BLB 3 /* best local bound */ #define GLP_BT_BPH 4 /* best projection heuristic */ double tol_int; /* mip.tol_int */ double tol_obj; /* mip.tol_obj */ int tm_lim; /* mip.tm_lim (milliseconds) */ int out_frq; /* mip.out_frq (milliseconds) */ int out_dly; /* mip.out_dly (milliseconds) */ void (*cb_func)(glp_tree *T, void *info); /* mip.cb_func */ void *cb_info; /* mip.cb_info */ int cb_size; /* mip.cb_size */ int pp_tech; /* preprocessing technique: */ #define GLP_PP_NONE 0 /* disable preprocessing */ #define GLP_PP_ROOT 1 /* preprocessing only on root level */ #define GLP_PP_ALL 2 /* preprocessing on all levels */ double mip_gap; /* relative MIP gap tolerance */ int mir_cuts; /* MIR cuts (GLP_ON/GLP_OFF) */ int gmi_cuts; /* Gomory's cuts (GLP_ON/GLP_OFF) */ int cov_cuts; /* cover cuts (GLP_ON/GLP_OFF) */ int clq_cuts; /* clique cuts (GLP_ON/GLP_OFF) */ int presolve; /* enable/disable using MIP presolver */ int binarize; /* try to binarize integer variables */ int fp_heur; /* feasibility pump heuristic */ #if 1 /* 25/V-2013 */ int ps_heur; /* proximity search heuristic */ #endif #if 1 /* 29/VI-2013 */ int ps_tm_lim; /* proxy time limit, milliseconds */ #endif #if 1 /* 11/VII-2013 */ int use_sol; /* use existing solution */ const char *save_sol; /* filename to save every new solution */ #endif #if 1 /* 28/V-2010 */ int alien; /* use alien solver */ #endif double foo_bar[25]; /* (reserved) */ } glp_iocp; typedef struct { /* additional row attributes */ int level; /* subproblem level at which the row was added */ int origin; /* row origin flag: */ #define GLP_RF_REG 0 /* regular constraint */ #define GLP_RF_LAZY 1 /* "lazy" constraint */ #define GLP_RF_CUT 2 /* cutting plane constraint */ int klass; /* row class descriptor: */ #define GLP_RF_GMI 1 /* Gomory's mixed integer cut */ #define GLP_RF_MIR 2 /* mixed integer rounding cut */ #define GLP_RF_COV 3 /* mixed cover cut */ #define GLP_RF_CLQ 4 /* clique cut */ double foo_bar[7]; /* (reserved) */ } glp_attr; /* enable/disable flag: */ #define GLP_ON 1 /* enable something */ #define GLP_OFF 0 /* disable something */ /* reason codes: */ #define GLP_IROWGEN 0x01 /* request for row generation */ #define GLP_IBINGO 0x02 /* better integer solution found */ #define GLP_IHEUR 0x03 /* request for heuristic solution */ #define GLP_ICUTGEN 0x04 /* request for cut generation */ #define GLP_IBRANCH 0x05 /* request for branching */ #define GLP_ISELECT 0x06 /* request for subproblem selection */ #define GLP_IPREPRO 0x07 /* request for preprocessing */ /* branch selection indicator: */ #define GLP_NO_BRNCH 0 /* select no branch */ #define GLP_DN_BRNCH 1 /* select down-branch */ #define GLP_UP_BRNCH 2 /* select up-branch */ /* return codes: */ #define GLP_EBADB 0x01 /* invalid basis */ #define GLP_ESING 0x02 /* singular matrix */ #define GLP_ECOND 0x03 /* ill-conditioned matrix */ #define GLP_EBOUND 0x04 /* invalid bounds */ #define GLP_EFAIL 0x05 /* solver failed */ #define GLP_EOBJLL 0x06 /* objective lower limit reached */ #define GLP_EOBJUL 0x07 /* objective upper limit reached */ #define GLP_EITLIM 0x08 /* iteration limit exceeded */ #define GLP_ETMLIM 0x09 /* time limit exceeded */ #define GLP_ENOPFS 0x0A /* no primal feasible solution */ #define GLP_ENODFS 0x0B /* no dual feasible solution */ #define GLP_EROOT 0x0C /* root LP optimum not provided */ #define GLP_ESTOP 0x0D /* search terminated by application */ #define GLP_EMIPGAP 0x0E /* relative mip gap tolerance reached */ #define GLP_ENOFEAS 0x0F /* no primal/dual feasible solution */ #define GLP_ENOCVG 0x10 /* no convergence */ #define GLP_EINSTAB 0x11 /* numerical instability */ #define GLP_EDATA 0x12 /* invalid data */ #define GLP_ERANGE 0x13 /* result out of range */ /* condition indicator: */ #define GLP_KKT_PE 1 /* primal equalities */ #define GLP_KKT_PB 2 /* primal bounds */ #define GLP_KKT_DE 3 /* dual equalities */ #define GLP_KKT_DB 4 /* dual bounds */ #define GLP_KKT_CS 5 /* complementary slackness */ /* MPS file format: */ #define GLP_MPS_DECK 1 /* fixed (ancient) */ #define GLP_MPS_FILE 2 /* free (modern) */ typedef struct { /* MPS format control parameters */ int blank; /* character code to replace blanks in symbolic names */ char *obj_name; /* objective row name */ double tol_mps; /* zero tolerance for MPS data */ double foo_bar[17]; /* (reserved for use in the future) */ } glp_mpscp; typedef struct { /* CPLEX LP format control parameters */ double foo_bar[20]; /* (reserved for use in the future) */ } glp_cpxcp; typedef struct glp_tran glp_tran; /* MathProg translator workspace */ glp_prob *glp_create_prob(void); /* create problem object */ void glp_set_prob_name(glp_prob *P, const char *name); /* assign (change) problem name */ void glp_set_obj_name(glp_prob *P, const char *name); /* assign (change) objective function name */ void glp_set_obj_dir(glp_prob *P, int dir); /* set (change) optimization direction flag */ int glp_add_rows(glp_prob *P, int nrs); /* add new rows to problem object */ int glp_add_cols(glp_prob *P, int ncs); /* add new columns to problem object */ void glp_set_row_name(glp_prob *P, int i, const char *name); /* assign (change) row name */ void glp_set_col_name(glp_prob *P, int j, const char *name); /* assign (change) column name */ void glp_set_row_bnds(glp_prob *P, int i, int type, double lb, double ub); /* set (change) row bounds */ void glp_set_col_bnds(glp_prob *P, int j, int type, double lb, double ub); /* set (change) column bounds */ void glp_set_obj_coef(glp_prob *P, int j, double coef); /* set (change) obj. coefficient or constant term */ void glp_set_mat_row(glp_prob *P, int i, int len, const int ind[], const double val[]); /* set (replace) row of the constraint matrix */ void glp_set_mat_col(glp_prob *P, int j, int len, const int ind[], const double val[]); /* set (replace) column of the constraint matrix */ void glp_load_matrix(glp_prob *P, int ne, const int ia[], const int ja[], const double ar[]); /* load (replace) the whole constraint matrix */ int glp_check_dup(int m, int n, int ne, const int ia[], const int ja[]); /* check for duplicate elements in sparse matrix */ void glp_sort_matrix(glp_prob *P); /* sort elements of the constraint matrix */ void glp_del_rows(glp_prob *P, int nrs, const int num[]); /* delete specified rows from problem object */ void glp_del_cols(glp_prob *P, int ncs, const int num[]); /* delete specified columns from problem object */ void glp_copy_prob(glp_prob *dest, glp_prob *prob, int names); /* copy problem object content */ void glp_erase_prob(glp_prob *P); /* erase problem object content */ void glp_delete_prob(glp_prob *P); /* delete problem object */ const char *glp_get_prob_name(glp_prob *P); /* retrieve problem name */ const char *glp_get_obj_name(glp_prob *P); /* retrieve objective function name */ int glp_get_obj_dir(glp_prob *P); /* retrieve optimization direction flag */ int glp_get_num_rows(glp_prob *P); /* retrieve number of rows */ int glp_get_num_cols(glp_prob *P); /* retrieve number of columns */ const char *glp_get_row_name(glp_prob *P, int i); /* retrieve row name */ const char *glp_get_col_name(glp_prob *P, int j); /* retrieve column name */ int glp_get_row_type(glp_prob *P, int i); /* retrieve row type */ double glp_get_row_lb(glp_prob *P, int i); /* retrieve row lower bound */ double glp_get_row_ub(glp_prob *P, int i); /* retrieve row upper bound */ int glp_get_col_type(glp_prob *P, int j); /* retrieve column type */ double glp_get_col_lb(glp_prob *P, int j); /* retrieve column lower bound */ double glp_get_col_ub(glp_prob *P, int j); /* retrieve column upper bound */ double glp_get_obj_coef(glp_prob *P, int j); /* retrieve obj. coefficient or constant term */ int glp_get_num_nz(glp_prob *P); /* retrieve number of constraint coefficients */ int glp_get_mat_row(glp_prob *P, int i, int ind[], double val[]); /* retrieve row of the constraint matrix */ int glp_get_mat_col(glp_prob *P, int j, int ind[], double val[]); /* retrieve column of the constraint matrix */ void glp_create_index(glp_prob *P); /* create the name index */ int glp_find_row(glp_prob *P, const char *name); /* find row by its name */ int glp_find_col(glp_prob *P, const char *name); /* find column by its name */ void glp_delete_index(glp_prob *P); /* delete the name index */ void glp_set_rii(glp_prob *P, int i, double rii); /* set (change) row scale factor */ void glp_set_sjj(glp_prob *P, int j, double sjj); /* set (change) column scale factor */ double glp_get_rii(glp_prob *P, int i); /* retrieve row scale factor */ double glp_get_sjj(glp_prob *P, int j); /* retrieve column scale factor */ void glp_scale_prob(glp_prob *P, int flags); /* scale problem data */ void glp_unscale_prob(glp_prob *P); /* unscale problem data */ void glp_set_row_stat(glp_prob *P, int i, int stat); /* set (change) row status */ void glp_set_col_stat(glp_prob *P, int j, int stat); /* set (change) column status */ void glp_std_basis(glp_prob *P); /* construct standard initial LP basis */ void glp_adv_basis(glp_prob *P, int flags); /* construct advanced initial LP basis */ void glp_cpx_basis(glp_prob *P); /* construct Bixby's initial LP basis */ int glp_simplex(glp_prob *P, const glp_smcp *parm); /* solve LP problem with the simplex method */ int glp_exact(glp_prob *P, const glp_smcp *parm); /* solve LP problem in exact arithmetic */ void glp_init_smcp(glp_smcp *parm); /* initialize simplex method control parameters */ int glp_get_status(glp_prob *P); /* retrieve generic status of basic solution */ int glp_get_prim_stat(glp_prob *P); /* retrieve status of primal basic solution */ int glp_get_dual_stat(glp_prob *P); /* retrieve status of dual basic solution */ double glp_get_obj_val(glp_prob *P); /* retrieve objective value (basic solution) */ int glp_get_row_stat(glp_prob *P, int i); /* retrieve row status */ double glp_get_row_prim(glp_prob *P, int i); /* retrieve row primal value (basic solution) */ double glp_get_row_dual(glp_prob *P, int i); /* retrieve row dual value (basic solution) */ int glp_get_col_stat(glp_prob *P, int j); /* retrieve column status */ double glp_get_col_prim(glp_prob *P, int j); /* retrieve column primal value (basic solution) */ double glp_get_col_dual(glp_prob *P, int j); /* retrieve column dual value (basic solution) */ int glp_get_unbnd_ray(glp_prob *P); /* determine variable causing unboundedness */ int glp_interior(glp_prob *P, const glp_iptcp *parm); /* solve LP problem with the interior-point method */ void glp_init_iptcp(glp_iptcp *parm); /* initialize interior-point solver control parameters */ int glp_ipt_status(glp_prob *P); /* retrieve status of interior-point solution */ double glp_ipt_obj_val(glp_prob *P); /* retrieve objective value (interior point) */ double glp_ipt_row_prim(glp_prob *P, int i); /* retrieve row primal value (interior point) */ double glp_ipt_row_dual(glp_prob *P, int i); /* retrieve row dual value (interior point) */ double glp_ipt_col_prim(glp_prob *P, int j); /* retrieve column primal value (interior point) */ double glp_ipt_col_dual(glp_prob *P, int j); /* retrieve column dual value (interior point) */ void glp_set_col_kind(glp_prob *P, int j, int kind); /* set (change) column kind */ int glp_get_col_kind(glp_prob *P, int j); /* retrieve column kind */ int glp_get_num_int(glp_prob *P); /* retrieve number of integer columns */ int glp_get_num_bin(glp_prob *P); /* retrieve number of binary columns */ int glp_intopt(glp_prob *P, const glp_iocp *parm); /* solve MIP problem with the branch-and-bound method */ void glp_init_iocp(glp_iocp *parm); /* initialize integer optimizer control parameters */ int glp_mip_status(glp_prob *P); /* retrieve status of MIP solution */ double glp_mip_obj_val(glp_prob *P); /* retrieve objective value (MIP solution) */ double glp_mip_row_val(glp_prob *P, int i); /* retrieve row value (MIP solution) */ double glp_mip_col_val(glp_prob *P, int j); /* retrieve column value (MIP solution) */ void glp_check_kkt(glp_prob *P, int sol, int cond, double *ae_max, int *ae_ind, double *re_max, int *re_ind); /* check feasibility/optimality conditions */ int glp_print_sol(glp_prob *P, const char *fname); /* write basic solution in printable format */ int glp_read_sol(glp_prob *P, const char *fname); /* read basic solution from text file */ int glp_write_sol(glp_prob *P, const char *fname); /* write basic solution to text file */ int glp_print_ranges(glp_prob *P, int len, const int list[], int flags, const char *fname); /* print sensitivity analysis report */ int glp_print_ipt(glp_prob *P, const char *fname); /* write interior-point solution in printable format */ int glp_read_ipt(glp_prob *P, const char *fname); /* read interior-point solution from text file */ int glp_write_ipt(glp_prob *P, const char *fname); /* write interior-point solution to text file */ int glp_print_mip(glp_prob *P, const char *fname); /* write MIP solution in printable format */ int glp_read_mip(glp_prob *P, const char *fname); /* read MIP solution from text file */ int glp_write_mip(glp_prob *P, const char *fname); /* write MIP solution to text file */ int glp_bf_exists(glp_prob *P); /* check if the basis factorization exists */ int glp_factorize(glp_prob *P); /* compute the basis factorization */ int glp_bf_updated(glp_prob *P); /* check if the basis factorization has been updated */ void glp_get_bfcp(glp_prob *P, glp_bfcp *parm); /* retrieve basis factorization control parameters */ void glp_set_bfcp(glp_prob *P, const glp_bfcp *parm); /* change basis factorization control parameters */ int glp_get_bhead(glp_prob *P, int k); /* retrieve the basis header information */ int glp_get_row_bind(glp_prob *P, int i); /* retrieve row index in the basis header */ int glp_get_col_bind(glp_prob *P, int j); /* retrieve column index in the basis header */ void glp_ftran(glp_prob *P, double x[]); /* perform forward transformation (solve system B*x = b) */ void glp_btran(glp_prob *P, double x[]); /* perform backward transformation (solve system B'*x = b) */ int glp_warm_up(glp_prob *P); /* "warm up" LP basis */ int glp_eval_tab_row(glp_prob *P, int k, int ind[], double val[]); /* compute row of the simplex tableau */ int glp_eval_tab_col(glp_prob *P, int k, int ind[], double val[]); /* compute column of the simplex tableau */ int glp_transform_row(glp_prob *P, int len, int ind[], double val[]); /* transform explicitly specified row */ int glp_transform_col(glp_prob *P, int len, int ind[], double val[]); /* transform explicitly specified column */ int glp_prim_rtest(glp_prob *P, int len, const int ind[], const double val[], int dir, double eps); /* perform primal ratio test */ int glp_dual_rtest(glp_prob *P, int len, const int ind[], const double val[], int dir, double eps); /* perform dual ratio test */ void glp_analyze_bound(glp_prob *P, int k, double *value1, int *var1, double *value2, int *var2); /* analyze active bound of non-basic variable */ void glp_analyze_coef(glp_prob *P, int k, double *coef1, int *var1, double *value1, double *coef2, int *var2, double *value2); /* analyze objective coefficient at basic variable */ int glp_ios_reason(glp_tree *T); /* determine reason for calling the callback routine */ glp_prob *glp_ios_get_prob(glp_tree *T); /* access the problem object */ void glp_ios_tree_size(glp_tree *T, int *a_cnt, int *n_cnt, int *t_cnt); /* determine size of the branch-and-bound tree */ int glp_ios_curr_node(glp_tree *T); /* determine current active subproblem */ int glp_ios_next_node(glp_tree *T, int p); /* determine next active subproblem */ int glp_ios_prev_node(glp_tree *T, int p); /* determine previous active subproblem */ int glp_ios_up_node(glp_tree *T, int p); /* determine parent subproblem */ int glp_ios_node_level(glp_tree *T, int p); /* determine subproblem level */ double glp_ios_node_bound(glp_tree *T, int p); /* determine subproblem local bound */ int glp_ios_best_node(glp_tree *T); /* find active subproblem with best local bound */ double glp_ios_mip_gap(glp_tree *T); /* compute relative MIP gap */ void *glp_ios_node_data(glp_tree *T, int p); /* access subproblem application-specific data */ void glp_ios_row_attr(glp_tree *T, int i, glp_attr *attr); /* retrieve additional row attributes */ int glp_ios_pool_size(glp_tree *T); /* determine current size of the cut pool */ int glp_ios_add_row(glp_tree *T, const char *name, int klass, int flags, int len, const int ind[], const double val[], int type, double rhs); /* add row (constraint) to the cut pool */ void glp_ios_del_row(glp_tree *T, int i); /* remove row (constraint) from the cut pool */ void glp_ios_clear_pool(glp_tree *T); /* remove all rows (constraints) from the cut pool */ int glp_ios_can_branch(glp_tree *T, int j); /* check if can branch upon specified variable */ void glp_ios_branch_upon(glp_tree *T, int j, int sel); /* choose variable to branch upon */ void glp_ios_select_node(glp_tree *T, int p); /* select subproblem to continue the search */ int glp_ios_heur_sol(glp_tree *T, const double x[]); /* provide solution found by heuristic */ void glp_ios_terminate(glp_tree *T); /* terminate the solution process */ void glp_init_mpscp(glp_mpscp *parm); /* initialize MPS format control parameters */ int glp_read_mps(glp_prob *P, int fmt, const glp_mpscp *parm, const char *fname); /* read problem data in MPS format */ int glp_write_mps(glp_prob *P, int fmt, const glp_mpscp *parm, const char *fname); /* write problem data in MPS format */ void glp_init_cpxcp(glp_cpxcp *parm); /* initialize CPLEX LP format control parameters */ int glp_read_lp(glp_prob *P, const glp_cpxcp *parm, const char *fname); /* read problem data in CPLEX LP format */ int glp_write_lp(glp_prob *P, const glp_cpxcp *parm, const char *fname); /* write problem data in CPLEX LP format */ int glp_read_prob(glp_prob *P, int flags, const char *fname); /* read problem data in GLPK format */ int glp_write_prob(glp_prob *P, int flags, const char *fname); /* write problem data in GLPK format */ glp_tran *glp_mpl_alloc_wksp(void); /* allocate the MathProg translator workspace */ int glp_mpl_read_model(glp_tran *tran, const char *fname, int skip); /* read and translate model section */ int glp_mpl_read_data(glp_tran *tran, const char *fname); /* read and translate data section */ int glp_mpl_generate(glp_tran *tran, const char *fname); /* generate the model */ void glp_mpl_build_prob(glp_tran *tran, glp_prob *prob); /* build LP/MIP problem instance from the model */ int glp_mpl_postsolve(glp_tran *tran, glp_prob *prob, int sol); /* postsolve the model */ void glp_mpl_free_wksp(glp_tran *tran); /* free the MathProg translator workspace */ int glp_main(int argc, const char *argv[]); /* stand-alone LP/MIP solver */ int glp_read_cnfsat(glp_prob *P, const char *fname); /* read CNF-SAT problem data in DIMACS format */ int glp_check_cnfsat(glp_prob *P); /* check for CNF-SAT problem instance */ int glp_write_cnfsat(glp_prob *P, const char *fname); /* write CNF-SAT problem data in DIMACS format */ int glp_minisat1(glp_prob *P); /* solve CNF-SAT problem with MiniSat solver */ int glp_intfeas1(glp_prob *P, int use_bound, int obj_bound); /* solve integer feasibility problem */ int glp_init_env(void); /* initialize GLPK environment */ const char *glp_version(void); /* determine library version */ int glp_free_env(void); /* free GLPK environment */ void glp_puts(const char *s); /* write string on terminal */ /* commented by jpp for avoiding problems with swig */ /* void glp_printf(const char *fmt, ...); */ /* write formatted output on terminal */ /* commented by jpp for avoiding problems with swig */ /* void glp_vprintf(const char *fmt, va_list arg); */ /* write formatted output on terminal */ int glp_term_out(int flag); /* enable/disable terminal output */ void glp_term_hook(int (*func)(void *info, const char *s), void *info); /* install hook to intercept terminal output */ int glp_open_tee(const char *name); /* start copying terminal output to text file */ int glp_close_tee(void); /* stop copying terminal output to text file */ #ifndef GLP_ERRFUNC_DEFINED #define GLP_ERRFUNC_DEFINED typedef void (*glp_errfunc)(const char *fmt, ...); #endif #define glp_error glp_error_(__FILE__, __LINE__) glp_errfunc glp_error_(const char *file, int line); /* display fatal error message and terminate execution */ #define glp_assert(expr) \ ((void)((expr) || (glp_assert_(#expr, __FILE__, __LINE__), 1))) void glp_assert_(const char *expr, const char *file, int line); /* check for logical condition */ void glp_error_hook(void (*func)(void *info), void *info); /* install hook to intercept abnormal termination */ #define glp_malloc(size) glp_alloc(1, size) /* allocate memory block (obsolete) */ #define glp_calloc(n, size) glp_alloc(n, size) /* allocate memory block (obsolete) */ void *glp_alloc(int n, int size); /* allocate memory block */ void *glp_realloc(void *ptr, int n, int size); /* reallocate memory block */ void glp_free(void *ptr); /* free (deallocate) memory block */ void glp_mem_limit(int limit); /* set memory usage limit */ void glp_mem_usage(int *count, int *cpeak, size_t *total, size_t *tpeak); /* get memory usage information */ typedef struct glp_graph glp_graph; typedef struct glp_vertex glp_vertex; typedef struct glp_arc glp_arc; struct glp_graph { /* graph descriptor */ void *pool; /* DMP *pool; */ /* memory pool to store graph components */ char *name; /* graph name (1 to 255 chars); NULL means no name is assigned to the graph */ int nv_max; /* length of the vertex list (enlarged automatically) */ int nv; /* number of vertices in the graph, 0 <= nv <= nv_max */ int na; /* number of arcs in the graph, na >= 0 */ glp_vertex **v; /* glp_vertex *v[1+nv_max]; */ /* v[i], 1 <= i <= nv, is a pointer to i-th vertex */ void *index; /* AVL *index; */ /* vertex index to find vertices by their names; NULL means the index does not exist */ int v_size; /* size of data associated with each vertex (0 to 256 bytes) */ int a_size; /* size of data associated with each arc (0 to 256 bytes) */ }; struct glp_vertex { /* vertex descriptor */ int i; /* vertex ordinal number, 1 <= i <= nv */ char *name; /* vertex name (1 to 255 chars); NULL means no name is assigned to the vertex */ void *entry; /* AVLNODE *entry; */ /* pointer to corresponding entry in the vertex index; NULL means that either the index does not exist or the vertex has no name assigned */ void *data; /* pointer to data associated with the vertex */ void *temp; /* working pointer */ glp_arc *in; /* pointer to the (unordered) list of incoming arcs */ glp_arc *out; /* pointer to the (unordered) list of outgoing arcs */ }; struct glp_arc { /* arc descriptor */ glp_vertex *tail; /* pointer to the tail endpoint */ glp_vertex *head; /* pointer to the head endpoint */ void *data; /* pointer to data associated with the arc */ void *temp; /* working pointer */ glp_arc *t_prev; /* pointer to previous arc having the same tail endpoint */ glp_arc *t_next; /* pointer to next arc having the same tail endpoint */ glp_arc *h_prev; /* pointer to previous arc having the same head endpoint */ glp_arc *h_next; /* pointer to next arc having the same head endpoint */ }; glp_graph *glp_create_graph(int v_size, int a_size); /* create graph */ void glp_set_graph_name(glp_graph *G, const char *name); /* assign (change) graph name */ int glp_add_vertices(glp_graph *G, int nadd); /* add new vertices to graph */ void glp_set_vertex_name(glp_graph *G, int i, const char *name); /* assign (change) vertex name */ glp_arc *glp_add_arc(glp_graph *G, int i, int j); /* add new arc to graph */ void glp_del_vertices(glp_graph *G, int ndel, const int num[]); /* delete vertices from graph */ void glp_del_arc(glp_graph *G, glp_arc *a); /* delete arc from graph */ void glp_erase_graph(glp_graph *G, int v_size, int a_size); /* erase graph content */ void glp_delete_graph(glp_graph *G); /* delete graph */ void glp_create_v_index(glp_graph *G); /* create vertex name index */ int glp_find_vertex(glp_graph *G, const char *name); /* find vertex by its name */ void glp_delete_v_index(glp_graph *G); /* delete vertex name index */ int glp_read_graph(glp_graph *G, const char *fname); /* read graph from plain text file */ int glp_write_graph(glp_graph *G, const char *fname); /* write graph to plain text file */ void glp_mincost_lp(glp_prob *P, glp_graph *G, int names, int v_rhs, int a_low, int a_cap, int a_cost); /* convert minimum cost flow problem to LP */ int glp_mincost_okalg(glp_graph *G, int v_rhs, int a_low, int a_cap, int a_cost, double *sol, int a_x, int v_pi); /* find minimum-cost flow with out-of-kilter algorithm */ int glp_mincost_relax4(glp_graph *G, int v_rhs, int a_low, int a_cap, int a_cost, int crash, double *sol, int a_x, int a_rc); /* find minimum-cost flow with Bertsekas-Tseng relaxation method */ void glp_maxflow_lp(glp_prob *P, glp_graph *G, int names, int s, int t, int a_cap); /* convert maximum flow problem to LP */ int glp_maxflow_ffalg(glp_graph *G, int s, int t, int a_cap, double *sol, int a_x, int v_cut); /* find maximal flow with Ford-Fulkerson algorithm */ int glp_check_asnprob(glp_graph *G, int v_set); /* check correctness of assignment problem data */ /* assignment problem formulation: */ #define GLP_ASN_MIN 1 /* perfect matching (minimization) */ #define GLP_ASN_MAX 2 /* perfect matching (maximization) */ #define GLP_ASN_MMP 3 /* maximum matching */ int glp_asnprob_lp(glp_prob *P, int form, glp_graph *G, int names, int v_set, int a_cost); /* convert assignment problem to LP */ int glp_asnprob_okalg(int form, glp_graph *G, int v_set, int a_cost, double *sol, int a_x); /* solve assignment problem with out-of-kilter algorithm */ int glp_asnprob_hall(glp_graph *G, int v_set, int a_x); /* find bipartite matching of maximum cardinality */ double glp_cpp(glp_graph *G, int v_t, int v_es, int v_ls); /* solve critical path problem */ int glp_read_mincost(glp_graph *G, int v_rhs, int a_low, int a_cap, int a_cost, const char *fname); /* read min-cost flow problem data in DIMACS format */ int glp_write_mincost(glp_graph *G, int v_rhs, int a_low, int a_cap, int a_cost, const char *fname); /* write min-cost flow problem data in DIMACS format */ int glp_read_maxflow(glp_graph *G, int *s, int *t, int a_cap, const char *fname); /* read maximum flow problem data in DIMACS format */ int glp_write_maxflow(glp_graph *G, int s, int t, int a_cap, const char *fname); /* write maximum flow problem data in DIMACS format */ int glp_read_asnprob(glp_graph *G, int v_set, int a_cost, const char *fname); /* read assignment problem data in DIMACS format */ int glp_write_asnprob(glp_graph *G, int v_set, int a_cost, const char *fname); /* write assignment problem data in DIMACS format */ int glp_read_ccdata(glp_graph *G, int v_wgt, const char *fname); /* read graph in DIMACS clique/coloring format */ int glp_write_ccdata(glp_graph *G, int v_wgt, const char *fname); /* write graph in DIMACS clique/coloring format */ int glp_netgen(glp_graph *G, int v_rhs, int a_cap, int a_cost, const int parm[1+15]); /* Klingman's network problem generator */ void glp_netgen_prob(int nprob, int parm[1+15]); /* Klingman's standard network problem instance */ int glp_gridgen(glp_graph *G, int v_rhs, int a_cap, int a_cost, const int parm[1+14]); /* grid-like network problem generator */ int glp_rmfgen(glp_graph *G, int *s, int *t, int a_cap, const int parm[1+5]); /* Goldfarb's maximum flow problem generator */ int glp_weak_comp(glp_graph *G, int v_num); /* find all weakly connected components of graph */ int glp_strong_comp(glp_graph *G, int v_num); /* find all strongly connected components of graph */ int glp_top_sort(glp_graph *G, int v_num); /* topological sorting of acyclic digraph */ int glp_wclique_exact(glp_graph *G, int v_wgt, double *sol, int v_set); /* find maximum weight clique with exact algorithm */ #ifdef __cplusplus } #endif #endif /* eof */ python-glpk-0.4.52/src/swig/glpkpi.c0000644000175000017500000000232111372025056015413 0ustar jppjpp/* glpkpi.c (C functions for setting/canceling printing in the stdout) */ /*---------------------------------------------------------------------- -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. ----------------------------------------------------------------------*/ #include #include "./glpk.h" /* written by jpp */ python-glpk-0.4.52/src/swig/glpkpi.h0000644000175000017500000000244111372025056015423 0ustar jppjpp/* glpkpi.h (definition of all functions callable by Python) */ /*---------------------------------------------------------------------- -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. ----------------------------------------------------------------------*/ #ifndef glpkpi_h #define glpkpi_h #include "./glpk.h" /* functions written by jpp for the python interface: */ /* library functions (jpp) */ #endif python-glpk-0.4.52/src/swig/glpkpi.i0000644000175000017500000000340111372025056015421 0ustar jppjpp/* *** This is C code *** Filename : glpk.i (primitives for swig producing the python-glpk API) */ /*---------------------------------------------------------------------- -- This code is part of the Python-GLPK interface. -- -- Copyright (C) 2005, Joao Pedro Pedroso and Filipe Brandao -- Faculdade de Ciencias, Universidade do Porto -- Porto, Portugal. All rights reserved. E-mail: . -- -- Python-GLPK 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, or (at your option) any -- later version. -- -- Python-GLPK 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 GLPK; see the file COPYING. If not, write to the Free -- Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -- 02110-1301, USA. ----------------------------------------------------------------------*/ %module glpkpi %{ #include "./glpk.h" %} /* Some global variable declarations */ /* Some read-only variables */ %immutable; /* Some more variables */ %mutable; /* Functions for creating C arrays in Python; see usage in 'example_refman.py' */ %include "carrays.i" %array_class(int, intArray); /* a = intArray(SIZE) -> "a" can be passed to C functions as int *, int [], ... */ %array_class(double, doubleArray); /* a = doubleArray(SIZE) -> "a" can be passed to C functions as double *, double [], ... */ %include glpkpi.h %include "./glpk.h" /* change if glpk.h is installed somewhere else */ python-glpk-0.4.52/src/swig/Makefile0000644000175000017500000000127711365006730015432 0ustar jppjppPYVERS := $(shell pyversions -d) DIR := $(shell basename `pwd`) all: _glpkpi.so glpkpi.py glpkpi.py: glpkpi.i glpkpi.c glpkpi.h Makefile swig -python glpkpi.i sed -i 's/:in /:_in /g' glpkpi.py _glpkpi.so: glpkpi.py glpkpi.o glpkpi_wrap.o gcc -Wall -shared glpkpi.o glpkpi_wrap.o -lm -lglpk -o _glpkpi.so glpkpi.o: glpkpi.c gcc -Wall -c -fPIC glpkpi.c -DHAVE_CONFIG_H -I/usr/include/$(PYVERS) -I/usr/lib/$(PYVERS)/config glpkpi_wrap.o: glpkpi_wrap.c gcc -Wall -c -fPIC glpkpi_wrap.c -DHAVE_CONFIG_H -I/usr/include/$(PYVERS) -I/usr/lib/$(PYVERS)/config glpkpi_wrap.c: glpkpi.i glpkpi.c glpkpi.h Makefile swig -python glpkpi.i clean: rm -f *.o *~ *.pyc *.pyo _*.so glpkpi_wrap.c glpkpi.py python-glpk-0.4.52/src/swig/readme.txt0000644000175000017500000000033311253725470015765 0ustar jppjppSimple interface for using GLPK in Python. This requires GLPK to be installed, and uses the SWIG package for producing the API. Notice that the glpk's C keyword 'in' is renamed '_in' in Python, for avoiding conflict.