def test_LinExprTensor(): model = Model() x = model.add_var_tensor(shape=(3, ), name="x") print(x) assert x.shape == (3, ) assert isinstance(x, LinExprTensor) A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) y = A @ x print(y) assert y.shape == (3, ) assert isinstance(y, LinExprTensor) constr = y <= 10 print(constr) assert constr.shape == (3, ) assert isinstance(x, LinExprTensor) constr = y >= 10 print(constr) assert constr.shape == (3, ) assert isinstance(x, LinExprTensor) constr = y == 10 print(constr) assert constr.shape == (3, ) assert isinstance(x, LinExprTensor)
def test_numpy(): model = Model() N = 1000 start = time.time() x = model.add_var_tensor(shape=(N, N), name="x") # inefficient way to compute trace, so we can test optimizations # equivalent to model += np.trace(x) model += np.ones((N, )) @ (x * np.eye(N)) @ np.ones((N, )) # constraints model += np.vectorize(lambda x_i_j: x_i_j >= 1)(x) stop = time.time() print("model built in: %.1f seconds" % (stop - start)) model.write("numpy_tensors.lp") result = model.optimize() assert result == OptimizationStatus.OPTIMAL
import sys from mip import Model, INTEGER, maximize, CutType, OptimizationStatus larger_diff = -1 best_cut = None for ct in CutType: print("Trying cut type: {}".format(ct.name)) m = Model() if m.solver_name.upper() in ["GRB", "GUROBI"]: print("This feature is currently not supported in Gurobi.") else: m.verbose = 0 x = m.add_var_tensor(shape=(2, 1), name="x", var_type=INTEGER) m.objective = maximize(2 * x[0] + x[1]) m += 7 * x[0] + x[1] <= 28 m += -x[0] + 3 * x[1] <= 7 m += -8 * x[0] - 9 * x[1] <= -32 m.optimize(relax=True) olr = m.objective_value cp = m.generate_cuts([ct]) if cp and cp.cuts: print("{} cuts generated:".format(len(cp.cuts))) for c in cp.cuts: print(" " + str(c))
This is a purely integer problem well suited to showcase numpy matrices. """ from mip import Model, MINIMIZE, INTEGER import numpy as np model = Model(sense=MINIMIZE) # we have coins for 1 cent, 2 cents, 5 cents, 10 cents, 20 cents, 50 cents, 1 euro, 2 euros vals = np.array([0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2], dtype=float) # we have a limited amount of coins for each type available = np.array([5, 5, 5, 5, 5, 5, 2, 0], dtype=int) # 8 types of coins in total x = model.add_var_tensor(shape=vals.shape, name="x", var_type=INTEGER) # objective: minimize number of coins model.objective = x.sum() # boundary: amount must be equal to required change, within rouding errors required_change = 3.74 eps = 0.005 # total value of the coins amount = x.dot(vals) print("Value of the coins: %s" % amount) # these are 2 separate scalar constraints computed with tensor notation model += (required_change - eps) <= amount model += amount <= (required_change + eps)