In an optimisation problem, I have some relationships between variables i.e. they should take same values. I define a dataframe (called Master) that contains all the data and another dataframe (called Relationship) that in each row contains ID for variables that are related. For example, first row contains A1, A5, A3 and A9, so based on indexing in Master a constraint should ensure that x[1] = x[5] = x[3] = x[9]. This is explained in more detail in the MWE in comments. I thought it will be more a DataFrames related issue but I have not been able to get my head around this specific problem.
How could I define this constraint?
A not so nice way of applying the constraint could be to arbitrary change the IDs in the Master
where they are related, i.e. replace with same ID. And then use the unique
function of DataFrames to find the corresponding index and set them equal, but a more elegant solution should be possible.
using JuMP, Clp
function get_data()
Relationship = DataFrame(ID = ["A1","A2","A4"], LINK_1 = ["A5","A6","A10"],
LINK_2 = ["A3","A7",""], LINK_3 = ["A9","A11","A12"])
ID_t = collect(1:15)
ID = Vector{String}(undef,15)
for i in 1:15
ID[i]="A".*string(ID_t[i])
end
PRICE = rand(10.0:100.0,15)
Master = DataFrame(ID = ID,PRICE = PRICE)
return Relationship, Master
end
Relationship, Master = get_data()
Price = Master.PRICE
model = Model(Clp.Optimizer)
@variable(model,0<=x[i=1:length(Price)] <=1)
@constraint(model,con, sum(Price[i]*x[i] for i in 1:length(Price)) <=300)
@constraint(model,con2, sum(Price[i]*x[i] for i in 1:length(Price)) >=200)
# Create a dummy variable so that all elements in same rows in the Relationship dataframe
# take same values (in optimisation)
@variable(model,t[1:length(Relationship.ID)])
# Define the constraint that ensures that
#x[1] = x[5] = x[3] = x[9] = t[1]
#x[2] = x[6] = x[7] = x[11] = t[2]
#x[4] = x[10] = x[12] = t[3]
# Create a dictionary based on the Master dataframe
d = Dict([Master.ID[i] => Master.PRICE[i] for i in 1:nrow(Master)])
# For all rows in Relationship get references to the corresponding entries
# in Master to define the above constraint
# Warning some of the rows may have some blanks entries as in the example!