I am looking to minimize an objective function subject to certain constraints.
The function that I am looking to minimize is:
def distance_function(choice_matrix, distance_matrix, factory_distance):
hub_to_demand_distance = distance_matrix.dot(choice_matrix)
hub_factory_distance = pd.concat([hub_to_demand_distance, factory_distance],axis=1)
min_dist_to_demand = pd.DataFrame(hub_factory_distance.min(axis=1))
transposed_choice = choice_matrix.T
factory_to_hub = transposed_choice.dot(factory_distance)
total_distance = min_dist_to_demand.sum(axis=0)+factory_to_hub.sum(axis=0)
return total_distance
These are the constraints that I have defined:
cons = (
{'type':'ineq','fun': lambda f: 1-choice_matrix[0][0]-choice_matrix[1][0]},
{'type':'ineq','fun': lambda f: 1-choice_matrix[0][1]-choice_matrix[1][1]},
{'type':'ineq','fun': lambda f: 1-choice_matrix[0][2]-choice_matrix[1][2]},
{'type':'ineq','fun': lambda f: 1-choice_matrix[0][3]-choice_matrix[1][3]},
{'type':'eq','fun': lambda f: choice_matrix[0][0]+choice_matrix[0][1]+choice_matrix[0][2]+choice_matrix[0][3]-1},
{'type':'eq','fun': lambda f: choice_matrix[1][0]+choice_matrix[1][1]+choice_matrix[1][2]+choice_matrix[1][3]-1}
)
I have tried using Scipy Optimize to minimize the function as shown:
optimize.minimize(distance_function, choice_matrix, args=(distance_matrix, factory_distance),method='SLSQP',jac=None,constraints=cons)
When I run this, I get the following error:
ValueError: Dot product shape mismatch, (4, 4) vs (8,)
Could you please tell me:
Why this is happening and what needs to be done?
In the code that I shown, I have taken Choice Matrix to have 4 rows and 2 columns and hence I have manually defined 6 constraints (The constraint is the sum of the elements in each row should be lesser than or equal to 1. The other constraint is the sum of the elements in each column should be equal to 1) My question is if my Choice Matrix has 40 rows and 5 columns, is there a better way to define the constraints than manually entering 45 lines?
Thank you in advance for your help!