GLPK
Introducció
En aquest exemple, explorarem com enviar a Multivac un programa usant Glpk per a calcular una funció objectiu.
Codi d’exemple
Suposem que volem maximitzar la següent funció objectiu:
Crearem un arxiu per exemple anomenat test_glpk.py per a calcular el resultat:
#!/usr/bin/python3
import glpk # Import the GLPK module
lp = glpk.LPX() # Create empty problem instance
lp.name = 'sample' # Assign symbolic name to problem
lp.obj.maximize = True # Set this as a maximization problem
lp.rows.add(3) # Append three rows to this instance
for r in lp.rows: # Iterate over all rows
r.name = chr(ord('p')+r.index) # Name them p, q, and r
lp.rows[0].bounds = None, 100.0 # Set bound -inf < p <= 100
lp.rows[1].bounds = None, 600.0 # Set bound -inf < q <= 600
lp.rows[2].bounds = None, 300.0 # Set bound -inf < r <= 300
lp.cols.add(3) # Append three columns to this instance
for c in lp.cols: # Iterate over all columns
c.name = 'x%d' % c.index # Name them x0, x1, and x2
c.bounds = 0.0, None # Set bound 0 <= xi < inf
lp.obj[:] = [10.0, 6.0, 4.0] # Set objective coefficients
lp.matrix = [
1.0, 1.0, 1.0, # Set nonzero entries of the
10.0, 4.0, 5.0, # constraint matrix. (In this
2.0, 2.0, 6.0 # case, all are non-zero.)
]
lp.simplex() # Solve this LP with the simplex method
print ('Z = %g;' % lp.obj.value) # Retrieve and print obj func value
print ('; '.join('%s = %g' % (c.name, c.primal) for c in lp.cols))
Execució
Crearem un virtual environment de python anomenat venv. Aquest pas només és necessari fer la primera vegada que es vol crear el venv, les altres vegades es pot reusar el mateix.
Es requereix instal·lar el paquet glpk: pip install glpk
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install glpk
$ deactivate
Crearem un document amb els parametres de configuració, per exemple: test_glpk.slurm` que conté la configuració d’execució per a aquest script de glpk.
VERSION=1.3
JOB_NAME=test_glpk
NAME_OUTPUT=out
PARTITION=all
N_TASKS=1
CPUS_PER_TASK=1
MAIL_TYPE=END,FAIL
MAIL_USER=nom.usuari@upc.edu
MEMORY=1G
BEGIN=now
TIME_LIMIT=00:05:00
LOG_OUTPUT=log
FORCED_NODES=
EXCLUDED_NODES=
ROUTE=~/
COMMANDS=(
"hostname" #Per a saber a quina màquina s'ha executat
"source $ROUTE/venv/bin/activate"
"python3 $ROUTE/test_glpk.py"
"deactivate"
)
Aquest script el llançarem des de iocex usant la següent comanda:
multivac test_glpk.slurm
El resultat del nostre programa un cop finalitzada l’execució serà visible al mateix directori a on hem fet l’execució.