Skip to content
Snippets Groups Projects
Commit 605edb9c authored by Abd Errahmane Kiouche's avatar Abd Errahmane Kiouche :speech_balloon:
Browse files

Update PL_order/PL_order.py

parent 8fe7e804
No related branches found
No related tags found
No related merge requests found
import numpy as np
from cylp.cy import CyClpSimplex
from cylp.py.modeling.CyLPModel import CyLPModel, CyLPArray
from cylp.py.mip import SimpleNodeCompare
from cylp.cy.CyCgl import CyCglGomory, CyCglClique, CyCglKnapsackCover
from cylp.py.utils.sparseUtil import csr_matrixPlus
import networkx as nx
import numpy as np
import time
import sys
from scipy.sparse import csc_matrix
def load_graph(file_path, isdirected):
f = open(file_path,"r")
if isdirected :
G = nx.DiGraph() # the graph is directed
else:
G = nx.Graph() # the graph is undirected
lines = f.readlines()
for line in lines :
nodes = line.split('\t')
if int(nodes[0])!=int(nodes[1]):
#G.add_node(int(nodes[0]))
#G.add_node(int(nodes[1]))
G.add_edge(int(nodes[0]),int(nodes[1]))
return G
def PL_variables(G,t,pr):
all_paths = []
edges_dict ={} # key : edge , value : edge index
dict_paths ={} # key : edge , value : path index
# init
for n in G.nodes() :
for n2 in list(G.neighbors(n)):
dict_paths[(n,n2)] = []
#dict_paths[(n2,n)] = []
# Extract all simple path with length <= t
edges= list(G.edges())
i = 0
nodes = list(G.nodes())
for i1 in range(len(nodes)-1):
n = nodes[i1]
for i2 in range(i1+1,len(nodes)) :
l = nodes[i2]
paths = nx.all_simple_paths(G,source =n ,target = l, cutoff= t)
l_path = [ list(p) for p in map(nx.utils.pairwise, paths)]
for p in l_path :
all_paths.append(p)
if l in list(G.neighbors(n)) :
dict_paths[(n,l)].append(len(edges)+i)
dict_paths[(l,n)].append(len(edges)+i)
i+=1
print("The number of paths : " + str(len(all_paths)))
# creating edges dict
edges_dict ={}
i = 0
for e in edges :
u = e[0]
v = e[1]
edges_dict[(u,v)] = i
edges_dict[(v,u)] = i
i+=1
# creating pl variables
objs = [1 for i in range(len(edges))] + [0 for j in range(len(all_paths))]
lhs_ineqs_r = []
lhs_ineqs_c = []
lhs_ineqs_d = []
lhs_ineqs2_r = []
lhs_ineqs2_c = []
lhs_ineqs2_d = []
rhs_ineqs = []
rhs_ineqs2 = []
# inequality (3)
r_i = 0
path_index = len(edges)
for path in all_paths :
for e in path :
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(edges_dict[e])
lhs_ineqs_d.append(-1)
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(path_index)
lhs_ineqs_d.append(1)
rhs_ineqs.append(0)
r_i+=1
path_index+=1
# inequality (4)
for e in edges :
u,v = e
if v < u:
e =(v,u)
find =False
for i in dict_paths[e] :
find = True
lhs_ineqs_r.append(r_i)
lhs_ineqs_c.append(i)
lhs_ineqs_d.append(1)
if find :
r_i+=1
rhs_ineqs.append(1)
# inequality (5)
r_i2 = 0
for i in range(1,t+1):
for u in G.nodes():
find = False
for v in list(G.neighbors(u)):
pis = dict_paths[(u,v)]
if v < u :
pis = dict_paths[(v,u)]
for pi in pis:
if (len(all_paths[pi-len(edges)])<= i):
find = True
lhs_ineqs2_r.append(r_i2)
lhs_ineqs2_c.append(pi)
lhs_ineqs2_d.append(1)
if find :
r_i2+=1
prsn = pr[i]*len(list(G.neighbors(u)))
rhs_ineqs2.append(prsn)
row = np.array(lhs_ineqs_r)
col = np.array(lhs_ineqs_c)
data = np.array(lhs_ineqs_d)
lhs_ineqs = csc_matrix((data, (row, col)), shape=(r_i, len(objs)))
row = np.array(lhs_ineqs2_r)
col = np.array(lhs_ineqs2_c)
data = np.array(lhs_ineqs2_d)
lhs_ineqs2 = csc_matrix((data, (row, col)), shape=(r_i2, len(objs)))
return objs,lhs_ineqs,rhs_ineqs,lhs_ineqs2,rhs_ineqs2
def save_graph(G,filename):
file = open(file_name,"w")
for e in G.edges():
file.write(str(e[0])+'\t'+str(e[1])+ "\n")
file.close()
if __name__ == "__main__":
np.set_printoptions(threshold=sys.maxsize)
for i in range(30):
file_name = sys.argv[1] + str(i) + ".txt"
file_name_o = sys.argv[2] + str(i) + "_PL.txt"
algo = sys.argv[3]
G = load_graph( file_name , False)
t = 2
p = [0,0.0,0.5]
print ("Computing variables . . . ")
start = time.time()
objs,lhs_ineqs,rhs_ineqs,lhs_ineqs2,rhs_ineqs2 = PL_variables(G,t,p)
end = time.time()
print("Runtime : " + str( end-start ))
print("Solving the linear problem . . . ")
s = CyClpSimplex()
x = s.addVariable('x',len(objs),isInt=True)
#s.setInteger(x[0:len(objs)])
# Create coefficients and bounds
A = lhs_ineqs
a = CyLPArray(rhs_ineqs)
B = lhs_ineqs2
b = CyLPArray(rhs_ineqs2)
# Add constraints
s += A * x <= a
s += 0 <= x <= 1
s += B * x >= b
# Set the objective function
c = CyLPArray(objs)
s.objective = c * x
if ( algo == '1' ) :
print("Relaxed problem")
s.primal()
sol = s.primalVariableSolution['x']
else :
print("Integer linear programming")
s.copyInIntegerInformation(np.array ( s.nCols * [ True ], np.uint8 ))
cbcModel = s.getCbcModel ()
cbcModel.solve()
sol = cbcModel.primalVariableSolution['x']
end = time.time()
print("Runtime : " + str( end-start ))
data = np.asarray(sol)
score_list = list(data)
scores = score_list[0:len(list(G.edges()))]
edges = list(G.edges())
for i in range(len(scores)) :
if scores[i] < 0 :
scores[i] = 0
# sorting the edges
dict_edges_scores = {}
for i in range(len(scores)) :
dict_edges_scores[i] = scores[i]
sorted_edges = list({k: v for k, v in sorted(dict_edges_scores.items(), key=lambda item: item[1],reverse=True)}.keys())
file = open(file_name_o,"w")
for s in sorted_edges:
file.write(str(edges[s][0])+'\t'+str(edges[s][1])+'\t'+ str(dict_edges_scores[s])+ "\n")
file.close()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment