Exemplo n.º 1
1
def test_model():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype = 'C', obj = 1.0)
    y = s.addVar("y", vtype = 'C', obj = 2.0)

    assert x.getObj() == 1.0
    assert y.getObj() == 2.0

    s.setObjective(4.0 * y + 10.5, clear = False)
    assert x.getObj() == 1.0
    assert y.getObj() == 4.0
    assert s.getObjoffset() == 10.5

    # add some constraint
    c = s.addCons(x + 2 * y >= 1.0)
    assert c.isLinear()
    s.chgLhs(c, 5.0)
    s.chgRhs(c, 6.0)

    assert s.getLhs(c) == 5.0
    assert s.getRhs(c) == 6.0

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
    assert s.getSlack(c, solution) == 0.0
    assert s.getSlack(c, solution, 'lhs') == 0.0
    assert s.getSlack(c, solution, 'rhs') == 1.0
    assert s.getActivity(c, solution) == 5.0

    s.writeProblem('model')
    s.writeProblem('model.lp')

    s.freeProb()
    s = Model()
    x = s.addVar("x", vtype = 'C', obj = 1.0)
    y = s.addVar("y", vtype = 'C', obj = 2.0)
    c = s.addCons(x + 2 * y <= 1.0)
    s.setMaximize()

    s.delCons(c)

    s.optimize()

    assert s.getStatus() == 'unbounded'
Exemplo n.º 2
1
    def getColumnFromMIP(self, timeLimit):

        def getPatternFromSolution(subMIP):
            edges = []
            for x in subMIP.getVars():
                if "x" in x.name:
                    if subMIP.getVal(x) > 0.99:
                        i, j = x.name.split("_")[1:]
                        edges.append((int(i), int(j)))
                    
            return edges

        # Storing the values of the dual solutions:
        dualSols = {}
        for c in self.cons:
            i = int(c.name.split("_")[-1].strip())
            dualSols[i] = self.model.getDualsolLinear(c)

        # Model for the sub-problem:
        subMIP = Model("VRP-Sub")
        subMIP.setPresolve(SCIP_PARAMSETTING.OFF)
        subMIP.setMinimize

        subMIP.setRealParam("limits/time", timeLimit)
        
        # Binary variables x_ij indicating whether the vehicle
        # traverses edge (i, j)
        x = {}
        for i in self.data.nodes:
            for j in self.data.nodes:
                if i != j:
                    x[i, j] = subMIP.addVar(vtype="B", obj=self.data.costs[i, j] - (dualSols[i] if i in self.clientNodes else 0), name="x_%d_%d" % (i, j))

        # Non negative variables u_i indicating the demand served up to node i:
        u = {}
        for i in self.data.nodes:
            u[i] = subMIP.addVar(vtype="C", lb=0, ub=self.data.cap, obj=0.0, name="u_%d" % i)

        for j in self.clientNodes:
            subMIP.addCons(quicksum(x[i, j] for i in self.data.nodes if i != j) <= 1)

        for h in self.clientNodes:
            subMIP.addCons(quicksum(x[i, h] for i in self.data.nodes if i != h) ==
                           quicksum(x[h, i] for i in self.data.nodes if i != h))

        for i in self.data.nodes:
            for j in self.clientNodes:
                if i != j:
                    subMIP.addCons(u[j] >= u[i] + self.data.demands[j]*x[i, j] - self.data.cap*(1 - x[i, j]))

        subMIP.addCons(quicksum(x[self.data.depot, j] for j in self.clientNodes) <= 1)

        subMIP.hideOutput()
        subMIP.optimize()

        mipSol = subMIP.getBestSol()
        obj = subMIP.getSolObjVal(mipSol)
        
        pattern = getPatternFromSolution(subMIP)
        
        return obj, pattern
Exemplo n.º 3
0
def test_circle():
    points =[
            (2.802686, 1.398947),
            (4.719673, 4.792101),
            (1.407758, 7.769566),
            (2.253320, 2.373641),
            (8.583144, 9.769102),
            (3.022725, 5.470335),
            (5.791380, 1.214782),
            (8.304504, 8.196392),
            (9.812677, 5.284600),
            (9.445761, 9.541600)]

    m = Model()
    a = m.addVar('a', lb=None)
    b = m.addVar('b', ub=None)
    r = m.addVar('r')

    # minimize radius
    m.setObjective(r, 'minimize')

    for i,p in enumerate(points):
        # NOTE: SCIP will not identify this as SOC constraints!
        m.addCons( sqrt((a - p[0])**2 + (b - p[1])**2) <= r, name = 'point_%d'%i)

    m.optimize()

    bestsol = m.getBestSol()
    assert abs(m.getSolVal(bestsol, r) - 5.2543) < 1.0e-3
    assert abs(m.getSolVal(bestsol, a) - 6.1242) < 1.0e-3
    assert abs(m.getSolVal(bestsol, b) - 5.4702) < 1.0e-3
Exemplo n.º 4
0
def test_circle():
    points = [(2.802686, 1.398947), (4.719673, 4.792101), (1.407758, 7.769566),
              (2.253320, 2.373641), (8.583144, 9.769102), (3.022725, 5.470335),
              (5.791380, 1.214782), (8.304504, 8.196392), (9.812677, 5.284600),
              (9.445761, 9.541600)]

    m = Model()
    a = m.addVar('a', lb=None)
    b = m.addVar('b', ub=None)
    r = m.addVar('r')

    # minimize radius
    m.setObjective(r, 'minimize')

    for i, p in enumerate(points):
        # NOTE: SCIP will not identify this as SOC constraints!
        m.addCons(sqrt((a - p[0])**2 + (b - p[1])**2) <= r,
                  name='point_%d' % i)

    m.optimize()

    bestsol = m.getBestSol()
    assert abs(m.getSolVal(bestsol, r) - 5.2543) < 1.0e-3
    assert abs(m.getSolVal(bestsol, a) - 6.1230) < 1.0e-3
    assert abs(m.getSolVal(bestsol, b) - 5.4713) < 1.0e-3
Exemplo n.º 5
0
def test_model():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    assert x.getObj() == 1.0
    assert y.getObj() == 2.0

    s.setObjective(4.0 * y + 10.5, clear=False)
    assert x.getObj() == 1.0
    assert y.getObj() == 4.0
    assert s.getObjoffset() == 10.5

    # add some constraint
    c = s.addCons(x + 2 * y >= 1.0)
    s.chgLhs(c, 5.0)
    s.chgRhs(c, 6.0)

    assert s.getLhs(c) == 5.0
    assert s.getRhs(c) == 6.0

    badsolution = s.createSol()
    s.setSolVal(badsolution, x, 2.0)
    s.setSolVal(badsolution, y, 2.0)
    assert s.getSlack(c, badsolution) == 0.0
    assert s.getSlack(c, badsolution, 'lhs') == 1.0
    assert s.getSlack(c, badsolution, 'rhs') == 0.0
    assert s.getActivity(c, badsolution) == 6.0
    s.freeSol(badsolution)

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
    assert s.getSlack(c, solution) == 0.0
    assert s.getSlack(c, solution, 'lhs') == 0.0
    assert s.getSlack(c, solution, 'rhs') == 1.0
    assert s.getActivity(c, solution) == 5.0

    s.freeProb()
    s = Model()
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)
    c = s.addCons(x + 2 * y <= 1.0)
    s.setMaximize()

    s.delCons(c)

    s.optimize()

    assert s.getStatus() == 'unbounded'
Exemplo n.º 6
0
def test_solution_getbest():
    m = Model()

    x = m.addVar("x", lb=0, ub=2, obj=-1)
    y = m.addVar("y", lb=0, ub=4, obj=0)
    m.addCons(x * x <= y)

    m.optimize()

    sol = m.getBestSol()
    assert round(sol[x]) == 2.0
    assert round(sol[y]) == 4.0
    print(sol)  # prints the solution in the transformed space

    m.freeTransform()
    sol = m.getBestSol()
    assert round(sol[x]) == 2.0
    assert round(sol[y]) == 4.0
    print(sol)  # prints the solution in the original space
Exemplo n.º 7
0
def test_knapsack():
    # create solver instance
    s = Model("Knapsack")
    s.hideOutput()

    # setting the objective sense to maximise
    s.setMaximize()

    # item weights
    weights = [4, 2, 6, 3, 7, 5]
    # item costs
    costs = [7, 2, 5, 4, 3, 4]

    assert len(weights) == len(costs)

    # knapsack size
    knapsackSize = 15

    # adding the knapsack variables
    knapsackVars = []
    varNames = []
    varBaseName = "Item"
    for i in range(len(weights)):
        varNames.append(varBaseName + "_" + str(i))
        knapsackVars.append(s.addVar(varNames[i], vtype='I', obj=costs[i], ub=1.0))


    # adding a linear constraint for the knapsack constraint
    coeffs = {knapsackVars[i]: weights[i] for i in range(len(weights))}
    s.addCons(coeffs, lhs=None, rhs=knapsackSize)

    # solve problem
    s.optimize()

    s.printStatistics()

    # retrieving the best solution
    solution = s.getBestSol()

    # print solution
    varSolutions = []
    for i in range(len(weights)):
        solValue = round(s.getVal(knapsackVars[i], solution))
        varSolutions.append(solValue)
        if solValue > 0:
            print (varNames[i], "Times Selected:", solValue)
            print ("\tIncluded Weight:", weights[i]*solValue, "\tItem Cost:", costs[i]*solValue)

        s.releaseVar(knapsackVars[i])

    includedWeight = sum([weights[i]*varSolutions[i] for i in range(len(weights))])
    assert includedWeight > 0 and includedWeight <= knapsackSize
Exemplo n.º 8
0
def test_heur():
    s = Model()
    heuristic = MyHeur()
    s.includeHeur(heuristic,
                  "PyHeur",
                  "custom heuristic implemented in python",
                  "Y",
                  timingmask=SCIP_HEURTIMING.BEFORENODE)
    s.setPresolve(SCIP_PARAMSETTING.OFF)
    x = s.addVar("x", obj=1.0)
    y = s.addVar("y", obj=2.0)
    s.addCons(x + 2 * y >= 5)
    s.optimize()
    sol = s.getBestSol()
    assert sol is not None
    assert round(sol[x]) == 5.0
    assert round(sol[y]) == 0.0
Exemplo n.º 9
0
def test_lp():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    assert x.getObj() == 1.0
    assert y.getObj() == 2.0

    s.setObjective(4.0 * y, clear=False)
    assert x.getObj() == 1.0
    assert y.getObj() == 4.0

    # add some constraint
    c = s.addCons(x + 2 * y >= 1.0)
    s.chgLhs(c, 5.0)
    s.chgRhs(c, 5.0)

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0

    s.freeProb()
    s = Model()
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)
    c = s.addCons(x + 2 * y <= 1.0)
    s.setMaximize()

    s.delCons(c)

    s.optimize()

    assert s.getStatus() == 'unbounded'
Exemplo n.º 10
0
def test_lp():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    # add some constraint
    s.addCons(x + 2 * y >= 5.0)

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
Exemplo n.º 11
0
def test_lp():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    # add some constraint
    s.addCons(x + 2*y >= 5.0)

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
Exemplo n.º 12
0
def test_heur():
    # create solver instance
    s = Model()
    heuristic = MyHeur()
    s.includeHeur(heuristic, "PyHeur", "custom heuristic implemented in python", "Y", timingmask=SCIP_HEURTIMING.BEFORENODE)
    s.setPresolve(SCIP_PARAMSETTING.OFF)

    # add some variables
    x = s.addVar("x", obj=1.0)
    y = s.addVar("y", obj=2.0)

    # add some constraint
    s.addCons(x + 2*y >= 5)

    # solve problem
    s.optimize()

    # print solution
    sol = s.getBestSol()
    assert sol != None
    assert round(sol[x]) == 5.0
    assert round(sol[y]) == 0.0
Exemplo n.º 13
0
def test_simplelp():
    # create solver instance
    s = Model()

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    # add some constraint
    coeffs = {x: 1.0, y: 2.0}
    s.addCons(coeffs, 5.0)

    # solve problem
    s.optimize()

    # retrieving the best solution
    solution = s.getBestSol()

    # print solution
    assert round(s.getVal(x, solution)) == 5.0
    assert round(s.getVal(y, solution)) == 0.0

    s.free()
Exemplo n.º 14
0
def conv_model(conf):
	model = Model("Example")  
	model.hideOutput()
	dram_rd_bw = 20 
	dram_wr_bw = 20
	adj = np.array([[0,1,0,0,1,1],
				[1,0,0,0,0,0],
			    [1,1,1,1,0,0],
			    [1,1,1,1,0,0],
			    [0,1,0,0,0,0],
			    [1,1,1,1,1,1]])

	x = {}
	for i in range(1, 7):
		for j in range(1, 7):
			x[i, j] = model.addVar(vtype="INTEGER", name="x(%s,%s)"%(i,j))

	C_comp = model.addVar("C_comp", vtype="INTEGER")
	C_psum = model.addVar("C_psum", vtype="INTEGER")
	C_act = model.addVar("C_act", vtype="INTEGER")
	C_rd = model.addVar("C_rd", vtype="INTEGER")
	C_rw = model.addVar("C_rw", vtype="INTEGER")
	C_exe = model.addVar("C_exe", vtype="INTEGER")
	X = model.addVar("X", vtype="INTEGER")
	L = model.addVar("L", vtype="INTEGER")
	T = model.addVar("T", vtype="INTEGER")



	for i in range(1, 7):
		for j in range(1, 7):
			model.addCons(x[i, j] >= 1) 

	for i in range(1, 7):
		for j in range(1, 7):
			if adj[j - 1, i - 1] == 0:
				model.addCons(x[i, j] == 1) 

	model.addCons(x[1, 1] * x[2, 1] * x[3, 1] * x[4, 1] * x[5, 1] * x[6, 1] <= conf['D1']) 
	model.addCons(x[1, 2] * x[2, 2] * x[3, 2] * x[4, 2] * x[5, 2] * x[6, 2] <= conf['D2']) 
	model.addCons(x[1, 3] * x[2, 3] * x[3, 3] * x[4, 3] * x[5, 3] * x[6, 3] <= conf['D3']) 

	model.addCons(x[1, 1] * x[1, 2] * x[1, 3] * x[1, 4] * x[1, 5] * x[1, 6] >= conf['M']) 
	model.addCons(x[2, 1] * x[2, 2] * x[2, 3] * x[2, 4] * x[2, 5] * x[2, 6] >= conf['N'])
	model.addCons(x[3, 1] * x[3, 2] * x[3, 3] * x[3, 4] * x[3, 5] * x[3, 6] >= conf['W'])
	model.addCons(x[4, 1] * x[4, 2] * x[4, 3] * x[4, 4] * x[4, 5] * x[4, 6] >= conf['H'])
	model.addCons(x[5, 1] * x[5, 2] * x[5, 3] * x[5, 4] * x[5, 5] * x[5, 6] >= conf['I'])
	model.addCons(x[6, 1] * x[6, 2] * x[6, 3] * x[6, 4] * x[6, 5] * x[6, 6] >= conf['J'])

	model.addCons(x[1, 4] * x[2, 4] * x[3, 4] * x[4, 4] * x[5, 4] * x[6, 4] <= X)
	model.addCons(x[1, 5] * x[2, 5] * x[3, 5] * x[4, 5] * x[5, 5] * x[6, 5] <= L)
	model.addCons(x[1, 6] * x[2, 6] * x[3, 6] * x[4, 6] * x[5, 6] * x[6, 6] <= T)
	model.addCons( X * (L * T + conf['D1'] + 6) <= C_comp)


	model.addCons(conf['N_ACT'] * X * L <= C_act)

	model.addCons(conf['N_PSUM']  * conf['D3'] *  X <= C_psum)

	model.addCons((C_psum + C_act) / dram_rd_bw <= C_rd)

	#model.addCons(C_psum / dram_wr_bw <= C_rw)

	model.addCons(C_comp <= C_exe)
	model.addCons(C_act <= C_exe)
	model.addCons(C_psum <= C_exe)
	model.addCons(C_rd <= C_exe)
	#model.addCons(C_rw <= C_exe)

	model.setObjective(C_exe)
	model.optimize()
	sol = model.getBestSol()

	out = np.zeros([6, 6], dtype=int)
	for i in range(1, 7):
		for j in range(1, 7):
			out[i-1, j-1] = sol[x[i, j]]
	
	return out
Exemplo n.º 15
0
def test_model():
    # create solver instance
    s = Model()

    # test parameter methods
    pric = s.getParam('lp/pricing')
    s.setParam('lp/pricing', 'q')
    assert 'q' == s.getParam('lp/pricing')
    s.setParam('lp/pricing', pric)
    s.setParam('visual/vbcfilename', 'vbcfile')
    assert 'vbcfile' == s.getParam('visual/vbcfilename')

    assert 'lp/pricing' in s.getParams()
    s.setParams({'visual/vbcfilename': '-'})
    assert '-' == s.getParam('visual/vbcfilename')

    # add some variables
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)

    assert x.getObj() == 1.0
    assert y.getObj() == 2.0

    s.setObjective(4.0 * y + 10.5, clear=False)
    assert x.getObj() == 1.0
    assert y.getObj() == 4.0
    assert s.getObjoffset() == 10.5

    # add some constraint
    c = s.addCons(x + 2 * y >= 1.0)
    assert c.isLinear()
    s.chgLhs(c, 5.0)
    s.chgRhs(c, 6.0)

    assert s.getLhs(c) == 5.0
    assert s.getRhs(c) == 6.0

    # solve problem
    s.optimize()

    solution = s.getBestSol()

    # print solution
    assert (s.getVal(x) == s.getSolVal(solution, x))
    assert (s.getVal(y) == s.getSolVal(solution, y))
    assert round(s.getVal(x)) == 5.0
    assert round(s.getVal(y)) == 0.0
    assert s.getSlack(c, solution) == 0.0
    assert s.getSlack(c, solution, 'lhs') == 0.0
    assert s.getSlack(c, solution, 'rhs') == 1.0
    assert s.getActivity(c, solution) == 5.0

    # check expression evaluations
    expr = x * x + 2 * x * y + y * y
    expr2 = x + 1
    assert s.getVal(expr) == s.getSolVal(solution, expr)
    assert s.getVal(expr2) == s.getSolVal(solution, expr2)
    assert round(s.getVal(expr)) == 25.0
    assert round(s.getVal(expr2)) == 6.0

    s.writeProblem('model')
    s.writeProblem('model.lp')

    s.freeProb()
    s = Model()
    x = s.addVar("x", vtype='C', obj=1.0)
    y = s.addVar("y", vtype='C', obj=2.0)
    c = s.addCons(x + 2 * y <= 1.0)
    s.setMaximize()

    s.delCons(c)

    s.optimize()

    assert s.getStatus() == 'unbounded'
Exemplo n.º 16
0
def tsp_solver(c, customers, vehicle_tours):
    def addcut(cut_edges):
        G = networkx.Graph()
        G.add_edges_from(cut_edges)
        Components = list(networkx.connected_components(G))
        if len(Components) == 1:
            return False
        model.freeTransform()
        for S in Components:
            model.addCons(
                quicksum(x[i, j] for i in S for j in S) <= len(S) - 1)

        return True

    # Add the depot on each vehicle
    vehicle_tours = {k: vehicle_tours[k] + [0] for k in vehicle_tours.keys()}
    final_obj = 0
    final_tours = []
    for key, value in vehicle_tours.iteritems():
        v_customers = value
        model = Model("vrp_tsp")
        #model.hideOutput()
        x = {}

        for i in v_customers:
            for j in v_customers:
                # vehicle moves from customer i to customer j
                x[i, j] = model.addVar(vtype="B", name="x(%s,%s)" % (i, j))

        for i in v_customers:
            # Constraint: every customer can only be visited once
            # (or, every node must be connected and connect to another node)
            model.addCons(quicksum(x[i, j] for j in v_customers) == 1)
            model.addCons(quicksum(x[j, i] for j in v_customers) == 1)

            for j in v_customers:
                if i == j:
                    # Constraint: a node cannot conect to itself
                    model.addCons(x[i, j] == 0)

        # Objective function: minimize total distance of the tour
        model.setObjective(
            quicksum(x[i, j] * c[(i, j)] for i in v_customers
                     for j in v_customers), "minimize")

        EPS = 1.e-6
        isMIP = False
        while True:
            model.optimize()
            edges = []
            for (i, j) in x:
                if model.getVal(x[i, j]) > EPS:
                    edges.append((i, j))

            if addcut(edges) == False:
                if isMIP:  # integer variables, components connected: solution found
                    break
                model.freeTransform()
                for (
                        i, j
                ) in x:  # all components connected, switch to integer model
                    model.chgVarType(x[i, j], "B")
                    isMIP = True

        # model.optimize()
        best_sol = model.getBestSol()
        sub_tour = []

        # Build the graph path
        # Retrieve the last node of the graph, i.e., the last one connecting to the depot
        last_node = [n for n in edges if n[1] == 0][0][0]
        G = networkx.Graph()
        G.add_edges_from(edges)
        path = list(networkx.all_simple_paths(G, source=0, target=last_node))
        path.sort(reverse=True, key=lambda u: len(u))

        if len(path) > 0:
            path = path[0][1:]
        else:
            path = path[1:]

        obj = model.getSolObjVal(best_sol)
        final_obj += obj
        final_tours.append([customers[i] for i in path])

        # print("Customers visited by vehicle %s: %s" % (key, value))
        # print("Objective cost for vehicle %s: %s" % (key, obj))
        # print("Edges visited by vehicle %s: %s" % (key, edges))
        # print("Path visited by vehicle %s: %s" % (key, path))
    return final_obj, final_tours
Exemplo n.º 17
0
    def calc_damage(self):
        data = self.data

        # 各サブステ x とダメージ倍率 f(x) の関係式を2次関数で近似。パラメータa,b,cは要調整。
        # 係数: 	# f(x) = ax^2 + bx + c
        # scipを使う関係上、連続な関数を使用せざるを得ない。下記参照リンクの計算式の床関数もガン無視。なので多少誤差が出る(コンマ%くらい?)。
        # reference: http://allaganstudies.akhmorning.com/guide/damage/
        self.lmd_fdh = lambda x: 4.1667e-5 * x + 1

        self.lmd_fch = lambda x: (3.6732e-9 * x + 2.7271e-5) * x + 0.02 + 1

        self.lmd_fdt = lambda x: 3.9394e-05 * x + 1

        self.lmd_fss_gdc = lambda x: (2.13073e-9 * x + 3.81069e-5) * x + 1
        self.lmd_fss_dot_aa = lambda x: 3.9394e-05 * x + 1

        self.lmd_fss =  lambda x: self.rate_ss * self.lmd_fss_gdc(x) \
              + (self.rate_aa+self.rate_dot) * self.lmd_fss_dot_aa(x) \
              + (1-(self.rate_ss+self.rate_aa+self.rate_dot)) * 1

        self.lmd_ftn = lambda x: 3.0303e-5 * x + 1

        self.lmd_fpi = lambda x: 1  # 信仰値はダメージ倍率に影響なし

        self.expr_min = lambda x, y: (x + y) / 2 - abs(
            x - y) / 2  # min関数をscipが読める形に置き換える。
        # サブステの装備内での上限値を考慮するために必要。

        model = Model("calc_damage_multiplier")
        objvar = model.addVar("objvar", lb=1.0, ub=None, vtype="C")
        model.setObjective(objvar, "maximize")

        #### def variables for SCIP ####
        _is_chosen = {}
        # ex_m = {}
        ex_m_dh = {}
        ex_m_ch = {}
        ex_m_dt = {}
        ex_m_ss = {}
        ex_m_tn = {}
        ex_m_pi = {}
        # mg_m = {}
        mg_m_dh = {}
        mg_m_ch = {}
        mg_m_dt = {}
        mg_m_ss = {}
        mg_m_tn = {}
        mg_m_pi = {}
        # subst = {}
        dh = {}
        ch = {}
        dt = {}
        ss = {}
        tn = {}
        pi = {}

        for eq in data:
            # 各装備に対するエクス装着数
            ex_m_dh[eq] = model.addVar(name="ex_m_dh_" + eq, vtype="I", lb=0)
            ex_m_ch[eq] = model.addVar(name="ex_m_ch_" + eq, vtype="I", lb=0)
            ex_m_dt[eq] = model.addVar(name="ex_m_dt_" + eq, vtype="I", lb=0)
            ex_m_ss[eq] = model.addVar(name="ex_m_ss_" + eq, vtype="I", lb=0)
            ex_m_tn[eq] = model.addVar(name="ex_m_tn_" + eq, vtype="I", lb=0)
            ex_m_pi[eq] = model.addVar(name="ex_m_pi_" + eq, vtype="I", lb=0)
            # 制約条件:1装備当たりのエクス装着数が、装着可能な個数の上限を超えない
            model.addCons(
                ex_m_dh[eq] + ex_m_ch[eq] + ex_m_dt[eq] + ex_m_ss[eq] +
                ex_m_tn[eq] + ex_m_pi[eq] <= data[eq]["ex_m"])

            # 各装備に対するメガ装着数
            mg_m_dh[eq] = model.addVar(name="mg_m_dh_" + eq, vtype="I", lb=0)
            mg_m_ch[eq] = model.addVar(name="mg_m_ch_" + eq, vtype="I", lb=0)
            mg_m_dt[eq] = model.addVar(name="mg_m_dt_" + eq, vtype="I", lb=0)
            mg_m_ss[eq] = model.addVar(name="mg_m_ss_" + eq, vtype="I", lb=0)
            mg_m_tn[eq] = model.addVar(name="mg_m_tn_" + eq, vtype="I", lb=0)
            mg_m_pi[eq] = model.addVar(name="mg_m_pi_" + eq, vtype="I", lb=0)
            # 制約条件:1装備当たりのメガ装着数が、装着可能な個数の上限を超えない
            model.addCons(
                mg_m_dh[eq] + mg_m_ch[eq] + mg_m_dt[eq] + mg_m_ss[eq] +
                mg_m_tn[eq] + mg_m_pi[eq] <= data[eq]["mg_m"])

            ######## どちらの装備を選択したほうがよいかを変数にして解いてみる。
            _is_chosen[eq] = []
            if len(data[eq]["dh"]) == 1:
                _is_chosen[eq].append(
                    model.addVar(name=eq + "_0", vtype="B", lb=0, ub=1))
                model.addCons(_is_chosen[eq][0] <= 1)
            else:
                _is_chosen[eq].append(
                    model.addVar(name=eq + "_0", vtype="B", lb=0,
                                 ub=1))  # 要修正。3以上の時。
                _is_chosen[eq].append(
                    model.addVar(name=eq + "_1", vtype="B", lb=0, ub=1))
                model.addCons(_is_chosen[eq][0] + _is_chosen[eq][1] <= 1)
                # model.addCons(quicksum(_is_chosen[eq][i] for i in range(len(_is_chosen[eq]))) <= 1)
            ########

            # tmp_dh = 60*ex_m_dh[eq] + 20*mg_m_dh[eq] + data[eq]["dh"][0]
            # tmp_ch = 60*ex_m_ch[eq] + 20*mg_m_ch[eq] + data[eq]["ch"][0]
            # tmp_dt = 60*ex_m_dt[eq] + 20*mg_m_dt[eq] + data[eq]["dt"][0]
            # tmp_ss = 60*ex_m_ss[eq] + 20*mg_m_ss[eq] + data[eq]["ss"][0]

            ########
            tmp_dh = 60*ex_m_dh[eq] + 20*mg_m_dh[eq] \
              + quicksum( data[eq]["dh"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )
            tmp_ch = 60*ex_m_ch[eq] + 20*mg_m_ch[eq] \
              + quicksum( data[eq]["ch"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )
            tmp_dt = 60*ex_m_dt[eq] + 20*mg_m_dt[eq] \
              + quicksum( data[eq]["dt"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )
            tmp_ss = 60*ex_m_ss[eq] + 20*mg_m_ss[eq] \
              + quicksum( data[eq]["ss"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )
            tmp_tn = 60*ex_m_tn[eq] + 20*mg_m_tn[eq] \
              + quicksum( data[eq]["tn"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )
            tmp_pi = 60*ex_m_pi[eq] + 20*mg_m_pi[eq] \
              + quicksum( data[eq]["pi"][i][0]*_is_chosen[eq][i] for i in range(len(_is_chosen[eq])) )

            # マテリアにより上昇するサブステが、サブステ上限値を超えないようにする
            dh[eq] = self.expr_min(tmp_dh, data[eq]["dh"][0][1])
            ch[eq] = self.expr_min(tmp_ch, data[eq]["ch"][0][1])
            dt[eq] = self.expr_min(tmp_dt, data[eq]["dt"][0][1])
            ss[eq] = self.expr_min(tmp_ss, data[eq]["ss"][0][1])
            tn[eq] = self.expr_min(tmp_tn, data[eq]["tn"][0][1])
            pi[eq] = self.expr_min(tmp_pi, data[eq]["pi"][0][1])

        dh_sum = quicksum(dh[eq] for eq in data)
        ch_sum = quicksum(ch[eq] for eq in data)
        dt_sum = quicksum(dt[eq] for eq in data)
        ss_sum = quicksum(ss[eq] for eq in data)
        tn_sum = quicksum(tn[eq] for eq in data)
        pi_sum = quicksum(pi[eq] for eq in data)

        #### damage efficiency in each substatuses ####
        fdh = self.lmd_fdh(dh_sum)
        fch = self.lmd_fch(ch_sum)
        fdt = self.lmd_fdt(dt_sum)
        fss = self.lmd_fss(ss_sum)
        ftn = self.lmd_ftn(tn_sum)
        fpi = self.lmd_fpi(pi_sum)
        model.addCons(objvar <= fdh * fch * fdt * fss * ftn *
                      fpi)  # 制約条件(目的関数):ダメージ効率を最大化する

        #### SS調整 ####
        model.addCons(ss_sum >= self.ss_lower)  # 制約条件: SSが少なくとも X 以上

        ## 信仰調整 ##
        model.addCons(pi_sum >= self.pi_lower)  # 制約条件: 信仰が少なくとも X 以上

        #### optimize ####
        model.optimize()
        sol = model.getBestSol()

        #### show result ####
        ## 注意:	addVar()で vtype="I" や "B" として宣言した変数(整数変数、バイナリ変数)は、
        ##			解を取得するために getVal() を呼ぶと、値が float 型で返ってくるので気を付けること。
        num_eq = {}
        result = {}
        for eq in data:
            ########
            print(_is_chosen[eq])
            num_eq[eq] = [round(model.getVal(v))
                          for v in _is_chosen[eq]].index(1)
            ########
            result[eq] = {}
            result[eq]["dh"] = (
                min(
                    60 * round(model.getVal(ex_m_dh[eq])) +
                    20 * round(model.getVal(mg_m_dh[eq])) +
                    data[eq]["dh"][num_eq[eq]][0],
                    data[eq]["dh"][num_eq[eq]][1]),
                data[eq]["dh"][num_eq[eq]][1],
            )
            result[eq]["ch"] = (
                min(
                    60 * round(model.getVal(ex_m_ch[eq])) +
                    20 * round(model.getVal(mg_m_ch[eq])) +
                    data[eq]["ch"][num_eq[eq]][0],
                    data[eq]["ch"][num_eq[eq]][1]),
                data[eq]["ch"][num_eq[eq]][1],
            )
            result[eq]["dt"] = (
                min(
                    60 * round(model.getVal(ex_m_dt[eq])) +
                    20 * round(model.getVal(mg_m_dt[eq])) +
                    data[eq]["dt"][num_eq[eq]][0],
                    data[eq]["dt"][num_eq[eq]][1]),
                data[eq]["dt"][num_eq[eq]][1],
            )
            result[eq]["ss"] = (
                min(
                    60 * round(model.getVal(ex_m_ss[eq])) +
                    20 * round(model.getVal(mg_m_ss[eq])) +
                    data[eq]["ss"][num_eq[eq]][0],
                    data[eq]["ss"][num_eq[eq]][1]),
                data[eq]["ss"][num_eq[eq]][1],
            )
            result[eq]["tn"] = (
                min(
                    60 * round(model.getVal(ex_m_tn[eq])) +
                    20 * round(model.getVal(mg_m_tn[eq])) +
                    data[eq]["tn"][num_eq[eq]][0],
                    data[eq]["tn"][num_eq[eq]][1]),
                data[eq]["tn"][num_eq[eq]][1],
            )
            result[eq]["pi"] = (
                min(
                    60 * round(model.getVal(ex_m_pi[eq])) +
                    20 * round(model.getVal(mg_m_pi[eq])) +
                    data[eq]["pi"][num_eq[eq]][0],
                    data[eq]["pi"][num_eq[eq]][1]),
                data[eq]["pi"][num_eq[eq]][1],
            )

        # 装備品のみのサブステ
        equip_dh = sum([data[eq]["dh"][num_eq[eq]][0] for eq in data])
        equip_ch = sum([data[eq]["ch"][num_eq[eq]][0] for eq in data])
        equip_dt = sum([data[eq]["dt"][num_eq[eq]][0] for eq in data])
        equip_ss = sum([data[eq]["ss"][num_eq[eq]][0] for eq in data])
        equip_tn = sum([data[eq]["tn"][num_eq[eq]][0] for eq in data])
        equip_pi = sum([data[eq]["pi"][num_eq[eq]][0] for eq in data])
        subst_init = equip_dh + equip_ch + equip_dt + equip_ss + equip_tn + equip_pi

        # マテリアのみのサブステ
        subst_materia_dh = sum([result[eq]["dh"][0]
                                for eq in result]) - equip_dh
        subst_materia_ch = sum([result[eq]["ch"][0]
                                for eq in result]) - equip_ch
        subst_materia_dt = sum([result[eq]["dt"][0]
                                for eq in result]) - equip_dt
        subst_materia_ss = sum([result[eq]["ss"][0]
                                for eq in result]) - equip_ss
        subst_materia_tn = sum([result[eq]["tn"][0]
                                for eq in result]) - equip_tn
        subst_materia_pi = sum([result[eq]["pi"][0]
                                for eq in result]) - equip_pi
        subst_materia = subst_materia_dh + subst_materia_ch + subst_materia_dt + subst_materia_ss + subst_materia_tn + subst_materia_pi

        fdh_sol = self.lmd_fdh(equip_dh + subst_materia_dh)
        fch_sol = self.lmd_fch(equip_ch + subst_materia_ch)
        fdt_sol = self.lmd_fdt(equip_dt + subst_materia_dt)
        fss_sol = self.lmd_fss(equip_ss + subst_materia_ss)
        fss_dot_aa_sol = self.lmd_fss_dot_aa(equip_ss + subst_materia_ss)
        fss_gdc_sol = self.lmd_fss_gdc(equip_ss + subst_materia_ss)
        ftn_sol = self.lmd_ftn(equip_tn + subst_materia_tn)
        fpi_sol = self.lmd_fpi(equip_pi + subst_materia_pi)

        print(sol)
        print("Optimal value:", model.getObjVal())
        print("")
        print("")
        print("            エクス              |メガ              | サブステ")
        print(
            "            dh ch dt ss tn pi|dh ch dt ss tn pi|     dh           ch           dt           ss           tn           pi"
        )
        for eq in data:
            ex_m_dh_num = round(model.getVal(ex_m_dh[eq]))
            ex_m_ch_num = round(model.getVal(ex_m_ch[eq]))
            ex_m_dt_num = round(model.getVal(ex_m_dt[eq]))
            ex_m_ss_num = round(model.getVal(ex_m_ss[eq]))
            ex_m_tn_num = round(model.getVal(ex_m_tn[eq]))
            ex_m_pi_num = round(model.getVal(ex_m_pi[eq]))

            mg_m_dh_num = round(model.getVal(mg_m_dh[eq]))
            mg_m_ch_num = round(model.getVal(mg_m_ch[eq]))
            mg_m_dt_num = round(model.getVal(mg_m_dt[eq]))
            mg_m_ss_num = round(model.getVal(mg_m_ss[eq]))
            mg_m_tn_num = round(model.getVal(mg_m_tn[eq]))
            mg_m_pi_num = round(model.getVal(mg_m_pi[eq]))

            tmp_form = lambda x: str(x) if x > 0 else "-"

            string = "{0:10s}: {1}  {2}  {3}  {4}  {5}  {6} |{7}  {8}  {9}  {10}  {11}  {12} |{13:4d}  +{14:3d}   {15:4d}  +{16:3d}   {17:4d}  +{18:3d}   {19:4d}  +{20:3d}   {21:4d}  +{22:3d}   {23:4d}  +{24:3d}"
            print(
                string.format(
                    eq,
                    tmp_form(ex_m_dh_num),
                    tmp_form(ex_m_ch_num),
                    tmp_form(ex_m_dt_num),
                    tmp_form(ex_m_ss_num),
                    tmp_form(ex_m_tn_num),
                    tmp_form(ex_m_pi_num),
                    tmp_form(mg_m_dh_num),
                    tmp_form(mg_m_ch_num),
                    tmp_form(mg_m_dt_num),
                    tmp_form(mg_m_ss_num),
                    tmp_form(mg_m_tn_num),
                    tmp_form(mg_m_pi_num),
                    data[eq]["dh"][num_eq[eq]][0],
                    round(result[eq]["dh"][0]) - data[eq]["dh"][num_eq[eq]][0],
                    data[eq]["ch"][num_eq[eq]][0],
                    round(result[eq]["ch"][0]) - data[eq]["ch"][num_eq[eq]][0],
                    data[eq]["dt"][num_eq[eq]][0],
                    round(result[eq]["dt"][0]) - data[eq]["dt"][num_eq[eq]][0],
                    data[eq]["ss"][num_eq[eq]][0],
                    round(result[eq]["ss"][0]) - data[eq]["ss"][num_eq[eq]][0],
                    data[eq]["tn"][num_eq[eq]][0],
                    round(result[eq]["tn"][0]) - data[eq]["tn"][num_eq[eq]][0],
                    data[eq]["pi"][num_eq[eq]][0],
                    round(result[eq]["pi"][0]) - data[eq]["pi"][num_eq[eq]][0],
                ))

        print("")
        print(num_eq)
        print("")
        print("サブステ 装備	: {0:4.0f}".format(subst_init))
        print("サブステ マテリア	: {0:4.0f}".format(subst_materia))
        print("サブステ 総数	: {0:4.0f}".format(subst_init + subst_materia))
        print("")
        print("                       Equip  Materia")
        print("dh(ダイレクトヒット)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_dh + subst_materia_dh, equip_dh, subst_materia_dh))
        print("ch(クリティカルヒット)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_ch + subst_materia_ch, equip_ch, subst_materia_ch))
        print("dt(意思力)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_dt + subst_materia_dt, equip_dt, subst_materia_dt))
        print("ss(スキルスピード)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_ss + subst_materia_ss, equip_ss, subst_materia_ss))
        print("tn(不屈)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_tn + subst_materia_tn, equip_tn, subst_materia_tn))
        print("pi(信仰)	: {0:4.0f} ({1:4.0f} +  {2:4.0f})".format(
            equip_pi + subst_materia_pi, equip_pi, subst_materia_pi))
        print("")
        self.show_eff(fdh_sol, fch_sol, fdt_sol, fss_sol, fss_gdc_sol,
                      fss_dot_aa_sol, ftn_sol, fpi_sol)

        # memo
        # 解に対する変数の値が知りたい場合
        # print(sol[dh])
        # print(model.getSolVal(sol, dh))
        # print(model.getVal(dh))

        # 解に対する式の値が知りたい場合
        # print(model.getSolVal(sol, fdh))
        # print(model.getVal(fdh))

        print("******** 厳密解 ********")
        rtn = self.calc_exact_dmg_multiplier(equip_dh + subst_materia_dh,
                                             equip_ch + subst_materia_ch,
                                             equip_dt + subst_materia_dt,
                                             equip_ss + subst_materia_ss,
                                             equip_tn + subst_materia_tn,
                                             equip_pi + subst_materia_pi)
        self.show_eff(*rtn)
Exemplo n.º 18
0
def scip_solver_3(customers, customer_count, vehicle_count, vehicle_capacity):
    """
    #### Notations #### 
    G = Symmetric Graph; G= (T, A) 
    T = Set of Nodes; T = [N ∪ {0, n+1}] 
    A = Set of Arcs linking any pair of nodes, (i.j) ∈ A
    V = Total Number of Vehicles; v = {1,2...V} 
    y[i,j] = Cost of travel from node i to node j 
    d[i] = Delivery requests of node i, i = 1, ..., N
    p[i] = Pickup requests of node i, i = 1, ..., N (NOT TO BE USED IN THIS PROBLEM)
    Q = Capacity of Vehicle 
    TL = Maximum Route Length for any Vehicle v

    #### Decision Variables #### 
    D[i,v] = The load remaining to be delivered by vehicle v when departing from node i
    P[i,v] = The cumulative load picked by vehicle v when departing from node i (NOT TO BE USED IN THIS PROBLEM)
    X[v,i,j] = 1 if vehicle travels from i to j, 0 otherwise

    P[i], d[i], Q, y[i,j] are non-negative integers 

    """

    model = Model("vrp")
    # model.hideOutput()
    model.setMinimize()

    model.setRealParam("limits/gap", 0.03)
    model.setRealParam("limits/absgap", 0.03)
    model.setRealParam("limits/time", 600)  # Time limit in seconds

    T = customers
    V = vehicle_count
    Q = vehicle_capacity
    A = range(0, customer_count)
    Am = range(1, customer_count)
    Vr = range(0, vehicle_count)

    y, d, D, X = {}, {}, {}, {}
    for i in A:
        d[i] = customers[i].demand
        for j in A:
            y[i, j] = length(customers[i], customers[j])
            for v in Vr:
                X[v, i, j] = model.addVar(vtype="B",
                                          name="X(%s,%s,%s)" % (v, i, j))
        for v in Vr:
            D[i, v] = model.addVar(lb=0,
                                   ub=Q,
                                   vtype="I",
                                   name="D(%s,%s)" % (i, v))
    """
    Lower Bound for Number of Vehicles
    """
    l = int(sum(d[i] for i in Am) / Q)
    for v in Vr:
        # Constraint: the total delivery load for a route is placed on the vehicle v,
        #             embarking on each trip, at the starting node itself
        # model.addCons(D[0,v] >= quicksum(X[v,i,j]*d[i] for i in Am for j in Am), "c12(%s)" % v)
        model.addCons(D[0, v] == Q, "c12(%s)" % v)

        for i in Am:
            # Constraint: the load on vehicle v, when departing from node i, is always lower than the vehicle capacity
            model.addCons(D[i, v] <= Q, "c11(%s,%s)" % (i, v))
            model.addCons(D[i, v] >= 0, "c17(%s,%s)" % (i, v))

    for j in A:
        if j > 0:
            # Constraint: each node must be visited exactly once
            model.addCons(
                quicksum(X[v, i, j] for v in Vr for i in A) == 1,
                "c8(%s)" % (j))
        for v in Vr:
            # Constraint: the same vehicle arrives and departs from each node it serves
            model.addCons(
                quicksum(X[v, i, j] for i in A) - quicksum(X[v, j, i]
                                                           for i in A) == 0,
                "c10(%s,%s)" % (j, v))

    for i in A:
        for j in Am:
            for v in Vr:
                # Constraint: transit load constraints i.e., if arc (i, j) is visited by the vehicle v, then the
                # quantity to be delivered by the vehicle has to decrease by d j
                model.addCons((D[i, v] - d[j] - D[j, v]) * X[v, i, j] == 0,
                              "c14(%s,%s,%s)" % (i, j, v))

    # Constraint: the number of vehicles used should be, at least, the calculated lower bound
    # model.addCons(quicksum(X[v,0,j] for v in Vr for j in Am) >= l, "cBound")

    # Objective function: minimize the total cost of travel
    model.setObjective(
        quicksum(y[i, j] * X[v, i, j] for i in A for j in A
                 for v in Vr), "minimize")

    model.optimize()
    best_sol = model.getBestSol()
    vehicle_tours = []

    for v in Vr:
        for i in A:
            for j in A:
                print "X[%s,%s,%s]: %s" % (
                    v, i, j, model.getSolVal(best_sol, X[v, i, j]))

    found_conn = 0
    visited_nodes = []
    for v in Vr:
        found_conn = 0
        vehicle_tours.append([])
        for i in A:
            if i == found_conn:
                found_conn = 0
                for j in Am:
                    if not j in visited_nodes:
                        current_val = model.getSolVal(best_sol, X[v, i, j])
                        if current_val >= 0.9:
                            if j > 0:
                                vehicle_tours[v].append(customers[j])
                                visited_nodes.append(j)
                            found_conn = j
                            break
                        if found_conn > 0:
                            break
    print(vehicle_tours)

    obj = model.getSolObjVal(best_sol)

    return obj, vehicle_tours
Exemplo n.º 19
0
def scip_solver_2(customers, customer_count, vehicle_count, vehicle_capacity):
    model = Model("vrp")

    c_range = range(0, customer_count)
    cd_range = range(1, customer_count)

    x, d, w, v = {}, {}, {}, {}
    for i in c_range:
        for j in c_range:
            d[i, j] = length(customers[i], customers[j])
            w[i, j] = customers[i].demand + customers[j].demand
            if j > i and i == 0:  # depot
                x[i, j] = model.addVar(ub=2,
                                       vtype="I",
                                       name="x(%s,%s)" % (i, j))
            elif j > i:
                x[i, j] = model.addVar(ub=1,
                                       vtype="I",
                                       name="x(%s,%s)" % (i, j))

    model.addCons(
        quicksum(x[0, j] for j in cd_range) <= 2 * vehicle_count,
        "DegreeDepot")

    for i in cd_range:
        model.addCons(
            quicksum(x[j, i] for j in c_range if j < i) +
            quicksum(x[i, j] for j in c_range if j > i) == 2, "Degree(%s)" % i)

        # model.addCons(quicksum(x[j, i] * w[j, i] for j in c_range if j < i) +
        #              quicksum(x[i, j] * w[i, j] for j in c_range if j > i) <= 2*vehicle_capacity)

        # for j in cd_range:
        #    for z in cd_range:
        #        if j > i and z > j:
        #            x[i, j] + x[j, z] + x[i, z] <= 2

        # for j in c_range:
        #    if j > i:
        #        model.addCons(x[i, j] * w[i, j] <= vehicle_capacity)

    model.setObjective(
        quicksum(d[i, j] * x[i, j] for i in c_range for j in c_range if j > i),
        "minimize")

    # model.hideOutput()

    # mip_gaps = [0.9, 0.5, 0.2, 0.03]
    mip_gaps = [0.0]
    runs = 0

    start = datetime.now()
    for gap in mip_gaps:
        model.freeTransform()
        model.setRealParam("limits/gap", gap)
        # model.setRealParam("limits/absgap", 0.3)
        model.setRealParam("limits/time", 60 * 20)  # Time limit in seconds
        # model.setIntParam('limits/bestsol', 1)

        edges, final_edges, runs = optimize(customer_count, customers, model,
                                            vehicle_capacity, vehicle_count, x)

    # model.setIntParam('limits/bestsol', -1)
    # model.freeTransform()
    # model.setRealParam("limits/gap", 0)
    # edges, final_edges = optimize(customer_count, customers, model, vehicle_capacity, vehicle_count, x)

    run_time = datetime.now() - start

    print edges
    print final_edges
    output = [[]] * vehicle_count
    for i in range(vehicle_count):
        output[i] = []
        current_item = None
        if len(final_edges) > 0:
            # Get the first edge starting with 0
            for e in final_edges:
                if e[0] == 0:
                    current_item = e
                    break
            if current_item:
                a = current_item[0]
                current_node = current_item[1]
                output[i].append(customers[current_node])
                final_edges.remove(current_item)
                searching_connections = True
                while searching_connections and len(final_edges) > 0:
                    for edge in final_edges:
                        found_connection = False
                        a_edge = edge[0]
                        b_edge = edge[1]

                        # If we find the node connecting with a 0
                        # it means the cycle has been closed
                        if b_edge == current_node and a_edge == 0:
                            final_edges.remove(edge)
                            break

                        if a_edge == current_node:
                            output[i].append(customers[b_edge])
                            current_node = b_edge
                            found_connection = True
                        elif b_edge == current_node:
                            output[i].append(customers[a_edge])
                            current_node = a_edge
                            found_connection = True

                        if found_connection:
                            final_edges.remove(edge)
                            break

                    if not found_connection:
                        searching_connections = False

    print output

    sol = model.getBestSol()
    obj = model.getSolObjVal(sol)

    print("RUN TIME: %s" % str(run_time))
    print("NUMBER OF OPTIMIZATION RUNS: %s" % runs)

    return obj, output
Exemplo n.º 20
0
def conv_model(conf_hw, conf_workload):
	model = Model("Example")
	model.hideOutput()
	
	# word per cycle
	dram_rd_bw = 8 
	dram_wr_bw = 8

	loop_depth = 6

	adj = np.array([[0,1,0,0,1,1],
				[1,0,0,0,0,0],
			    [1,1,1,1,0,0],
			    [1,1,1,1,0,0],
			    [0,1,0,0,0,0],
			    [1,1,1,1,1,1]])

	x = {}
	for i in range(loop_depth):
		for j in range(6): # 6 - D1,2,3,X,L,T
			x[i, j] = model.addVar(vtype="INTEGER", name="x(%s,%s)"%(i,j))

	# keep tile param of infeasible partition dim to 1
	for i in range(loop_depth):
		for j in range(6):
			if adj[j, i] == 0:
				model.addCons(x[i, j] == 1) 


	# mapping matrix space constraint
	for i in range(loop_depth):
		for j in range(6):
			model.addCons(x[i, j] >= 1)


	# spartial partition - D1,2,3
	for i in range(3):
		model.addCons(x[0, i] * x[1, i] * x[2, i] * x[3, i] * x[4, i] * x[5, i] <= conf_hw[list(conf_hw.keys())[i]])

	# worload amount
	for j in range(loop_depth):
		model.addCons(x[j, 0] * x[j, 1] * x[j, 2] * x[j, 3] * x[j, 4] * x[j, 5]  >= conf_workload[list(conf_workload.keys())[j]])

	# constraint1: accumulation latency - tm * tw * th > D1 + lat (4)
	model.addCons(x[0, 5] * x[2, 5] * x[3, 5] >= (conf_hw['D1'] + 4))

	# constraint2: WBUF consumption <= N_W (tlx - m, n, i, j)
	n_w = model.addVar("n_w", vtype="INTEGER")
	model.addCons(x[0, 5] * x[1, 5] * x[4, 5] * x[5, 5] * x[0, 4] * x[1, 4] * x[4, 4] * x[5, 4] * x[0, 3] * x[1, 3] * x[4, 3] * x[5, 3] == n_w)
	model.addCons(n_w <= conf_hw['N_W'])

	# constraint3: ActBUF consumption <= N_ACT (t - n, w, h)
	model.addCons(x[1, 5] * x[2, 5] * x[3, 5] <= conf_hw['N_ACT'])

	# constraint4: PSum consumption <= N_PSUM (tl - m, w, h)
	n_psum = model.addVar("n_psum", vtype="INTEGER")
	model.addCons(x[0, 5] * x[2, 5] * x[3, 5] * x[0, 4] * x[2, 4] * x[3, 4] == n_psum)
	model.addCons(n_psum <= conf_hw['N_PSUM'])

	# performance evaluation

	c_comp = model.addVar("c_comp", vtype="INTEGER")
	n_actrd = model.addVar("n_actrd", vtype="INTEGER")
	n_psumwr = model.addVar("n_psumwr", vtype="INTEGER")
	n_psumrd = model.addVar("n_psumrd", vtype="INTEGER")

	# final execution time
	c_exe = model.addVar("c_exe", vtype="INTEGER")

	# estimate the computation time
	c_comp = model.addVar("c_comp", vtype="INTEGER")
	model.addCons(c_comp == x[0, 5] * x[1, 5] * x[2, 5] * x[3, 5] * x[4, 5] * x[5, 5] * x[0, 4] * x[1, 4] * x[2, 4] * x[3, 4] * x[4, 4] * x[5, 4] * x[0, 3] * x[1, 3] * x[2, 3] * x[3, 3] * x[4, 3] * x[5, 3])

	c_x = model.addVar("c_x", vtype="INTEGER")
	model.addCons(x[0, 3] * x[1, 3] * x[2, 3] * x[3, 3] * x[4, 3] * x[5, 3] == c_x)
	c_l = model.addVar("c_l", vtype="INTEGER")
	model.addCons(x[0, 4] * x[1, 4] * x[2, 4] * x[3, 4] * x[4, 4] * x[5, 4] == c_l)

	# estimate actrd
	model.addCons(x[1, 5] * x[2, 5] * x[3, 5] * c_l * c_x == n_actrd)
	
	# estimate psumwr
	model.addCons(n_psum * c_x == n_psumwr)

	# estimate psumrd
	model.addCons(n_psumwr == n_psumrd)

	# bandwidth constraints
	model.addCons((n_actrd / c_exe) + (n_psumrd / c_exe) <= dram_rd_bw)
	model.addCons((n_psumwr / c_exe) <= dram_wr_bw)
		
	model.addCons(c_comp <= c_exe)
	model.addCons((n_actrd + n_psumrd) / dram_rd_bw <= c_exe)
	model.addCons(n_psumwr / dram_wr_bw <= c_exe)



	model.setObjective(c_exe)
	model.optimize()
	sol = model.getBestSol()

	return sol
Exemplo n.º 21
0
def optimal_split(texts,
                  labels=None,
                  train_ratio=0.8,
                  preset=None,
                  optimizer="mip"):
    alphabet = dict()

    for text in texts:
        for letter in text:
            if letter not in alphabet:
                alphabet[letter] = len(alphabet)

    if labels:
        unique_labels = set(labels)
        print("optimal_split uses %d additional labels." % len(unique_labels))
        for label in unique_labels:
            alphabet[("label", label)] = len(alphabet)

    counts = np.zeros((len(texts), len(alphabet)), dtype=np.uint8)

    for i, text in tqdm(list(enumerate(texts)), desc="counting"):
        for letter in text:
            j = alphabet[letter]
            counts[i, j] += 1

        if labels:
            j = alphabet[("label", labels[i])]
            counts[i, j] += 1

    total = np.sum(counts, axis=0, dtype=np.uint32)

    cons = np.zeros((len(alphabet), ), dtype=np.uint32)
    for j, x in enumerate(total):
        cons[j] = max(1, min(x - 1, int(x * train_ratio)))

    print("building model.")

    if optimizer == "scip":
        from pyscipopt import Model, quicksum
        model = Model()
        xs = [model.addVar(vtype="BINARY") for _ in range(len(texts))]

        if preset:
            for i in preset.get(True, []):
                model.addCons(xs[i] == 1)
            for i in preset.get(False, []):
                model.addCons(xs[i] == 0)

        for j in range(len(alphabet)):
            freq = quicksum([x * counts[i, j] for i, x in enumerate(xs)])
            model.addCons(freq >= cons[j])

        model.setObjective(quicksum(xs))
        model.setMinimize()

        model.optimize()
        sol = model.getBestSol()
        #print(sol)

        allocation = np.zeros((len(xs)), dtype=np.bool)
        for i, x in enumerate(xs):
            allocation[i] = sol[x] > 0.5
    elif optimizer == "mip":
        from mip import Model, MINIMIZE, CBC, BINARY, xsum
        model = Model(sense=MINIMIZE, solver_name=CBC)
        xs = [model.add_var(var_type=BINARY) for _ in range(len(texts))]

        if preset:
            for i in preset.get(True, []):
                model += xs[i] == 1
            for i in preset.get(False, []):
                model += xs[i] == 0

        for j in range(len(alphabet)):
            freq = xsum(x * counts[i, j] for i, x in enumerate(xs))
            model += freq >= cons[j]

        model += xsum(xs) >= int(len(xs) * train_ratio)

        model.objective = xsum(xs)  # minimize
        status = model.optimize(max_seconds=2)
        print(status)

        allocation = np.zeros((len(xs)), dtype=np.bool)
        for i, x in enumerate(xs):
            allocation[i] = x.x > 0.5
    else:
        raise ValueError("unsupported optimizer %s" % optimizer)

    return allocation
Exemplo n.º 22
0
def scip_solver_2(customers, customer_count, vehicle_count, vehicle_capacity):
    model = Model("vrp")

    c_range = range(0, customer_count)
    cd_range = range(1, customer_count)

    x, d, w, v = {}, {}, {}, {}
    for i in c_range:
        for j in c_range:
            d[i, j] = length(customers[i], customers[j])
            w[i, j] = customers[i].demand + customers[j].demand
            if j > i and i == 0:  # depot
                x[i, j] = model.addVar(ub=2,
                                       vtype="I",
                                       name="x(%s,%s)" % (i, j))
            elif j > i:
                x[i, j] = model.addVar(ub=1,
                                       vtype="I",
                                       name="x(%s,%s)" % (i, j))

    model.addCons(
        quicksum(x[0, j] for j in cd_range) <= 2 * vehicle_count,
        "DegreeDepot")

    for i in cd_range:
        model.addCons(
            quicksum(x[j, i] for j in c_range if j < i) +
            quicksum(x[i, j] for j in c_range if j > i) == 2, "Degree(%s)" % i)

    model.setObjective(
        quicksum(d[i, j] * x[i, j] for i in c_range for j in c_range if j > i),
        "minimize")

    mip_gaps = [0.0]
    runs = 0

    start = datetime.now()
    for gap in mip_gaps:
        model.freeTransform()
        model.setRealParam("limits/gap", gap)
        model.setRealParam("limits/time", 60 * 20)  # Time limit in seconds
        edges, final_edges, runs = optimize(customer_count, customers, model,
                                            vehicle_capacity, vehicle_count, x)

    run_time = datetime.now() - start

    print(edges)
    print(final_edges)
    output = [[]] * vehicle_count
    for i in range(vehicle_count):
        output[i] = []
        current_item = None
        if len(final_edges) > 0:

            for e in final_edges:
                if e[0] == 0:
                    current_item = e
                    break
            if current_item:
                a = current_item[0]
                current_node = current_item[1]
                output[i].append(customers[current_node])
                final_edges.remove(current_item)
                searching_connections = True
                while searching_connections and len(final_edges) > 0:
                    for edge in final_edges:
                        found_connection = False
                        a_edge = edge[0]
                        b_edge = edge[1]

                        if b_edge == current_node and a_edge == 0:
                            final_edges.remove(edge)
                            break

                        if a_edge == current_node:
                            output[i].append(customers[b_edge])
                            current_node = b_edge
                            found_connection = True
                        elif b_edge == current_node:
                            output[i].append(customers[a_edge])
                            current_node = a_edge
                            found_connection = True

                        if found_connection:
                            final_edges.remove(edge)
                            break

                    if not found_connection:
                        searching_connections = False

    print(output)

    sol = model.getBestSol()
    obj = model.getSolObjVal(sol)

    print("RUN TIME: %s" % str(run_time))
    print("NUMBER OF OPTIMIZATION RUNS: %s" % runs)

    return obj, output
Exemplo n.º 23
0
from pyscipopt import Model

model = Model("Caso2")  # model name is optional
a = model.addVar("a", vtype="CONTINUOUS")
b = model.addVar("b", vtype="CONTINUOUS")
o = model.addVar("o", vtype="CONTINUOUS")
tests = ["caso2_test1", "caso2_test2"]

for test in tests:
    #me traigo el caso de test y le pongo de nombre input_B e input_N
    copyfile(os.path.join("tests", "caso2", test + "_B.txt"), "input_B.txt")
    copyfile(os.path.join("tests", "caso2", test + "_N.txt"), "input_N.txt")
    #Cargo en SCIP el problema en formato ZIMPL
    model.readProblem("caso2.zpl")
    model.optimize()
    sol = model.getBestSol()
    #Busco solucion e imprimo puntos
    blanco = open('input_B.txt', 'r').read()
    negro = open('input_N.txt', 'r').read()
    print("\n\n###############################################")
    print("Test " + test + ":\n")
    print("Blanco: \n" + blanco)
    print("Negro: \n" + negro + "\n")
    print("Solucion:")
    print("a: {}".format(sol[a]))
    print("b: {}".format(sol[b]))
    print("o: {}".format(sol[o]))
    print("###############################################")
os.remove("input_B.txt")
os.remove("input_N.txt")
Exemplo n.º 24
0
def scip_solver(customers, facilities, limit_solutions):
    '''
    Data structure:

    Point = namedtuple("Point", ['x', 'y'])
    Facility = namedtuple("Facility", ['index', 'setup_cost', 'capacity', 'location'])
    Customer = namedtuple("Customer", ['index', 'demand', 'location'])
    '''

    n_f = range(0, len(facilities))
    n_c = range(0, len(customers))

    m = Model("Facility")
    m.hideOutput
    m.setMinimize()
    #m.setRealParam("limits/gap", 0.01)
    m.setRealParam("limits/time", 3600 * 4)
    #if limit_solutions == True:
    #	m.setIntParam("limits/bestsol", 10)
    #m.setIntParam("limits/bestsol", 1)

    # Variables to define if customer 'c' is assinged to facility 'f'
    # and if facility is active.
    x, f, d = {}, {}, {}
    for j in n_f:
        f[j] = m.addVar(vtype="B", name="f(%s)" % (j))
        for i in n_c:
            x[i, j] = m.addVar(vtype="B", name="x(%s,%s)" % (i, j))
            #x[i,j] = m.addVar(vtype="C", name="x(%s,%s)"%(i,j))

            # Distance between facilities and customers
            d[i, j] = facility_customer_dist(facilities[j], customers[i])

    for j in n_f:
        # Constraint 1: The sum of the demand from all the consumers 'c'
        # assigned to facility 'f' should be equal or less than the
        # facility's capacity.
        m.addCons(
            quicksum(x[i, j] * customers[i].demand
                     for i in n_c) <= f[j] * facilities[j].capacity,
            "Cap(%s)" % j)
        #m.addCons(quicksum(x[i,j] for i in n_c) <= facilities[j].capacity*f[j], "Cap(%s)"%i)

    # Constraint 2: Each customer must be served by exactly one facility
    for i in n_c:
        m.addCons(quicksum(x[i, j] for j in n_f) == 1, "Cust(%s)" % (i))
        #m.addCons(quicksum(x[i,j] for j in n_f) == customers[i].demand, "Cust(%s)"%i)

    # Constraint to make sure a not open facility is not assigned
    for (i, j) in x:
        m.addCons(x[i, j] <= f[j], "Fac(%s,%s)" % (i, j))
        #m.addCons(x[i,j] <= f[j]*customers[i].demand, "Fac(%s,%s)"%(i,j))

    # Objective function
    m.setObjective(
        quicksum(x[i, j] * d[i, j] for i in n_c
                 for j in n_f) + quicksum(f[j] * facilities[j].setup_cost
                                          for j in n_f), "minimize")

    m.data = x, f
    m.optimize()

    best_sol = m.getBestSol()
    sol = []
    for i in n_c:
        #print("Customer: %s" % i)
        for j in n_f:
            #print("Facility: %s" % j)
            current_val = m.getSolVal(best_sol, x[i, j])
            #print("x[%s,%s]: %s" % (i, j, current_val))
            if current_val >= 0.9:
                sol.append(j)
                break

    #assert len(sol) == len(customers)
    print len(customers)
    print len(sol)
    '''
    sol = [0 for i in range(0, n_c)]
    for i in range(0, n_f):
        for j in range(0, n_c):
            current_val = m.getVal(x[i,j])
            if current_val == 1:
                #print "x[%s,%s] = %s" % (i,j,current_val)
                sol[j] = i
    '''

    #obj = m.getObjVal()
    obj = m.getSolObjVal(best_sol)
    return obj, sol