简体   繁体   中英

CPLEX - getting minimum of a matrix subset

I am using the Python API to cplex to solve an optimization problem: finding the set of binary variables of size N (eg 10) to maximize their mutual distance. To do so, I have put together the following:

 matrix = pd.read_csv("matrix.csv", index_col=0)

 # declare integer variables
 im = Model(name='max_weight_clique')
 b = im.binary_var_dict(matrix.index.values)

 # define objective function
 clique_weight = im.sum(b[i] * b[j] * (matrix.loc[i, j] + matrix.loc[j, i])
                             for i, j in itertools.combinations(matrix.index, 2))
 # add to key performance indicators
 im.add_kpi(clique_weight, 'clique_weight')

 # set size of clique
 im.add_constraint(im.sum(b) == 10)

 im.maximize(clique_weight)

I would like to modify my objective function to, instead, maximize the minimum distance. When I try to specify this as the following, I run into an error:

# minimum within clique
clique_min = im.min(adj_mat.loc[i, j] for i in adj_mat.index for j in adj_mat.index if b[i] == 1 and b[j] == 1)
im.add_kpi(clique_min, 'clique_min')

TypeError: cannot convert a constraint to boolean: acc_num_NC_015394 == 1

How should I correctly specify this constraint? This seems related to this SO , but my issue is specific to the python API.

The issue in your formulation is that the '==' tests involving binary decision variables in the iterators are not recognized as model constraints.

One option to model this kind of constraint is to use indicator constraints. Here is a possible formulation for your example:

bij_ind = im.binary_var_matrix(matrix.index.values, matrix.index.values, name='ind_')
clique_min = im.continuous_var(name='clique_min')
for i in matrix.index:
    for j in matrix.index:
        im.add(bij_ind[i, j] == im.min(b[i], b[j]))
        im.add_indicator(bij_ind[i, j], clique_min <= adj_mat.loc[i, j])

im.add_kpi(clique_min, 'clique_min')
im.maximize(clique_min)

I don't think this formulation is very efficient though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM