Skip to content
Snippets Groups Projects
Commit 2299f49e authored by Goes,M. (Martijn)'s avatar Goes,M. (Martijn)
Browse files

Better IO, added testinstance 1, gurobipy tests for knapsack + start of ex2

parent fa9ebfad
No related branches found
No related tags found
No related merge requests found
No preview for this file type
ex2.py 0 → 100644
import gurobipy as gp
from gurobipy import GRB
p1 = 55
c1 = 50
p2 = 25
c2 = 100
n = 3 # projects
T = 4 # days
w_it = [ [2,2,2,2] ,
[4,3,4,2],
[10,0,0,0] ] # row = task number, col = day
u_i = [1,0,0,2] # minimal number of experienced workers
m = gp.Model()
r_it = m.addMVars((3,4), vtype=GRB.INTEGER, name="reg") # regular workers
e_it = m.addMVars((3,4), vtype=GRB.INTEGER, name="exp") # experienced workers
m.setObjective(gp.quicksum(r_it[i,t] * c1 + e_it[i,t] * c2 for i in range(n) for t in range(T)), GRB.MAXIMIZE)
# m.addConstr(gp.quicksum(r_it[i,t] for i in range (n)))
\ No newline at end of file
import gurobipy as gp
from gurobipy import GRB
"""
Solves the regular Knapsack problem (to get acquainted with gurobipy).
Easy regular gurobipy example: https://pypi.org/project/gurobipy/
Knapsack gurobipy: https://gist.github.com/jhelgert/eb8cc47dda8795f60a68afb10ac95433
j = 1..n items
weight a_j
value c_j
B = volume of knapsack
Use decision variable x_j = 0 or 1 to (not) take item j
"""
n = 9 # number of items
c = [6, 6, 8, 9, 6, 7, 3, 2, 6] # value
a = [2, 3, 6, 7, 5, 9, 4, 8, 5] # weight
B = 20 # volume
m = gp.Model()
x = m.addVars(n, vtype=GRB.BINARY, name="x")
m.setObjective(gp.quicksum(c[i] * x[i] for i in range(n)), GRB.MAXIMIZE)
m.addConstr((gp.quicksum(a[i] * x[i] for i in range(n)) <= B), name="knapsack")
m.optimize()
print(f"Optimal objective value: {m.objVal}")
for xj in x:
print(x[xj])
\ No newline at end of file
......@@ -2,21 +2,37 @@ from cmath import inf
import numpy as np
import os
import offline as LP
from typing import Tuple, List
from functools import reduce
def ParseInput(src):
contents = open(src,'r')
def ParseInput(src : str) -> Tuple[List[float], List[Tuple[float, float]]]:
"""This function parses input from a file for the telescope problem.
The function will parse the first line to know how many pictures we want to send.
The following n lines contain the sizes of the images.
The next line contains the number of blackouts
The next n lines contain the time and the length of the blackout seperated by a comma.
imageCount = int(contents.readline())
Args:
src (string): The name of the inputfile
Returns:
Tuple[List[float], List[Tuple[float, float]]: Returns 2 lists: one list with the images and one list with the blackouts
"""
contents = list()
with open(src, 'r') as INPUT_FILE:
contents = INPUT_FILE.readlines()
imageCount = int(contents.pop(0))
imageCollection = np.empty(imageCount)
for i in range (0, imageCount):
imageCollection[i] = float(contents.readline())
imageCollection[i] = float(contents.pop(0))
blackoutCount = int(contents.readline())
blackoutCollection = [] # tuples, so just a list, no need for numpy array
blackoutCount = int(contents.pop(0))
blackoutCollection = list() # tuples, so just a list, no need for numpy array
for _ in range (0, blackoutCount):
string = contents.readline().split(", ") # delimiter between start and end
string = contents.pop(0).split(", ") # delimiter between start and end
startTime = float(string[0])
endTime = float(string[1])
blackoutCollection.append((startTime, startTime + endTime))
......@@ -24,21 +40,26 @@ def ParseInput(src):
# add imaginary black box at infinity, so there is always a black box to the right of an image
blackoutCollection.append((float(inf), float(inf)))
print("image sizes: {}".format(imageCollection))
print("blackouts: {}".format(blackoutCollection))
print(f"image sizes: {imageCollection}")
print(f"blackouts: {blackoutCollection}")
return (imageCollection, blackoutCollection)
def PrintOutput(filename, endTime, imageTimes):
if os.path.exists(filename):
os.remove(filename)
def PrintOutput(filename : str, endTime : float, imageTimes : List[float]):
"""This function writes the output of the algorithm to a given outputfile
The first lane contains the endTime of the last picture
The other lines contain the startTime of each image
result = open(filename, 'w')
result.write("{}".format(str(endTime)))
for i in range(0, len(imageTimes)):
result.write("\n{}".format(str(imageTimes[i])))
Args:
filename (str): The filename of the outputfile to write the output to
endTime (float): The time between t0 and the end of the last picture
imageTimes (List[float]): The startTimes for all the images
"""
with open(filename, 'w') as OUTPUT_FILE:
OUTPUT_FILE.write(f"{str(endTime)}")
OUTPUT_FILE.writelines(reduce(lambda x, y: x + "\n" + f"{str(y)}", imageTimes, ""))
parsedIn = ParseInput('t1_in.txt')
res = LP.Solve(parsedIn[0], parsedIn[1])
PrintOutput('t1_out.txt', res[0], res[1])
\ No newline at end of file
if __name__ == "__main__":
parsedIn = ParseInput('t1_in.txt')
res = LP.Solve(parsedIn[0], parsedIn[1])
PrintOutput('t1_out.txt', res[0], res[1])
\ No newline at end of file
......@@ -24,7 +24,8 @@ def Solve(images, blackouts):
else:
time = "No solution"
return (41.618, [35, 29.6, 18, 35.618, 0.86])
# return (41.618, [35, 29.6, 18, 35.618, 0.86]) # answer to test instance 0
return (45, [22, 4, 35, 42, 0, 5, 28, 11]) # answer to test instance 1
# return (time, timeSteps)
......
5
0.618
2.5
10
6
3.14
2
4, 0.25
5, 11
\ No newline at end of file
41.618
35
29.6
18
35.618
0.86
\ No newline at end of file
8
1
1.9
3
3
5
5
0.618
2.5
10
6
3.14
2
4, 0.25
5, 11
\ No newline at end of file
11
5
10.5, 0.5
23.1, 0.9
26, 2
34.5, 0.5
41, 1
\ No newline at end of file
41.618
45
22
24
35
29.6
18
35.618
0.86
\ No newline at end of file
42
0
5
28
11
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment