'how to set constraint in ortools python

I'm trying to add a constraint to a MIP that I'm solving using ortools.

Here's my dataframe:

index, type, num_value
a, new, 1
b, new, 2
c, old, 1
d, old, 3
e, new, 2
f, old, 2

The objective is to find 3 items in the index column where the sum of num_value is maximized. However, now I want to add a constraint for 'type': out of the 3 items selected, one of them must be of type 'old'.

Here's my code so far:

solver = pywraplp.Solver('simple mip', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

index_to_int = {}
int_to_index = {}

cnt = 0
for i in df['index']:
    index_to_int[i] = cnt
    int_to_index[cnt] = i
    cnt += 1

selected = [solver.BoolVar('item'+str(c)) for c in range(cnt)]

solver.Maximize(solver.Sum((i.num_value)*selected[index_to_int[i.index]] for i in df.itertuples()))

solver.Add(solver.Sum(selected)==3)

solver.Add(solver.Sum([df.loc[selected, 'type'])>1)

status = solver.Solve()

I think the constraint for at least 1 of the type 'old' is wrong and therefore i'm not getting the desired result. How do I specify that with ortools?



Solution 1:[1]

You cannot use >, you need to use >=.. and I do not see 'old' appear in your last equation.

Solution 2:[2]

well we have to tag them with new varaibles like say df['old'] = np.where(df['type'].isin(['old']),1,0)

then we set a constrain on the listed column as : list_old = df['old'].to_list() constrain_01=[] for i in len(selected): constrain_01.append(selected[i]*list_old[i]) solver.Add(sum(constrain_01)>=1)## at least 1 means at minimum of 1 needs to be selected then you keep the other pieces like wise

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Laurent Perron
Solution 2 Indranil Ganguly