Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
EST = inst["EST"]
mip = create_mip("gurobi", J, dur, S, c, r, EST)
mip.verbose = 0
mip.relax()
mip.optimize()
assert mip.status == OptimizationStatus.OPTIMAL
z_relax = mip.objective_value
mip = create_mip("gurobi", J, dur, S, c, r, EST)
mip.verbose = 0
mip.max_nodes = 512
mip.optimize()
z_lb = mip.objective_bound
z_ub = mip.objective_value
assert mip.status in [
OptimizationStatus.OPTIMAL,
OptimizationStatus.FEASIBLE,
]
sum_dur = sum(dur[i] for i in J)
score = (
(z_ub - z_relax) / sum_dur
+ 2 * (z_ub - z_relax)
+ 5 * (z_ub - z_lb)
)
assert score >= -1e-10
if score > best_score:
best_score = score
best_inst = inst
best_z_relax = z_relax
best_z_lb = z_lb
best_z_ub = z_ub
inst = best_inst
with open("./data/rcpsp-%d-%d.json" % (nj, ii + 1), "w") as outfile:
model.start = [(x[seq[i]][seq[i+1]], 1) for i in range(len(seq)-1)]
model.max_seconds = timeLimit
model.threads = threads
model.optimize()
end = time()
print(model.status)
print(model.solver_name)
objv = 1e20
gap = 1e20
n_nodes = 0
if model.status in [OptimizationStatus.OPTIMAL, OptimizationStatus.FEASIBLE]:
out.write('route with total distance %g found: 0'
% (model.objective_value))
nc = 0
while True:
n_nodes += 1
nc = [i for i in V if x[nc][i].x >= 0.99][0]
out.write(' -> %s' % nc)
if nc == 0:
break
out.write('\n')
objv = model.objective_value
gap = model.gap
if n_nodes != n:
err.write('incomplete route (%d from %d) generated.\n' % (n_nodes, n))
exit(1)
raise ParameterNotAvailable("Error getting status")
if gstatus[0] == GRB_OPTIMAL:
self._status = OptimizationStatus.OPTIMAL
ires = ffi.new("int *")
st = GRBgetintattr(grb_model, "NumVars".encode("utf-8"), ires)
if st != 0:
raise ParameterNotAvailable("Could not query number of variables")
ncols = ires[0]
self._cb_sol = ffi.new("double[{}]".format(ncols))
res = GRBcbget(cb_data, where, GRB_CB_MIPNODE_REL, self._cb_sol)
if res != 0:
raise ParameterNotAvailable("Error getting fractional solution")
else:
self._cb_sol = ffi.NULL
elif where == GRB_CB_MIPSOL:
self._status = OptimizationStatus.FEASIBLE
ires = ffi.new("int *")
st = GRBgetintattr(grb_model, "NumVars".encode("utf-8"), ires)
if st != 0:
raise ParameterNotAvailable(
"Could not query number of variables in Gurobi callback"
)
ncols = ires[0]
self._cb_sol = ffi.new("double[{}]".format(ncols))
res = GRBcbget(cb_data, where, GRB_CB_MIPSOL_SOL, self._cb_sol)
if res != 0:
raise ParameterNotAvailable(
"Error getting integer solution in gurobi callback"
)
objp = ffi.new("double *")
res = GRBcbget(cb_data, where, GRB_CB_MIPSOL_OBJ, objp)
if model.num_solutions:
out.write("route with total distance %g found: %s" % (model.objective_value, 0))
nc = 0
while True:
nc = [i for i in V if x[nc][i].x >= 0.99][0]
out.write(" -> %s" % nc)
if nc == 0:
break
out.write("\n")
# sanity tests
from mip import OptimizationStatus
if model.status == OptimizationStatus.OPTIMAL:
assert round(model.objective_value) == 7013
elif model.status == OptimizationStatus.FEASIBLE:
assert round(model.objective_value) >= 7013
else:
assert model.objective_bound <= 7013 + 1e-7
model.check_optimization_results()
# concluded (time, iteration limit...)
if (self.num_int() + self.get_int_attr("NumSOS")) and (not relax):
if status in [8, 9, 10, 11, 13]:
nsols = self.get_int_attr("SolCount")
if nsols >= 1:
self.__x = ffi.new("double[{}]".format(self.num_cols()))
self.__obj_val = self.get_dbl_attr("ObjVal")
attr = "X".encode("utf-8")
st = GRBgetdblattrarray(
self._model, attr, 0, self.num_cols(), self.__x
)
if st:
raise ParameterNotAvailable("Error querying Gurobi solution")
return OptimizationStatus.FEASIBLE
return OptimizationStatus.NO_SOLUTION_FOUND
if status == 1: # LOADED
return OptimizationStatus.LOADED
if status == 2: # OPTIMAL
if isinstance(self.__x, EmptyVarSol):
self.__obj_val = self.get_dbl_attr("ObjVal")
self.__x = ffi.new("double[{}]".format(self.num_cols()))
attr = "X".encode("utf-8")
st = GRBgetdblattrarray(self._model, attr, 0, self.num_cols(), self.__x)
if st:
raise ParameterNotAvailable("Error quering Gurobi solution")
if (self.num_int() + self.get_int_attr("NumSOS")) == 0 or (relax):
def objective_bound(self: "Model") -> Optional[numbers.Real]:
"""
A valid estimate computed for the optimal solution cost,
lower bound in the case of minimization, equals to
:attr:`~mip.Model.objective_value` if the
optimal solution was found.
"""
if self.status not in [
mip.OptimizationStatus.OPTIMAL,
mip.OptimizationStatus.FEASIBLE,
mip.OptimizationStatus.NO_SOLUTION_FOUND,
]:
return None
return self.solver.get_objective_bound()
# checking if a solution was found
if model.num_solutions:
out.write('route with total distance %g found: %s'
% (model.objective_value, 0))
nc = 0
while True:
nc = [i for i in V if x[nc][i].x >= 0.99][0]
out.write(' -> %s' % nc)
if nc == 0:
break
out.write('\n')
# sanity tests
if model.status == OptimizationStatus.OPTIMAL:
assert round(model.objective_value) == 7013
elif model.status == OptimizationStatus.FEASIBLE:
assert round(model.objective_value) >= 7013
else:
assert model.objective_bound <= 7013 + 1e-7
if status == 6: # CUTOFF
return OptimizationStatus.CUTOFF
if status == 7: # ITERATION_LIMIT
return OptimizationStatus.OTHER
if status == 8: # NODE_LIMIT
return OptimizationStatus.OTHER
if status == 9: # TIME_LIMIT
return OptimizationStatus.OTHER
if status == 10: # SOLUTION_LIMIT
return OptimizationStatus.FEASIBLE
if status == 11: # INTERRUPTED
return OptimizationStatus.OTHER
if status == 12: # NUMERIC
return OptimizationStatus.OTHER
if status == 13: # SUBOPTIMAL
return OptimizationStatus.FEASIBLE
if status == 14: # INPROGRESS
return OptimizationStatus.OTHER
if status == 15: # USER_OBJ_LIMIT
return OptimizationStatus.FEASIBLE
self._updated = True
return status
print("Facilities capacities: {} ".format([z[f].x for f in F]))
print("Facilities cost: {}".format([y[f].x for f in F]))
# plotting allocations
for (i, j) in [(i, j) for (i, j) in product(F, C) if x[(i, j)].x >= 1e-6]:
plt.plot(
(pf[i][0], pc[j][0]), (pf[i][1], pc[j][1]), linestyle="--", color="darkgray"
)
plt.savefig("location-sol.pdf")
# sanity checks
opt = 99733.94905406
if m.status == OptimizationStatus.OPTIMAL:
assert abs(m.objective_value - opt) <= 0.01
elif m.status == OptimizationStatus.FEASIBLE:
assert m.objective_value >= opt - 0.01
else:
assert m.status not in [OptimizationStatus.INFEASIBLE, OptimizationStatus.UNBOUNDED]
def xi(self, i: int) -> Optional[numbers.Real]:
"""Value for this variable in the :math:`i`-th solution from the solution
pool. Note that None is returned if the solution is not available."""
if self.__model.status in [
mip.OptimizationStatus.OPTIMAL,
mip.OptimizationStatus.FEASIBLE,
]:
return self.__model.solver.var_get_xi(self, i)
return None