Convert values of gurobi.LineExpr to integers
AnsweredHi,
I have the following graph `G`
This is created using the following code
import networkx as nx
import matplotlib.pyplot as plt
G = nx.hoffman_singleton_graph()
pos = nx.spring_layout(G)
nx.draw(G, pos=pos)
nx.draw_networkx_labels(G=G, pos=pos)
plt.show()
`G` consists of 50 nodes. I only want to include 25 nodes. In additon, I only want to include the nodes (and edges) that maximizes the connectivity between node `A` (=5) and node `B` (=20).
I wrote the following script:
import numpy as np
import gurobipy as grb
from networkx.algorithms.connectivity import local_edge_connectivity
A = 5
B = 20
nodes = list(G.nodes)
n_nodes = len(nodes)
edges = nx.to_numpy_array(G, nodelist=nodes)
thresh_nodes = 20
model = grb.Model('mip_model')
F = model.addVars(n_nodes, vtype=grb.GRB.BINARY)
model.addConstr(grb.quicksum([F[n] for n in range(n_nodes))]) == thresh_nodes)
model.addConstr(F[nodes.index(A)] == 1)
model.addConstr(F[nodes.index(B)] == 1)
E = np.array([edges[n] * F[n] for n in range(n_nodes)])
model.setObjective(local_edge_connectivity(nx.from_numpy_array(A=E), A, B), grb.GRB.MAXIMIZE)
model.optimize()
This results in an error because `E` is a numpy.ndarray that consists of gurobi.LineExpr-elements and nx.from_numpy_array() cannot deal with this datatype. How do I make sure that the nx.from_numpy_array() uses the .X-values ({0, 1}) of `E`?
Thanks
-
Hi,
You cannot pass Gurobi Python objects to a NetworkX algorithm function "local_edge_connectivity". This function expects a NetworkX graph object as the first argument. You cannot create a NetworkX object using an adjacency matrix whose values are Gurobi decision variables.
You can find the local edge connectivity values between the nodes in graph \(G\) and use those values in whatever optimization problem you are trying to solve.
Best regards,
Maliheh
0 -
Hi,
Thank you for your reply. I understand that the "nx.from_numpy_array"-function doesn't accept Gurobi decision variables as input. However, is it possible to convert the values of the decision variables to a `numpy.array`?
0 -
However, is it possible to convert the values of the decision variables to a `numpy.array`?
Yes, you can convert the values to a numpy array but the issue is that you do not have access to values until the optimization problem is solved.
If you define variables as Var objects using Model.addVar() or Model.addVars() methods, you can create an array using the values of individual variables by querying the X attribute after the optimization problem is solved.
If you define variables as an MVar object using Model.addMVar(), querying the X attribute on an MVar object would result in a numpy array of decision values. However, the optimization problem needs to be solved before querying the values.Best regards,
Maliheh
0
Please sign in to leave a comment.
Comments
3 comments