• Main Page
  • Namespaces
  • Classes
  • Files
  • File List

/home/mark/model/software/ScrumPy/ScrumPy/LP/glpk.py

00001 
00002 
00003 
00004 """
00005 glpk.py - (c) Mark Poolman 2008 onwards.
00006 A high(ish) level interface between python and the glpk library of
00007 Andrew Makhorin (mao AT gnu DOT org) which can be found at www.gnu.org/software/glpk
00008 
00009 
00010 This module is still experimental and is
00011 
00012   *************************   NOT TO BE REDISTRIBUTED  ***************************
00013 
00014 without the prior consent of the author.
00015 
00016 """
00017 
00018 
00019 
00020 
00021 import os, sys, exceptions, random
00022 import glpk_ll # _ll -> low-level interface created with Swig
00023 
00024 
00025 ########################## freindly interface to low level c arrays
00026 
00027 from Array import BaseArray
00028 class IntArray(BaseArray):
00029     _del = glpk_ll.delete_intArray
00030     _get = glpk_ll.intArray_getitem
00031     _set = glpk_ll.intArray_setitem
00032     _new = glpk_ll.new_intArray
00033     _cast = int
00034 
00035     #_offset=1 by default
00036 
00037     def __init__(self,SizeOrList):
00038         if type(SizeOrList) ==int:   # we're initing an undetlying malloc'd C array
00039             SizeOrList *= [0]        # ensure all elements are iniitialised
00040         BaseArray.__init__(self,SizeOrList)
00041 
00042 class DoubleArray(BaseArray):
00043     _del = glpk_ll.delete_doubleArray
00044     _get = glpk_ll.doubleArray_getitem
00045     _set = glpk_ll.doubleArray_setitem
00046     _new = glpk_ll.new_doubleArray
00047     _cast = float
00048 
00049     def __init__(self,SizeOrList):
00050         if type(SizeOrList) ==int:   # we're initing an undetlying malloc'd C array
00051             SizeOrList *= [0.0]        # ensure all elements are iniitialised
00052         BaseArray.__init__(self,SizeOrList)
00053     #_offset=1 by default
00054 
00055 
00056 
00057 
00058 ########################## mappings between arrays/lists etc
00059 
00060 def AddOne(l):
00061     return map(lambda x: x+1, l)
00062 
00063 def SubOne(l):
00064     return map(lambda x: x-1, l)
00065 
00066 def Vec2Lists(vec):
00067     """ pre: vec indexable type with elements comparable to 0
00068        post: list of indices and vals of non-zereos in vec """
00069 
00070     d = {}
00071     for i in range(len(vec)):
00072         val = vec[i]
00073         if val != 0:
00074             d[i] = val
00075     return d.keys(), d.values()
00076 
00077 def Lists2Vec(idxs,vals,size):
00078     """ pre: len(vals) == len(idxs), max(idx)<size
00079        post: rv[indxs[i]] = vals[i], i[0..size-1] else 0.0 """
00080 
00081 
00082     rv = [0.0] * size
00083     for i in range(len(idxs)):
00084         idx = idxs[i]
00085         if idx >=0:
00086             rv[idx] = vals[i]
00087     return rv
00088 
00089 
00090 
00091 #########################
00092 
00093 
00094 VerySmall = 1e-12
00095 def IsZero(number, tol=VerySmall):
00096     return abs(number) < tol
00097 
00098 
00099 
00100 
00101 ########################## mappings between various constants
00102 
00103 Sym2Num = {}             # map between symbolic constants and their values
00104 Num2Sym = {}
00105 Str2Num = {}
00106 Num2Str = {             # map constant status values to human strings
00107     glpk_ll.LPX_MIN : "Min",
00108     glpk_ll.LPX_MAX : "Max"
00109 }
00110 
00111 Status2Str = {           # map symbolic status constants to human strings
00112     "LPX_OPT"    : "Optimal",
00113     "LPX_FEAS"   : "Feasible",
00114     "LPX_INFEAS" : "Infeasible",
00115     "LPX_NOFEAS" : "No feasible",
00116     "LPX_UNDEF"  : "Undefined",
00117     'LPX_UNBND'  : "Unbounded!"
00118 }
00119 
00120 
00121 for d in dir(glpk_ll):
00122     if d.startswith("LPX_"):
00123         num =  getattr(glpk_ll,d)
00124         if type(num)==int:
00125             Sym2Num[d] = num
00126             Num2Sym[num] = d
00127 
00128 for k in Status2Str.keys():
00129     Num2Str[Sym2Num[k]] = Status2Str[k] # generic status
00130 
00131     kp = k.replace("_","_P_")        # primal status if present
00132     if Sym2Num.has_key(kp):
00133         Status2Str[kp] = Num2Str[Sym2Num[kp]] = "Primal "+ Status2Str[k]
00134 
00135     kd = k.replace("_","_D_")         # dual status if present
00136     if Sym2Num.has_key(kd):
00137         Status2Str[kd] = Num2Str[Sym2Num[kd]] = "Dual " +Status2Str[k]
00138 
00139 for k in Num2Str.keys():
00140     Str2Num[Num2Str[k]] = k
00141 
00142 
00143 #
00144 # class that executes a glpk_ll function with fixed first arg
00145 # and arbitrary subsequent args
00146 #
00147 class exec_ll:
00148         def __init__(self,name, arg0):
00149             self.name = name
00150             self.arg0 = arg0
00151 
00152         def __call__(self, *args):
00153             return getattr(glpk_ll, self.name)(self.arg0,*args)
00154 
00155 
00156 
00157 
00158 #
00159 # IO utils
00160 #
00161 #
00162 def F2Str(fun):
00163     """ pre: fun(filename) writes to a file
00164        post: returns as a string what fun was going to write """
00165 
00166     dest = str(random.randint(0,100000))
00167     fun(dest)
00168     rv = open(dest).read()
00169     os.remove(dest)
00170     return rv
00171 
00172 
00173 #
00174 ##
00175 ### ##################### main user interface to glpk
00176 ##
00177 #
00178 class lp:
00179 
00180 
00181     _Readers = {      # map humanoid format descriptions to glpk function names
00182         "FixedMPS"    : glpk_ll._glp_lpx_read_mps,
00183         "FreeMPS"     : glpk_ll._glp_lpx_read_freemps,
00184         "CPLEX"       : glpk_ll._glp_lpx_read_cpxlp,
00185         "GnuMathProg" : glpk_ll._glp_lpx_read_model
00186     }
00187 
00188     _MethodsMap = {   # map methods to names of functions that have trivial equivalence
00189                       # methods can't be bound until we have an lpx instance - see __init__()
00190         "SetName":"_glp_lpx_set_prob_name",
00191         "GetName":"_glp_lpx_get_prob_name",
00192 
00193         "SetObjDir":"_glp_lpx_set_obj_dir",
00194         "GetObjDir":"_glp_lpx_get_obj_dir",
00195 
00196         "GetObjVal" :"_glp_lpx_get_obj_val",
00197 
00198         "SetObjName":"_glp_lpx_set_obj_name",
00199         "GetObjName":"_glp_lpx_get_obj_name",
00200 
00201         "GetNumRows":"_glp_lpx_get_num_rows",
00202         "GetNumCols":"_glp_lpx_get_num_cols"
00203     }
00204 
00205 
00206     _StatusGettersMap = {  # as above, these query problem status
00207         "Generic": "_glp_lpx_get_status",
00208         "Primal" : "_glp_lpx_get_prim_stat",
00209         "Dual"   : "_glp_lpx_get_dual_stat"
00210     }
00211     _StatusGetters = {} # will be bound here on __init__()
00212 
00213 
00214     _WritersMap = {  # map nice warm fuzzy pythonic string format descriptions to glpk functions
00215         "Human" :"_glp_lpx_print_prob",
00216         "FixedMPS" : "_glp_lpx_write_mps",
00217         "FreeMPS"  : "_glp_lpx_write_freemps",
00218         "CPLEX"    : "_glp_lpx_write_cpxlp",
00219         "Solution" : "_glp_lpx_print_sol"
00220     }
00221     _Writers = {} # as previous maps
00222 
00223 
00224 
00225 
00226     def __init__(self, name="Unamed"):
00227         self.lpx = glpk_ll._glp_lpx_create_prob()
00228         self.__setup()
00229 
00230         self.SetName(name)
00231 
00232 
00233     def __setup(self):
00234         self.rnames={}
00235         self.cnames={}
00236         self.cidxs = {}
00237         self.ridxs = {}
00238 
00239         self.__map_ll()
00240 
00241 
00242         for method in self._MethodsMap:
00243             setattr(self, method, exec_ll(self._MethodsMap[method],self.lpx))
00244 
00245         for writer in self._WritersMap:
00246             self._Writers[writer] = exec_ll(self._WritersMap[writer],self.lpx)
00247 
00248         for getter in self._StatusGettersMap:
00249             self._StatusGetters[getter] =  exec_ll(self._StatusGettersMap[getter],self.lpx)
00250 
00251 
00252     def __repr__(self):
00253         return self.GetName()+" (instance of glpk.lp)"
00254 
00255     def __str__(self):
00256         return self.Write()
00257 
00258 
00259     def __map_ll(self):
00260 
00261         for i in dir(glpk_ll):
00262             if i.startswith("glp_lpx") and not i.startswith("glp_lpx_read"):
00263                 setattr(self, "_"+i, exec_ll(i,self.lpx))
00264             elif i.startswith("_glp_lpx"):
00265                 setattr(self, i, exec_ll(i,self.lpx))
00266 
00267 
00268     #def __getattr__(self, attr):
00269     #    return
00270         # "just-in-time" alternative to __map_ll
00271         # the approach, and variants thereof, will almost certainly
00272         # cause more problems than it solves.
00273         # left here for your entertainment.
00274         #if attr.startswith("_glp_lpx"):
00275         #    a = exec_ll(attr[1:], self.lpx)
00276         #    setattr(self, attr,a)
00277         #    return a
00278 
00279 
00280 
00281     def __diccheck(self, dic, k):
00282         if not k in dic:
00283             sys.stderr.write(k+" is invalid - options are: "+", ".join(dic.keys()))
00284             raise exceptions.KeyError
00285         return dic[k]
00286 
00287 
00288     def __rowcheck(self, r):
00289         if r<0 or r>=self.GetNumRows():
00290             raise exceptions.IndexError, str(r)
00291         return r+1
00292 
00293     def __colcheck(self, c):
00294         if c<0 or c>=self.GetNumCols():
00295             raise exceptions.IndexError, str(c)
00296         return c+1
00297 
00298 
00299     def __getrow(self,r):
00300         if type(r)==str:
00301             if self.ridxs.has_key(r):
00302                 r = self.ridxs[r]
00303             else:
00304                 raise exceptions.KeyError, str(r)
00305 
00306         return self.__rowcheck(r)
00307 
00308 
00309     def __getcol(self,c):
00310         if type(c)==str:
00311             if self.cidxs.has_key(c):
00312                 c = self.cidxs[c]
00313             else:
00314                 raise exceptions.KeyError, str(c)
00315 
00316         return self.__colcheck(c)
00317 
00318 
00319 
00320     def __getbnds(self, lo, hi):
00321 
00322         if   lo == None and hi == None:
00323             flag, lo, hi = glpk_ll.LPX_FR, 0.0, 0.0
00324         elif lo != None and hi == None:
00325             flag, lo, hi = glpk_ll.LPX_LO, lo, 0.0
00326         elif lo == None and hi != None:
00327             flag, lo, hi = glpk_ll.LPX_UP, 0.0, hi
00328         elif lo != None and hi != None:
00329             if lo < hi:
00330                 flag =  glpk_ll.LPX_DB
00331             elif lo==hi:
00332                 flag = glpk_ll.LPX_FX
00333             else:
00334                 raise exceptions.ValueError, "lo > hi !"
00335 
00336         return flag, lo, hi
00337 
00338 
00339 
00340     def __RebuildNameDics(self):
00341 
00342         self.rnames = {}
00343         self.cnames = {}
00344         self.ridxs = {}
00345         self.cidxs = {}
00346         nr,nc = self.GetDims()
00347 
00348         for r in range(nr):
00349             rname = self._glp_lpx_get_row_name(r+1)
00350             self.rnames[r] =  rname
00351             self.ridxs[rname] = r
00352 
00353         for c in range(nc):
00354             cname = self._glp_lpx_get_col_name(c+1)
00355             self.cnames[c] =  cname
00356             self.cidxs[cname] = c
00357 
00358 
00359     def __del__(self):
00360             self._glp_lpx_delete_prob()
00361 
00362     #
00363     ## # Public methods start here
00364     #
00365 
00366 
00367     #
00368     ## define the problem
00369     #
00370 
00371     def SetObjDirec(self, direc="Min"):
00372         """ pre: direc = "Min" | "Max" """
00373 
00374         if not (direc=="Max" or direc=="Min"):
00375             raise exceptions.ValueError, direc
00376 
00377         #if direc == "Min":
00378         #    direc = glpk_ll.LPX_MIN
00379         #elif direc == "Max":
00380         #    direc = glpk_ll.LPX_MAX
00381         #else:
00382         #    raise exceptions.ValueError, direc
00383         self._glp_lpx_set_obj_dir(Str2Num[direc])
00384 
00385 
00386     def AddRows(self,rows):
00387 
00388         tr = type(rows)
00389         if tr == int:
00390             if rows <1:
00391                 raise exceptions.ValueError, "Can't add less then one row !"
00392             self._glp_lpx_add_rows(rows)
00393 
00394         elif tr == list:
00395             oldnr = self.GetNumRows()
00396             newnr = len(rows)
00397             if True in map(self.HasRow,rows):
00398                 raise exceptions.ValueError, "Can't add duplicate row index !"
00399 
00400             self._glp_lpx_add_rows(newnr)
00401             for ridx in range(newnr):
00402                 self.SetRowName(ridx+oldnr, rows[ridx])
00403 
00404         else:
00405             raise execeptions.TypeError, "rows must be int or list"
00406 
00407 
00408 
00409     def AddCols(self,cols):
00410 
00411         tc = type(cols)
00412         if tc == int:
00413             if cols <1:
00414                 raise exceptions.ValueError, "Can't add less then one col !"
00415             self._glp_lpx_add_cols(cols)
00416 
00417         elif tc == list:
00418             oldnc = self.GetNumCols()
00419             newnc = len(cols)
00420             if True in map(self.HasCol,cols):
00421                 raise exceptions.ValueError, "Can't add duplicate col index !"
00422 
00423             self._glp_lpx_add_cols(newnc)
00424             for cidx in range(newnc):
00425                 self.SetColName(cidx+oldnc, cols[cidx])
00426 
00427         else:
00428             raise execeptions.TypeError, "cols must be int or list"
00429 
00430 
00431     def GetRowIdxs(self,rows):
00432         return map(self.__getrow, rows)
00433 
00434     def GetColIdxs(self,cols):
00435         return map(self.__getcol, cols)
00436 
00437 
00438     def DelRows(self,rows):
00439         n = len(rows)
00440         rows = self.GetRowIdxs(rows)
00441         idxs = IntArray(rows)
00442         self._glp_lpx_del_rows(n,idxs._array)
00443         self.__RebuildNameDics()
00444 
00445 
00446     def DelCols(self,cols):
00447         n = len(cols)
00448         cols = self.GetColIdxs(cols)
00449         idxs = IntArray(cols)
00450         self._glp_lpx_del_cols(n,idxs._array)
00451         self.__RebuildNameDics()
00452 
00453 
00454     def SetRowName(self, r, name):
00455 
00456         if self.ridxs.has_key(name):
00457             raise exceptions.KeyError, "duplicate row name, "+name
00458 
00459         gr = self.__getrow(r)
00460         self._glp_lpx_set_row_name(gr,name)
00461         self.ridxs[name] = r
00462         self.rnames[r] = name
00463 
00464 
00465     def SetColName(self, c, name):
00466 
00467         if self.cidxs.has_key(name):
00468             raise exceptions.KeyError, "duplicate col name,"+name
00469 
00470         gc = self.__getcol(c)
00471         self._glp_lpx_set_col_name(gc,name)
00472         self.cidxs[name] = c
00473         self.cnames[c] = name
00474 
00475 
00476 
00477     def SetRowBounds(self, r, lo=None, hi=None):
00478 
00479         r = self.__getrow(r)
00480         flag, lo, hi = self.__getbnds(lo,hi)
00481         self._glp_lpx_set_row_bnds(r, flag, lo, hi)
00482 
00483 
00484     def SetColBounds(self, c, lo=None, hi=None):
00485 
00486         c = self.__getcol(c)
00487         flag, lo, hi = self.__getbnds(lo,hi)
00488         self._glp_lpx_set_col_bnds(c,flag,lo,hi)
00489 
00490 
00491 
00492     def SetRowVals(self, row, vals):
00493 
00494         row = self.__getrow(row)
00495         lenv = len(vals)
00496         if len(vals) != self.GetNumCols():
00497             raise exceptions.IndexError, "incorrect row length"
00498         zs = []
00499         nzs = []
00500         for i in range(lenv):
00501             if vals[i] == 0:
00502                 zs.append(i)
00503             else:
00504                 nzs.append(i)
00505         zs.reverse()
00506         if len(zs) !=0:
00507             vals = vals[:] # copy, because we are going to change the contents
00508         for i in zs:
00509             del vals[i]
00510         nzs = IntArray(AddOne(nzs))
00511         vals = DoubleArray(vals)
00512         self._glp_lpx_set_mat_row(row, len(vals), nzs._array, vals._array)
00513 
00514 
00515 
00516 
00517     def LoadMtxFromILists(self, RowIdxs, ColIdxs, ElVals):
00518 
00519         nels = len(ElVals)
00520         nr,nc = self.GetDims()
00521 
00522         if not len(RowIdxs) == len(ColIdxs) == nels:
00523             raise exceptions.IndexError, "Inconsistant indices and/or values"
00524 
00525         try:
00526             RowIdxs = map(self.__getrow, RowIdxs)
00527         except:
00528             raise exceptions.IndexError, "Bad row index"
00529 
00530         try:
00531             ColIdxs = map(self.__getcol, ColIdxs)
00532         except:
00533             raise exceptions.IndexError, "Bad col index"
00534 
00535         tupdic = {}
00536         for i in range(len(RowIdxs)):
00537             tup = str((RowIdxs[i],ColIdxs[i]))
00538             if tupdic.has_key(tup):
00539                 raise exceptions.IndexError, "Duplicate indices not allowed"
00540                 # don't ask me why not, I didn't write gplk.c !
00541             else:
00542                 tupdic[tup]=1
00543 
00544 
00545         zs = []                     # remove any zero element values, which for reasons unknown
00546         for i in range(nels):       # will cause precipitate termination in glpk
00547             if ElVals[i] ==0:
00548                 zs.append(i)
00549         if len(zs) != 0:
00550             RowIdxs, ColIdxs, ElVals = RowIdxs[:], ColIdxs[:], ElVals[:] # copy, keep orignals untouched
00551             zs.reverse()
00552             for i in zs:
00553                 for l in RowIdxs, ColIdxs, ElVals:
00554                     del l[i]
00555 
00556 
00557         ia = IntArray(RowIdxs)
00558         ja = IntArray(ColIdxs)
00559         ar = DoubleArray(ElVals)
00560 
00561         self._glp_lpx_load_matrix(
00562             len(ElVals),
00563             ia._array,
00564             ja._array,
00565             ar._array)
00566 
00567 
00568     def LoadMtxFromDic(self,dic, KeysAreRowNames=True):
00569 
00570         if KeysAreRowNames:
00571             for k in dic.keys():
00572                 self.SetRowVals(k,dic[k])
00573         else:
00574             print "D'oh !!"
00575 
00576 
00577     def SetObjCoef(self, c, coef):
00578 
00579         if c==-1 or c=="shift":
00580             self._glp_lpx_set_obj_coef(0, coef)
00581 
00582         c = self.__getcol(c)
00583         self._glp_lpx_set_obj_coef(c, coef)
00584 
00585 
00586     def SetObjCoefsFromLists(self, cs, coefs):
00587 
00588         lenc = len(cs)
00589         if lenc != len(coefs):
00590             raise exceptions.IndexError, "cs and coefs not of same length !"
00591 
00592         cs = map(self.__getcol,cs)
00593         for i in range(lenc):
00594             self._glp_lpx_set_obj_coef(cs[i], coefs[i])
00595 
00596 
00597     def SetObjCoefsFromDic(self, d):
00598 
00599         self.SetObjCoefsFromLists(d.keys(), d.values())
00600 
00601 
00602 
00603     #
00604     ##  problem information
00605     #
00606 
00607     def GetDims(self):
00608         return self.GetNumRows(), self.GetNumCols()
00609 
00610     def HasRow(self, r):
00611         """ pre: True
00612            post: HasRow(r) => r is a valid row index """
00613         try:
00614             self.__getrow(r)
00615             return True
00616         except:
00617             return False
00618 
00619 
00620     def HasCol(self, c):
00621         """pre: True
00622           post: HasCol(c) => c is a valid col index """
00623         try:
00624             self.__getcol(c)
00625             return True
00626         except:
00627             return False
00628 
00629 
00630     def GetRow(self, r):
00631         """ self.HasRow(r) => return row r as a list
00632             else: exception """
00633 
00634         r = self.__getrow(r)
00635         lenr = self.GetNumCols()
00636         inds = IntArray(lenr)
00637         vals = DoubleArray(lenr)
00638         self._glp_lpx_get_mat_row(r, inds._array, vals._array)
00639         inds = SubOne(inds.ToList())
00640         vals = vals.ToList()
00641 
00642         return Lists2Vec(inds, vals, lenr)
00643 
00644 
00645     def GetRowsAsLists(self):
00646 
00647         nr = self.GetDims()[0]
00648         return map(self.GetRow, range(nr))
00649 
00650 
00651 
00652 
00653     def GetCol(self, c):
00654 
00655         c = self.__getcol(c)
00656         lenc = self.GetNumCols()
00657         inds = IntArray(lenc)
00658         vals = DoubleArray(lenc)
00659         self._glp_lpx_get_mat_col(c, inds._array, vals._array)
00660         inds = SubOne(inds.ToList())
00661         vals = vals.ToList()
00662 
00663         return Lists2Vec(inds, vals, lenc)
00664 
00665 
00666     def GetRowName(self, r):
00667         self.__getrow(r) # sanity check, exception if r invalid
00668 
00669         if self.rnames.has_key(r):
00670             return self.rnames[r]
00671         return "row_"+str(r)
00672 
00673 
00674     def GetRowNames(self):
00675 
00676         return map(self.GetRowName, range(self.GetDims()[0]))
00677 
00678     def GetColName(self, c):
00679         self.__getcol(c) # sanity check, exception if r invalid
00680 
00681         if self.cnames.has_key(c):
00682             return self.cnames[c]
00683         return "col_"+str(c)
00684 
00685 
00686     def GetColNames(self):
00687 
00688         return map(self.GetColName, range(self.GetDims()[1]))
00689 
00690 
00691 
00692 
00693 
00694 
00695 
00696 
00697     #
00698     ## Solve the problem
00699     #
00700 
00701 
00702 
00703     def Solve(self, Method="Simplex"):
00704 
00705         self._glp_lpx_std_basis()
00706         self._glp_lpx_simplex()
00707 
00708 
00709 
00710     #
00711     ## Status information
00712     #
00713 
00714     def GetStatus(self, Stype="Generic"):
00715         """pre: Stype in ["Generic", "Primal", "Dual"]
00716           post: numerical value of current status """
00717 
00718         return self.__diccheck(self._StatusGetters, Stype)()
00719 
00720 
00721     def GetStatusMsg(self,Stype="Generic"):
00722         """pre: self.GetStatus(Stype)
00723           post: human string describing current status """
00724         return Num2Str[self.GetStatus(Stype)]
00725 
00726 
00727     def GetStatusSym(self,Stype="Generic"):
00728         """pre: self.GetStatus(Stype)
00729           post: symbolic string describing current status """
00730         return Num2Sym[self.GetStatus(Stype)]
00731 
00732 
00733     #
00734     ## Solution information
00735     #
00736     # see also: GetObjVal and GetObjName defined by __init__()
00737 
00738     def GetRowPrimal(self, r):
00739         r = self.__getrow(r)
00740         return self._glp_lpx_get_row_prim(r)
00741 
00742     def GetRowDual(self, r):
00743         r = self.__getrow(r)
00744         return self._glp_lpx_get_row_dual(r)
00745 
00746 
00747 
00748     def GetColPrimal(self, c):
00749         c = self.__getcol(c)
00750         return self._glp_lpx_get_col_prim(c)
00751 
00752     def GetColDual(self, c):
00753         c = self.__getcol(c)
00754         return self._glp_lpx_get_col_dual(c)
00755 
00756 
00757 
00758     #
00759     ##  I/O methods
00760     #
00761 
00762     def Read(self, src, format='CPLEX'):
00763         """pre: format in ['GnuMathProg', 'FixedMPS', 'CPLEX', 'FreeMPS']
00764                 src is readable filename in format format
00765           post: self represents problem in src """
00766 
00767 
00768         self._glp_lpx_delete_prob()
00769         self.lpx = self.__diccheck(self._Readers, format)(src)
00770         self.__setup()
00771         self.__RebuildNameDics()
00772 
00773 
00774 
00775     def Write(self, format="Human", dest=None):
00776         """ pre: format in ['FixedMPS', 'CPLEX', 'Human', 'FreeMPS', 'Solution']
00777                  Dest writable file name OR None
00778             post: Dest != None -> problem written in format to Dest
00779                   Dest == None -> returns proble as a string in format """
00780 
00781 
00782         writer = self.__diccheck(self._Writers, format)
00783         nr,nc = self.GetDims()
00784 
00785         if (nc < 1 or nr <1) and format != "Human":
00786             raise exceptions.IndexError, "must have at least one row and column"
00787 
00788         if dest==None:
00789             return F2Str(writer)
00790         else:
00791             writer(dest)
00792             rv = None
00793         return rv
00794 
00795 
00796 
00797 
00798     def PrintMtx(self):
00799         """ print current constraint matrix on stdout """
00800 
00801         rv =""
00802         nr,nc = self.GetDims()
00803         print " "*10,
00804         for c in range(nc):
00805             print self.GetColName(c).ljust(6),
00806         print
00807         for r in range(nr):
00808             print self.GetRowName(r).ljust(10), " ".join(map(lambda x:("%3.3g"%x).ljust(6), self.GetRow(r)))
00809 
00810 
00811 
00812 
00813 
00814 
00815 
00816 """
00817 lp = glpk_ll.glp_lpx_create_prob()
00818 glpk_ll.glp_lpx_set_prob_name(lp, "sample")
00819 glpk_ll.glp_lpx_set_obj_dir(lp, glpk_ll.LPX_MAX)
00820 glpk_ll.glp_lpx_add_rows(lp, 3)
00821 glpk_ll.glp_lpx_set_row_name(lp, 1, "p")
00822 glpk_ll.glp_lpx_set_row_bnds(lp, 1, glpk_ll.LPX_UP, 0.0, 100.0)
00823 glpk_ll.glp_lpx_set_row_name(lp, 2, "q")
00824 glpk_ll.glp_lpx_set_row_bnds(lp, 2, glpk_ll.LPX_UP, 0.0, 600.0)
00825 glpk_ll.glp_lpx_set_row_name(lp, 3, "r")
00826 glpk_ll.glp_lpx_set_row_bnds(lp, 3, glpk_ll.LPX_UP, 0.0, 300.0)
00827 glpk_ll.glp_lpx_add_cols(lp, 3)
00828 glpk_ll.glp_lpx_set_col_name(lp, 1, "x1")
00829 glpk_ll.glp_lpx_set_col_bnds(lp, 1, glpk_ll.LPX_LO, 0.0, 0.0)
00830 glpk_ll.glp_lpx_set_obj_coef(lp, 1, 10.0)
00831 glpk_ll.glp_lpx_set_col_name(lp, 2, "x2")
00832 glpk_ll.glp_lpx_set_col_bnds(lp, 2, glpk_ll.LPX_LO, 0.0, 0.0)
00833 glpk_ll.glp_lpx_set_obj_coef(lp, 2, 6.0)
00834 glpk_ll.glp_lpx_set_col_name(lp, 3, "x3")
00835 glpk_ll.glp_lpx_set_col_bnds(lp, 3, glpk_ll.LPX_LO, 0.0, 0.0)
00836 glpk_ll.glp_lpx_set_obj_coef(lp, 3, 4.0)
00837 
00838 
00839 ia = IntArray([1,1,1,2,3,2,3,2,3])
00840 ja = IntArray([1,2,3,1,1,2,2,3,3])
00841 ar = DoubleArray([1,1,1,10,2,4,2,5,6])
00842 #ia[1] = 1 ; ja[1] = 1 ; ar[1] =  1.0 # /* a[1,1] =  1 */
00843 #ia[2] = 1 ; ja[2] = 2 ; ar[2] =  1.0 # /* a[1 ;2] =  1 */
00844 #ia[3] = 1 ; ja[3] = 3 ; ar[3] =  1.0 # /* a[1 ;3] =  1 */
00845 #ia[4] = 2 ; ja[4] = 1 ; ar[4] = 10.0 # /* a[2 ;1] = 10 */
00846 #ia[5] = 3 ; ja[5] = 1 ; ar[5] =  2.0 # /* a[3 ;1] =  2 */
00847 #ia[6] = 2 ; ja[6] = 2 ; ar[6] =  4.0 # /* a[2 ;2] =  4 */
00848 #ia[7] = 3 ; ja[7] = 2 ; ar[7] =  2.0 # /* a[3 ;2] =  2 */
00849 #ia[8] = 2 ; ja[8] = 3 ; ar[8] =  5.0 # /* a[2 ;3] =  5 */
00850 #ia[9] = 3 ; ja[9] = 3 ; ar[9] =  6.0 # /* a[3 ;3] =  6 */
00851 
00852 glpk_ll.glp_lpx_load_matrix(lp, 9, ia._array, ja._array, ar._array)
00853 glpk_ll.glp_lpx_simplex(lp)
00854 Z = glpk_ll.glp_lpx_get_obj_val(lp)
00855 x1 = glpk_ll.glp_lpx_get_col_prim(lp, 1)
00856 x2 = glpk_ll.glp_lpx_get_col_prim(lp, 2)
00857 x3 = glpk_ll.glp_lpx_get_col_prim(lp, 3)
00858 print "\nZ =", Z, " x1 = ",x1," x2 = ",x2," x3 = ", x3
00859 #glpk_ll.glp_lpx_delete_prob(lp)
00860  #     return 0
00861 """

Generated on Tue Sep 4 2012 15:38:01 for ScrumPy by  doxygen 1.7.1