Пример #1
0
def opt(i):
    x,xx=oovars('x xx',domain=bin)
    startpoint={x:[0]*m,xx:[0]*(m*m)}
    constraints=[sum([x[j]*p[j]for j in range(m)])<=b[i]]+[\
                                                             (sum(x[k]for k in range(m) if req[i][j][0][k])<=req[i][j][1])\
                                                             for j in range(len(req[i]))]\
                                                             +[xx[j*m+k]*2<=x[j]+x[k] for j in range(m) for k in range(m)]\
                                                             +[xx[j*m+k]*2>=x[j]+x[k]-1 for j in range(m) for k in range(m)]
    obj=sum([v[i,j]*x[j] for j in range(m)])+sum(xx[j*m+k]*cov[i,j,k] for j in range(m) for k in range(m))
    prob=MILP(objective=obj, startPoint=startpoint, constraints=constraints)
    r=prob.solve('ralg')
    return [r(x[j])for j in range(m)]
Пример #2
0
def compute_sol():
    intVars = range(N_vars)
    lb = zeros(N_vars)
    ub = ones(N_vars)

    def denseRow(r):
        row = zeros(N_vars)
        for i, v in r.items():
            row[i] = v
        return row

    A = map(denseRow, A_lt)
    Aeq = map(denseRow, A_eq)
    ff = denseRow(f)

    p = MILP(f=ff, lb=lb, ub=ub, A=A, b=b_lt, Aeq=Aeq, beq=b_eq, intVars=intVars, goal='min')
    r = p.solve('glpk', iprint =-1)
    return r.xf
    f = [1]*optpaths; 
    intVars = range(0,optpaths); # all integer variables

    lb = array([0.0]*optpaths);
    ub = array([1.0]*optpaths); # assume binary variables ( wouldn't go down same path twice )
    A = zeros((optlabs, optpaths))

    for pidx in range(0,optpaths):
        for lidx in range(0,optlabs):
            if ( rlmap[lidx][1] < len(paths[rpmap[pidx]]) and paths[rpmap[pidx]][rlmap[lidx][1]] == rlmap[lidx][0] ):
                A[lidx,pidx] = -1; # everything negated

    b = [-1]*optlabs;


    p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars, goal='min')
    #r = p.solve('lpSolve')
    curtime = time_module.time();
    r = p.solve('glpk')
    print "Solver done. Took %.5f real time."%(time_module.time()-curtime)
    optneeded_paths = r.ff

# Decode solution
print 'Units needed:', len(mustpaths)+optneeded_paths
taken = mustpaths;
if ( optlabs > 0 ):
    for pidx in range(0,optpaths):
        if ( r.xf[pidx] == 1 ):
            taken.append(rpmap[pidx]);
        
print 'Taken paths:',taken
Пример #4
0
f = [1, 2, 3, 4, 5, 4, 2, 1]

# indexing starts from ZERO!
# while in native lpsolve-python wrapper from 1
# so if you used [5,8] for native lp_solve python binding
# you should use [4,7] instead
intVars = [4, 7]

lb = -1.5 * ones(8)
ub = 15 * ones(8)
A = zeros((5, 8))
b = zeros(5)
for i in xrange(5):
    for j in xrange(8):
        A[i,j] = -8+sin(8*i) + cos(15*j)
    b[i] = -150 + 80*sin(80*i)

p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars)

# if file name not ends with '.MPS' or '.mps'
# then '.mps' will be appended
success = p.exportToMPS('/home/dmitrey/PyTest/milp_1')
# or write into current dir: 
# success = p.exportToMPS('milp')
# success is False if a error occurred (read-only file system, no write access, etc)
# elseware success is True

# f_opt is 25.801450769161505
# x_opt is [ 15. 10.15072538 -1.5 -1.5 -1.  -1.5 -1.5 15.]
def opt_wta_step_1(weapon_units, target_units, ai, tool = 'cvxpy'):
    start_time = time.time()

    ### Set parameter
    WASTE_DAMAGE_COEF = 1.2
    REMAIN_DAMAGE_RATIO = 0.05
    ### Remark
    # Part 2: distence concept, in Build objective function, need more discuss ...

    ### Build information table
    damage_table, remain_damage_point = build_damage_table(target_units)
    hitpoints_table = build_hitpoints_table(target_units)
    maxhitpoints_table = [target_unit.type.maxHitPoints for target_unit in target_units]
    injury_table = build_injury_table(weapon_units, target_units, move_coef = ai.MOVE_COEF)
    max_injury_table = build_max_injury_table(weapon_units, target_units, injury_table)
    move_cost_table, total_move_cost = build_move_cost_table(weapon_units, target_units)
    
    m, n = len(weapon_units), len(target_units)
    
    if tool == 'cvxpy':
        obj_func_coef_table = []
        var_map_table = []
        for i in range(m):
            for j in range(n):
                if injury_table[i][j] != 0:
                    obj_func_coef_table.append(-damage_table[j] * injury_table[i][j] / hitpoints_table[j] / maxhitpoints_table[j])
                    var_map_table.append((i, j))
        var_amount = len(var_map_table)

        X = cvx.Bool(var_amount)
        #
        ### Build objective function
        # Part 1: damage concept
        obj_func = 0
        for i in xrange(var_amount):
            obj_func  = obj_func + obj_func_coef_table[i] * X[i]
        obj_func = cvx.Minimize(obj_func)
        #
        ### Build constraints
        cons_weapon_count = []
        for i in xrange(m):
            cons_weapon_count.append(0)
        cons_waste_damage = []
        for j in xrange(n):
            cons_waste_damage.append(0)
        for var_num, index in zip(range(var_amount), var_map_table):
            cons_weapon_count[index[0]] += X[var_num]
            cons_waste_damage[index[1]] += injury_table[index[0]][index[1]] * X[var_num]
        #
        cons = []
        for i in xrange(m):
            cons.append(cons_weapon_count[i] == 1)
        for j in xrange(n):
            cons.append(cons_waste_damage[j] <= hitpoints_table[j] + WASTE_DAMAGE_COEF * max_injury_table[j])
        #
        ### Start compute
        prob = cvx.Problem(obj_func, cons)
        prob.solve()
        #
        wta_result_1 = []
        zero_list = []
        for j in xrange(n):
            zero_list.append(0)
        for i in xrange(m):
            wta_result_1.append(list(zero_list))
        for i in xrange(var_amount):
            if X[i].value > 0.1:
                wta_result_1[var_map_table[i][0]][var_map_table[i][1]] = 1
        #
        #### Build result: target_of_weapon
        #target_of_weapon = []
        #for i in range(m):
        #    target_of_weapon.append(None)
        #    for j in range(n):
        #        if X[i, j].value > 0.1:
        #            target_of_weapon[i] = target_units[j]
        #            break
        #    if not target_of_weapon[i]:
        #        target_of_weapon[i] = target_units[0]
    elif tool == 'cvxpy_old':
        X = cvx.Bool(m, n)
        #
        ### Build objective function
        # Part 1: damage concept
        tmp_func = hitpoints_table[0] - injury_table[0][0] * X[0, 0]
        for i in range(1, m):
            tmp_func  = tmp_func - injury_table[i][0] * X[i, 0]
        obj_func = damage_table[0] / (target_units[0].hitPoints * target_units[0].type.maxHitPoints) * tmp_func 
        for j in range(1, n):
            tmp_func = hitpoints_table[j] - injury_table[0][j] * X[0, j]
            for i in range(1, m):
                tmp_func  = tmp_func - injury_table[i][j] * X[i, j]
            obj_func = obj_func + damage_table[j] / (target_units[j].hitPoints * target_units[j].type.maxHitPoints) * tmp_func
        obj_func = cvx.Minimize(obj_func)
        #
        ### Build constraints
        cons = []
        for i in range(m):
            tmp_cons = X[i, 0]
            for j in range(1, n):
                tmp_cons = tmp_cons + X[i, j]
            cons.append(tmp_cons <= 1)
        #
        for j in range(n):
            tmp_cons = injury_table[0][j] * X[0, j]
            for i in range(1, m):
                tmp_cons  = tmp_cons + injury_table[i][j] * X[i, j]
            tmp_cons = tmp_cons <= hitpoints_table[j] + WASTE_DAMAGE_COEF * max_injury_table[j]
            cons.append(tmp_cons)
        #
        ### Start compute
        prob = cvx.Problem(obj_func, cons)
        prob.solve()
        #
        wta_result_1 = []
        zero_list = []
        for i in range(n):
            zero_list.append(0)
        for i in range(m):
            wta_result_1.append(list(zero_list))
            for j in range(n):
                if X[i, j].value > 0.1:
                    wta_result_1[i][j] = 1
                    break
        #
        #### Build result: target_of_weapon
        #target_of_weapon = []
        #for i in range(m):
        #    target_of_weapon.append(None)
        #    for j in range(n):
        #        if X[i, j].value > 0.1:
        #            target_of_weapon[i] = target_units[j]
        #            break
        #    if not target_of_weapon[i]:
        #        target_of_weapon[i] = target_units[0]
    elif tool == 'openopt':
        #from openopt import MILP
        obj_func = []
        var_map_table = []
        for i in range(m):
            for j in range(n):
                if injury_table[i][j] != 0:
                    obj_func.append(-damage_table[j] * injury_table[i][j] / hitpoints_table[j] / maxhitpoints_table[j])
                    var_map_table.append((i, j))
        var_amount = len(var_map_table)
        #
        intVars = range(var_amount)
        #
        A = np.zeros((n, var_amount))
        Aeq = np.zeros((m, var_amount))
        for var_num, index in zip(range(var_amount), var_map_table):
            Aeq[index[0]][var_num] = 1
            A[index[1]][var_num] = injury_table[index[0]][index[1]]
        #
        b = np.mat(hitpoints_table) + WASTE_DAMAGE_COEF * np.mat(max_injury_table)
        beq = np.ones(m)
        #
        lb = np.zeros(var_amount)
        ub = np.ones(var_amount)
        #
        p = MILP(f=obj_func, lb=lb, ub=ub, A=A, b=b, Aeq=Aeq, beq=beq, intVars=intVars, goal='min')
        #r = p.solve('lpSolve')
        r = p.solve('glpk', iprint =-1)
        #r = p.solve('cplex')
        wta_result_1 = []
        zero_list = []
        for i in xrange(n):
            zero_list.append(0)
        for i in xrange(m):
            wta_result_1.append(list(zero_list))
        for i in xrange(var_amount):
            if r.xf[i] == 1:
                wta_result_1[var_map_table[i][0]][var_map_table[i][1]] = 1

        #ai.game.printf("step 1 --- %s seconds ---" % (time.time() - start_time))

    ### dump data to readable file or pickle file
    if ai.write_wta_1_count > 0:
        #write_data_in_file(damage_table, 'damage_table.txt')
        #write_data_in_file(hitpoints_table, 'hitpoints_table.txt')
        #write_data_in_file(maxhitpoints_table, 'maxhitpoints_table.txt')
        #write_data_in_file(injury_table, 'injury_table.txt')
        #write_data_in_file(max_injury_table, 'max_injury_table.txt')
        #write_data_in_file(wta_result_1, 'wta_result_1.txt')
        ##
        #write_data_in_pickle_file([damage_table, hitpoints_table, maxhitpoints_table, injury_table, max_injury_table], 'opt_data.pkl')
        #write_data_in_pickle_file(damage_table, 'opt_data.pkl')
        #write_data_in_pickle_file(hitpoints_table, 'opt_data.pkl')
        #write_data_in_pickle_file(injury_table, 'opt_data.pkl')
        #write_data_in_pickle_file(max_injury_table, 'opt_data.pkl')
        ##
        ai.write_wta_1_count -= 1

    #print("step 1 --- %s seconds ---" % (time.time() - start_time))
    #game.printf("\x04 ---------------------------")
    #game.printf("\x10 Minimize : " + str(prob.value))
    #game.printf("\x1E R.D.P    : " + str(remain_damage_point))
    return wta_result_1
Пример #6
0
f3 = 5*f1 + 4*f2 + 20

# Define objective; sum(a) and a.sum() are same as well as for numpy arrays
obj = x.sum() + y + 50*z + sum(f3) + 2*f2.sum() + 4064.6

# Start point - currently matters only size of variables
startPoint = {x:[8, 15], y:25, z:80} # however, using numpy.arrays is more recommended than Python lists

# Define some constraints
cons = [x+5*y<15, x[0]<-5, f1<[25, 35], f1>-100, 2*f1+4*z<[80, 800], 5*f2+4*z<100, [-5.5, -4.5]<x,  x<1, -17<y,  y<20, -4000<z, z<4]

# Create prob
# old-style:
#p = MILP(obj, startPoint, intVars = [y, z], constraints=cons)
# new (OpenOpt v 0.37+): 
p = MILP(obj, startPoint, constraints=cons)

# Solve
r = p.minimize('lpSolve', iprint=-1) # glpk is name of the solver involved, see OOF doc for more arguments

# Decode solution
s = r.xf
print('Solution: x = %s   y = %f  z = %f' % (str(s[x]), s[y], s[z]))
# Solution: x = [-5.25 -4.5 ]   y = 3.000000  z = -33.000000

# OPTIONAL: you can export the problem into MPS format file
# (lpsolve and its Python binding should be properly installed,
# you may take a look at the instructions from openopt.org/LP)
# if file name not ends with '.MPS' or '.mps'
# then '.mps' will be appended
success = p.exportToMPS('milp_1')
Пример #7
0
 d=oovar('d',domain=int)
 bef,ov=oovars('bef ov',domain=bool)
 loss=[p*(1-p)**(i+1)-p*(1-p)**i for i in range(m)]
 obj = p*m+sum([ov[corr2[i,j]]*loss[j] for i in range(m) for j in range(int(sum(con[i])))])
 
 # Start point - currently matters only size of variables
 startPoint = {d:[0]*m,bef:[0]*lyc ,ov:[0]*xtt} # however, using numpy.arrays is more recommended than Python lists
 # Define some constraints
 cons = [bef[corr[i,j]]+bef[corr[j,i]]==1 for i in range(m) for j in range(i+1,m) if con[i,j]>0.5]+\
     [d[i]==sum([bef[corr[j,i]] for j in range(m) if con[i,j]>0.5]+[0]) for i in range(m)]+\
     [d[i]<=j+ov[corr2[i,j]]*100 for i in range(m) for j in range(int(sum(con[i])))]
 # Create prob
 # old-style:
 #p = MILP(obj, startPoint, intVars = [y, z], constraints=cons)
 # new (OpenOpt v 0.37+): 
 pp = MILP(obj, startPoint, constraints=cons,maxIter=5000)
  
 # Solve
 r = pp.maximize('cplex') # glpk is name of the solver involved, see OOF doc for more arguments
  
 # Decode solution
 s = r.xf
 tmp=[[i,s[d][i]]for i in range(m)]
 order=[i[0] for i in sorted(tmp,key=lambda x:x[1])]
 t2=time.time()
 def payoff(a,p=0.7):
     m=len(a)
     ans=0
     for i in range(m):
         tmp=p
         for j in range(i):
Пример #8
0
__docformat__ = "restructuredtext en"

from numpy import *
from openopt import MILP

f = [1, 2, 3, 4, 5, 4, 2, 1]

# indexing starts from ZERO!
# while in native lpsolve-python wrapper from 1
# so if you used [5,8] for native lp_solve python binding
# you should use [4,7] instead
intVars = [4, 7]

lb = -1.5 * ones(8)
ub = 15 * ones(8)
A = zeros((5, 8))
b = zeros(5)
for i in xrange(5):
    for j in xrange(8):
        A[i,j] = -8+sin(8*i) + cos(15*j)
    b[i] = -150 + 80*sin(80*i)

p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars, goal='min')
r = p.solve('lpSolve')
#r = p.solve('glpk', iprint =-1)
#r = p.solve('cplex')

print('f_opt: %f' % r.ff) # 25.801450769161505
print('x_opt: %s' % r.xf) # [ 15. 10.15072538 -1.5 -1.5 -1.  -1.5 -1.5 15.]
    b = b + [NUMDRIFTERS];
    for pidx in range(0,len(boattrips[0])):
        A[optlabs,pidx] = 1;
            
    # [mask of paths starting at bidx] * x_paths <= [mask of paths ending for bidx] * x_paths
    for bidx in range(1, TIME/BOATTIME/2):
        for pidx in range(0,len(boattrips[bidx])):
            A[optlabs+ bidx,boatoptstart[bidx] + pidx] = 1;
    
        
        for pidx in boatends[bidx]:
            A[optlabs+ bidx,pidx] = -1;
          
    b = b + [0]*(TIME/BOATTIME/2-1);

    p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars, goal='max')
    #r = p.solve('lpSolve')
    curtime = time_module.time();
    r = p.solve('cplex')
    print "Solver done. Took %.5f real time."%(time_module.time()-curtime)
    optlabels_hit = r.ff

# Decode solution
labs_got = [];
if ( optlabs > 0 ):
    for lidx in range(0,optlabs):
        if ( r.xf[lidx+numpaths] == 1 ):
            labs_got.append(rlmap[lidx]);
            

paths_taken = [];
Пример #10
0
intVars = range(var_amount)

A = np.zeros((n, var_amount))
Aeq = np.zeros((m, var_amount))
for var_num, index in zip(range(var_amount), var_map_table):
    Aeq[index[0]][var_num] = 1
    A[index[1]][var_num] = injury_table[index[0]][index[1]] / hitpoints_table[index[1]]

b = np.mat(hitpoints_table) + WASTE_DAMAGE_COEF * np.mat(max_injury_table)
beq = np.ones(m)

lb = np.zeros(var_amount)
ub = np.ones(var_amount)

p = MILP(f=obj_func, lb=lb, ub=ub, A=A, b=b, Aeq=Aeq, beq=beq, intVars=intVars, goal='min')
#r = p.solve('lpSolve')
r = p.solve('glpk', iprint =-1)
#r = p.solve('cplex')



###########################################################################################
#from FuncDesigner import *
#WASTE_DAMAGE_COEF = 1.2
#
#start_time = time.time()
#
#m, n = len(injury_table), len(damage_table)
#
#startPoint = {}
    f = [1]*optpaths; 
    intVars = range(0,optpaths); # all integer variables

    lb = array([0.0]*optpaths);
    ub = array([1.0]*optpaths); # assume binary variables ( wouldn't go down same path twice )
    A = zeros((optlabs, optpaths))

    for pidx in range(0,optpaths):
        for lidx in range(0,optlabs):
            if ( rlmap[lidx] in paths[rpmap[pidx]] ):
                A[lidx,pidx] = -1; # everything negated

    b = [-1]*optlabs;


    p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars, goal='min')
    #r = p.solve('lpSolve')
    r = p.solve('glpk')
    optneeded_paths = r.ff

# Decode solution
print 'Units needed:', len(mustpaths)+optneeded_paths
taken = mustpaths;
if ( optlabs > 0 ):
    for pidx in range(0,optpaths):
        if ( r.xf[pidx] == 1 ):
            taken.append(rpmap[pidx]);
        
print 'Taken paths:',taken
print "Writing output"
fout = open("taken_paths.txt","w");
    A = zeros((optlabs + 1, numpaths + optlabs))

    for pidx in range(0, numpaths):
        for lidx in range(0, optlabs):
            if (rlmap[lidx] in paths[pidx]):
                A[lidx, pidx] = -1
                # everything negated

        A[optlabs, pidx] = 1

    for lidx in range(0, optlabs):
        A[lidx, lidx + numpaths] = 1

    b = [0] * optlabs + [NUMDRIFTERS]

    p = MILP(f=f, lb=lb, ub=ub, A=A, b=b, intVars=intVars, goal='max')
    #r = p.solve('lpSolve')
    r = p.solve('cplex')
    optlabels_hit = r.ff

# Decode solution
labs_got = []
if (optlabs > 0):
    for lidx in range(0, optlabs):
        if (r.xf[lidx + numpaths] == 1):
            labs_got.append(rlmap[lidx])

print 'Labels satisfied:', labs_got
print 'Total pixels covered:', optlabels_hit

taken = []