Help with the f1 function of the kcluster with fixed cardinality problem
AnsweredI'm trying to implement the F1  function of the kcluster with fixed cardinality problem, but i have troubles with variables and constraints when i check them with the .write on an lp file. This is my code:
from mip import *
# creating model
model = Model(sense=MAXIMIZE)
# cluster index
K: int = 2
# total number of items
N = 5
# number of items per cluster k
Mk = 2
# similarity between items i and j
s = [
[0, 0.2, 0.5, 0.8, 0.3],
[0.2, 0, 0.6, 0.4, 0.7],
[0.5, 0.6, 0, 0.9, 0.1],
[0.8, 0.4, 0.9, 0, 0.2],
[0.3, 0.7, 0.1, 0.2, 0]
]
# binary variable indicating whether item i is in cluster k(=1) or not(=0),(i = 1,...N; k = 1,...K_num )
xi = [[model.add_var('xi({})({})'.format(i, k), var_type=BINARY) for i in range(1, N)] for k in range(1, K)]
# binary variable indicating whether item j is in cluster k(=1) or not(=0),(j = 1,...N; k = 1,...K_num )
xj = [[model.add_var('xj({})({})'.format(j, k), var_type=BINARY) for j in range(1, N)] for k in range(1, K)]
# binary variable indicating whether items i and j are in the same cluster k(=1) or not (=0)
y = [[[model.add_var('y({})({})({})'.format(i, j, k), var_type=BINARY) for i in range(1, N  1) for j in range(i + 1, N)]]for k in range(1, K)]
# objective function: maximize the total similarity
model.objective = maximize(
xsum(s[i][j] * y[i][j][k] for k in range(1, K1) for i in range(1, N  1) for j in range(i + 1, N)))
# constraint: each item to belong to one cluster at most
model.add_constr(xsum(xi[i][k] for k in range(1, K  1) for i in range(1,N1) ) <= 1)
for k in range(1, K1):
for j in range(1, N1):
for i in range(1, j):
model.add_constr(y <= xi)
for k in range(1, K  1):
for i in range(1, N  1):
for j in range(i+1, N1):
model.add_constr(y <= xj)
# model += y <= xj
# constraint: do not allow violation of the number of items in each cluster
for k in range(1, K  1):
model.add_constr(xsum(xi) == Mk)
# optimizing
model.optimize()
model.write("prova.lp")
# objective value
print(model.objective_value)
0

Hi Matteo,
You may have asked your question in the wrong forum. Your Python code is not gurobipy, but some other framework.
 Riley
0
Please sign in to leave a comment.
Comments
1 comment