Exemple #1
0
def legalizeFloorplanResults(
    orig_v2s: Dict[Vertex, Slot], grouping_list: List[List[Vertex]],
    all_slot_list: List[Slot], resource_usage_limit: int
) -> Tuple[Dict[Slot, List[Vertex]], Dict[Vertex, Slot]]:
    """
  adjust the floorplanning to satisfy the area requirement
  """
    _logger.info('Begin legalizing the floorplan results...')
    _logger.info(f'Target resource usage limit: {resource_usage_limit}')

    m = Model()

    v_list = list(orig_v2s.keys())
    s_list = all_slot_list

    v_to_s_to_var, s_to_v_to_var = _createILPVars(m, v_list, s_list)
    v_to_s_to_cost = _getVToSToCost(v_list, s_list, orig_v2s)

    _addAreaConstrains(m, s_to_v_to_var, resource_usage_limit)

    _addUniqueConstrains(m, v_to_s_to_var)

    _addGroupingConstraints(m, grouping_list, v_to_s_to_var, s_list)

    _addObjective(m, v_to_s_to_cost, v_to_s_to_var)

    status = m.optimize()
    if status != OptimizationStatus.OPTIMAL:
        _logger.warning(
            f'Fail to legalize the floorplan under target ratio {resource_usage_limit}'
        )
        m.write('floorplan_legalization.lp')
        return None, None

    new_v2s, new_s2v = _getILPResults(v_to_s_to_var)

    _logResults(new_s2v, new_v2s, orig_v2s)

    _logger.info('Finish legalizing the floorplan results.')

    return new_s2v, new_v2s
Exemple #2
0
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
class PythonMIPReader(FileReaderInterface):
    def __init__(self, input_file: str) -> None:
        self.instance_name = input_file.split("/")[-1].split(".")[0]
        self.m = Model()

        print("Reding lp file", self.instance_name)
        self.m.read(input_file)
        print("Reading of ", self.instance_name, " model done!")

        self.vars = self.m.vars
        self.constrs = self.m.constrs

        self.tmp_reader_dir = tempfile.mkdtemp()

    def __del__(self):
        shutil.rmtree(self.tmp_reader_dir)

    def write_model_with_new_bounds(self, lbs: List[float],
                                    ubs: [List[float]]) -> str:
        assert (len(lbs) == len(ubs) == len(self.m.vars))
        for i in range(len(lbs)):
            self.m.vars[i].lb = lbs[i]
            self.m.vars[i].ub = ubs[i]
        out_path = os.path.join(self.tmp_reader_dir,
                                str(self.instance_name) + ".mps")
        self.m.write(out_path)
        return out_path

    def get_n_vars(self) -> int:
        return self.m.num_cols

    def get_n_cons(self) -> int:
        return self.m.num_rows

    def get_nnz(self) -> int:
        return self.m.num_nz

    def get_var_bounds(self) -> Tuple[List[float]]:
        ubs = map(lambda var: var.ub, self.vars)
        lbs = map(lambda var: var.lb, self.vars)
        return list(lbs), list(ubs)

    def get_lrhss(self) -> Tuple[List[float]]:
        lhss = map(
            lambda cons: float('-Inf')
            if cons.expr.sense == '<' else cons.rhs, self.constrs)
        rhss = map(
            lambda cons: float('Inf')
            if cons.expr.sense == '>' else cons.rhs, self.constrs)
        return list(lhss), list(rhss)

    def get_cons_matrix(self) -> Tuple[List[Union[int, float]]]:
        def get_expr_coos(expr: LinExpr, var_indices: Dict[Var,
                                                           int]) -> Generator:
            for var, coeff in expr.expr.items():
                yield coeff, var_indices[var]

        row_indices = []
        row_ptrs = []
        col_indices = []
        coeffs = []

        var_indices = {v: i for i, v in enumerate(self.vars)}

        row_ctr = 0
        row_ptrs.append(row_ctr)

        for row_idx, constr in enumerate(self.constrs):

            for coeff, col_idx in get_expr_coos(constr.expr, var_indices):
                row_ctr += 1
                row_indices.append(row_idx)
                col_indices.append(col_idx)
                coeffs.append(coeff)

            row_ptrs.append(row_ctr)

        return (coeffs, row_ptrs, col_indices)

    def get_SCIP_vartypes(self) -> List[int]:
        conversion_dict = {'B': 0, 'I': 1, 'C': 3}
        python_mip_vartypes = map(lambda var: var.var_type, self.vars)
        return list(map(conversion_dict.get, python_mip_vartypes))
Exemple #4
0
# There are k x t variables, stored in a matrix of k rows by t columns
x = [model.add_var(var_type=BINARY) for j in R]

model.objective = minimize(xsum(x[i] for i in R))

nodes_forgotten = 0
for a in J:
    tagset = user_hashtag_matrix.iloc[a][user_hashtag_matrix.iloc[a] == 1]
    if len(tagset.index) == 0:
        nodes_forgotten += 1
    else:
        model += xsum(x[i] for i in tagset.index) >= 1

model.optimize(max_seconds=optimization_runtime)
if write_model_file:
    model.write(model_filename)

sleep(1)

foundClusters = []
if model.status == OptimizationStatus.OPTIMAL or model.status == OptimizationStatus.FEASIBLE:
    print('Tags in each cluster:')
    for v in model.vars:
        if abs(v.x) > 1e-6 and int(
                v.name[4:-1]) < (k * t):  # only printing non-zeros
            if int(v.name[4:-1]) // t + 1 not in foundClusters:
                print("\nCluster", int(v.name[4:-1]) // t + 1)
                foundClusters.append(int(v.name[4:-1]) // t + 1)
            print(hashtags.iloc[(int(v.name[4:-1]) % t)][0])
    if cover_or_forget:
        print('\nForgotten nodes:')
    # STEP 3: adding the new columns (if any is obtained with negative reduced cost)
    ##########

    # checking if columns with negative reduced cost were produced and
    # adding them into the restricted master problem
    if pricing.objective_value < -1e-5:
        pattern = [a[i].x for i in range(m)]
        column = Column(constraints, pattern)
        lambdas.append(
            master.add_var(obj=1,
                           column=column,
                           name='lambda_%d' % (len(lambdas) + 1)))

        print('new pattern = {pattern}'.format(**locals()))

    # if no column with negative reduced cost was produced, then linear
    # relaxation of the restricted master problem is solved
    else:
        new_vars = False

    pricing.write('pricing.lp')

# printing the solution
print('')
print('Objective value: {master.objective_value:.3}'.format(**locals()))
print('Solution: ', end='')
for v in lambdas:
    if v.x > 1e-6:
        print('{v.name} = {v.x:.3}  {v.column}'.format(**locals()))
        print('          ', end='')
Exemple #6
0
# conflicting items
C = ((2, 3), (2, 4), (3, 4), (2, 5))

m = Model()

x = {i: m.add_var("x({})".format(i), var_type=BINARY) for i in I}

m.objective = maximize(xsum(p[i] * x[i] for i in I))

m += xsum(w[i] * x[i] for i in I) <= c

for (i, j) in C:
    m += x[i] + x[j] <= 1

m.verbose = 0
m.write("b.lp")
m.optimize(relax=True)

print("constraints before clique merging: {}. lower bound:"
      "{}.".format(len(m.constrs), m.objective_value))

m.clique_merge()

m.optimize(relax=True)

print("constraints after clique merging: {}. lower bound:"
      "{}.".format(len(m.constrs), m.objective_value))

m.optimize()

print("optimal: {}".format(m.objective_value))
#!/usr/bin/env python3
#
# See: https://python-mip.readthedocs.io/en/latest/examples.html
#
from mip import Model, xsum, maximize, MAXIMIZE, MINIMIZE, minimize, BINARY, INTEGER, CONTINUOUS

m = Model(sense=MINIMIZE)

x1 = m.add_var(var_type=CONTINUOUS)
x2 = m.add_var(var_type=CONTINUOUS)

m.objective = minimize(1100 * x1 + 700 * x2)

m += ((2 * x1 + 2 * x2) >= 16)

m += ((3 * x1 + 1 * x2) >= 12)

status = m.optimize()  #(max_seconds=300)

print("x1 =", x1.x, " x2 =", x2.x, " status =", status, " obj =",
      m.objective_value)

m.write("ex_prova.lp")
Exemple #8
0
# 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)

# coins availability
# these are 8 different scalar constraints expressed with tensor notation
model += x <= available, "availability"

# go and see how the constraint lable was expanded
model.write("numpy_tensor_example.lp")

model.optimize()

x_val = np.vectorize(lambda var: var.x)(x)
print("Solution vector: %s" % x_val)

print("Coins:")
for coin_value, pieces in zip(vals, x_val):
    print("%0.2f euro coin: %d" % (coin_value, pieces))
#!/usr/bin/env python3
#
# See: https://python-mip.readthedocs.io/en/latest/examples.html
#
from mip import Model, xsum, maximize, MAXIMIZE, BINARY, INTEGER

m = Model(sense=MAXIMIZE)

x1 = m.add_var(var_type=INTEGER)
x2 = m.add_var(var_type=INTEGER)

m.objective = maximize(5*x1 + 8*x2)

m += ((x1 + x2) <= 6)

m += ((5*x1 + 9*x2) <= 45)

status = m.optimize() #(max_seconds=300)

print("x1 =", x1.x, " x2 =", x2.x, " status =", status, " obj =",m.objective_value)

m.write("ex1_marcone.lp")