02b - Optimasi II - Algorithm and Python - 2024
02b - Optimasi II - Algorithm and Python - 2024
• Integrality constraint?
• Minimum cost network flow (MCNF) problem
Minimum cost network flow problem
6
Python language and how to run it
python
Anaconda Jyupiter, Google
Important data structures in Python:
Colabs, Spyder Python, etc lists (strings), tuples, and dictionaries
Function declarations
The Python Programming Language
• c = “u” OR c = ‘u’
• while statement
while i < 40:
do something
Control Structures (cont’d)
• for statement
for i in [1,2,4]:
print(i)
for i in range(50):
if i == 10:
break
• http://docs.python.org/2/tutorial/controlflow.html
Lists
• Creating a list
list0 = [] # create empty list manually
• Slicing
a = [99, 'bottles of love', ['on', 'the', 'wall']]
print(a[0:2])
→ [99, 'bottles of love']
print(a[1:])
→ ['bottles of love', ['on', 'the', 'wall']]
• Reverse indexing
print(a[-1])
→ ['on', 'the', 'wall']
print(a[-3:-1])
→ [99, 'bottles of love']
• Delete elements
del a[1]
print(a)
→ [99, ['on', 'the', 'wall']]
Lists (cont’d)
a = [0, 1, 2]
b = [3, 4]
a + b →
a * 3 →
a.append(5) → [0, 1, 2, 5]
a.pop(1) → [0, 2, 5]
a.insert(1, 42) → [0, 42, 2, 5]
a.reverse() → [5, 2, 42, 0]
a.sort() → [0, 2, 5, 42]
sorted(a) → [0, 2, 5, 42]
print(len(a))
→4
Strings
A string is similar to a list of characters
a = 'hello'
print(a[0])
→ 'h'
print(a[1:4])
→ 'ell'
print(a[-1])
→ 'o'
for c in a:
print(c)
→h e l l o
strvar5 = ''
strvar5 += 'cr'
strvar5 += 'ude' # concatenation
String formatting
# using string formatting
strvar3 = 'Pi is about %.4f' % 3.142951
→ 'Pi is about 3.1430’
len('hello') → 5 # size
# splitting strings
'hello_world'.split('_') → ['hello','world']
# remove whitespace
'hello_world \n'.strip() → 'hello_world'
Tuples
• Create a tuple
tup = ()
tup = ('32', 4, 'yes', 3.14)
• http://docs.python.org/2/library/functions.html#tuple
Dictionaries
• Dictionary are "associative arrays" mapping keys to
values: {key: value}
d = {
'Marky':'Mark', 'Funky':'Bunch', 3:'4', (1,2):[1,2,3]
}
print(d['Marky']) → 'Mark'
d['Donnie'] → error # raises KeyError exception
d['Donnie'] = 'Wahlberg' # value assignment
def f1(a):
a.append(4)
b = [1,2,3]
f1(b)
def f2(a):
a = 4
b = [1,2,3]
f2(b)
Pointers (or Reference vs. Copy)
• Another option:
m = Model(sense=MAXIMIZE, solver_name=CBC) # use
GRB for Gurobi
Build and optimize models using Python-MIP (2)
m.read('model.lp')
print('model has {} vars, {} constraints and {}
nzs'.format(m.num_cols, m.num_rows, m.num_nz))
Build and optimize models using Python-MIP (6)
• Optimizing and Querying Optimization Results
• The optimize() method, that executes the optimization of a
formulation, accepts optionally processing limits as parameters.
m.max_gap = 0.05
status = m.optimize(max_seconds=300)
if status == OptimizationStatus.OPTIMAL:
print('optimal solution cost {}
found'.format(m.objective_value))
elif status == OptimizationStatus.FEASIBLE:
print('sol.cost {} found, best possible:
{}'.format(m.objective_value, m.objective_bound))
elif status == OptimizationStatus.NO_SOLUTION_FOUND:
print('no feasible solution found, lower bound is:
{}'.format(m.objective_bound))
if status == OptimizationStatus.OPTIMAL or status ==
OptimizationStatus.FEASIBLE:
print('solution:')
for v in m.vars:
if abs(v.x) > 1e-6: # only printing non-zeros
print('{} : {}'.format(v.name, v.x))
Build and optimize models using Python-MIP (7)
The optimize() method returns the status (OptimizationStatus) of the BC
search:
• OPTIMAL if the search was concluded and the optimal solution was
found;
• FEASIBLE if a feasible solution was found but there was no time to prove
whether this solution was optimal or not;
• NO_SOLUTION_FOUND if in the truncated search no solution was found;
• INFEASIBLE or INT_INFEASIBLE if no feasible solution exists for the
model;
• UNBOUNDED if there are missing constraints or
• ERROR if some error occurred during optimization.
for k in range(model.num_solutions):
print('route {} with length {}'.format(k,
model.objective_values[k]))
for (i, j) in product(range(n), range(n)):
if x[i][j].xi(k) >= 0.98:
print('\tarc ({},{})'.format(i,j))
Hands-on python for
optimization
Knapsack problem
from mip import Model, xsum,
maximize, BINARY, CBC
p = [10, 13, 18, 31, 7, 15]
w = [11, 15, 20, 35, 10, 33]
c, I = 47, range(len(w))
m = Model("knapsack",
Knapsack solver_name=CBC)
problem x = [m.add_var(var_type=BINARY)
for i in I]