0

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:

  1. Why this is happening and what needs to be done?

  2. 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!

  • (1) I would start with a proper mathematical model. That makes it easier to understand what this is about. (2) minimize passes on a single vector x. Not a matrix. Check the dimensions of the argument choice_matrix in the distance function. (3) There may be better tools than scipy, but difficult to say without a proper mathematical model. – Erwin Kalvelagen Apr 01 '21 at 09:52
  • @ErwinKalvelagen: I understand from your point (2) that minimize passes on a single vector. However I have matrix. In that case, are there any better tools that you could point me to look at? – gatewaytovalhalla Apr 01 '21 at 10:01
  • I addressed that in (3). Note that you can reshape the vector inside the objective function. – Erwin Kalvelagen Apr 01 '21 at 10:25

0 Answers0