-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHeatMapBioDesignFixed.py
180 lines (159 loc) · 8.01 KB
/
HeatMapBioDesignFixed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# User Requirement for all graphs: f1 to f2 (check)
# ******
# Constraint for all graphs: (Sunday)
# 1. Randomly choose a valve or other control component always be closed;
# 2. Or two valve or other control component cannot be opened together
from ConstraintMaker import createRandomConstraint
from MetricsGenerator import calculate_false_pos
from AlgorithmComparison import Vespa_search, control_search, netxsp_search, astar_search, findall_control_path
import random
import csv
import networkx as nx
import os
import pandas as pd
from networkx.drawing.nx_agraph import read_dot
def getfileList(targetfolderpath):
Allfile = {}
NodeList = os.listdir(targetfolderpath)
for node in NodeList:
new_path = targetfolderpath + "/" + str(node)
edgelist = os.listdir(new_path)
edgelist.sort()
Allfile[node] = edgelist
return Allfile
def buildFlowGraph(flow_graph_path):
# Build flow layer graph g
g = read_dot(flow_graph_path)
g = g.to_undirected()
for edge in g.edges:
g[edge[0]][edge[1]]['weight'] = int(g.get_edge_data(edge[0], edge[1])['weight'])
pos = nx.spring_layout(g)
return g, pos
def locateValveAndCOonFE(vco_path):
data = pd.read_csv(vco_path, header=None, sep=" ")
VCOFlist = data.values.tolist()
VCO2FEdictionary = {}
FE2VCOdictionary = {}
for VCO in VCOFlist:
VCO2FEdictionary[VCO[0]] = VCO[1:]
tup_temp = tuple(VCO[1:])
if tup_temp in FE2VCOdictionary.keys():
FE2VCOdictionary[tup_temp].append(VCO[0])
else:
FE2VCOdictionary[tup_temp] = [VCO[0]]
# data structure of FE2VCOdictionary is like {('F1','F2'): ['V1', 'V2'], ('F1','F3'): ['V3']}
return VCO2FEdictionary, FE2VCOdictionary
pos = {}
if __name__ == '__main__':
# Section loop
Result_list_metric = []
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 350, 400, 450, 500, 600, 700, 800]
for i in a:
Result_list_metric.append(f"I={i} flag")
for i in a:
Result_list_metric.append(f"I={i} runtime")
Result_list_cases = []
for i in range(3, 4):
Result_list_section = []
path = f"RandomCaseFiles/Section_{i}"
# Build a dictionary saved all edge info file names as value, keys are the nodes info
AllDirInOneSection = getfileList(path)
ColumnDetail = []
node_num = 0
constraint_path = f"RandomCaseFiles/Constraint_b{i}.csv"
ConstraintInfoAll = {}
ConstraintEmptyFlag = 0
if os.path.isfile(constraint_path):
df = pd.read_csv(constraint_path, index_col=0, header=None).squeeze("columns").to_dict()
constriant = []
for v in df.values():
constriant.append(eval(v))
ConstraintInfoAll = dict(zip(df.keys(), constriant))
ConstraintEmptyFlag = 1
# Nodes info loop
for NodeInfo in AllDirInOneSection.keys():
j = 0
node_num += 1
GraphListInfo = AllDirInOneSection[NodeInfo]
# Graph info loop
jUpperBound = len(AllDirInOneSection[NodeInfo])
while j < jUpperBound:
print(f"Sec{i}, Node{node_num}, Edge{int(j/3)+1}")
index = NodeInfo.index('_')
index1 = NodeInfo.find('_', index+1)
index2 = GraphListInfo[j].find('_')
index0 = GraphListInfo[j].index('|')
ColumnDetail.append(f"Sec{i}|{NodeInfo[:index1]}|{GraphListInfo[j][:index0]}_{GraphListInfo[j][index0+1:index2]}")
print(ColumnDetail[-1])
# remark = GraphListInfo[j][6]
control_graph_path = f"{path}/{NodeInfo}/{GraphListInfo[j]}"
flow_graph_path = f"{path}/{NodeInfo}/{GraphListInfo[j + 1]}"
valve_co_txt = f"{path}/{NodeInfo}/{GraphListInfo[j + 2]}"
# Build flow layer graph g
g, pos = buildFlowGraph(flow_graph_path)
# Create random constraints for each g_c -- control graph
# Build control layer graph g_c
g_c = read_dot(control_graph_path)
g_c = g_c.to_undirected()
ControlNodes = list(g_c.nodes())
for edge in g_c.edges:
g_c[edge[0]][edge[1]]['weight'] = int(g_c.get_edge_data(edge[0], edge[1])['weight'])
CPlength = 0
for node in ControlNodes:
if node[0] == 'c' and node[1] != 'o':
CPlength += 1
VandCOlength = len(ControlNodes) - CPlength
# Constraint bound for each section: [1, 5, 10, 15]
upboundconstraint = [1, 5, 10, 15]
ConstraintNum = random.randint(upboundconstraint[i-1], upboundconstraint[i])
# if no constraint list given, just generate a new one
if ConstraintEmptyFlag != 0:
ConstraintList = ConstraintInfoAll[ColumnDetail[-1]]
else:
ConstraintList = createRandomConstraint(ControlNodes, ConstraintNum, VandCOlength)
ConstraintInfoAll[ColumnDetail[-1]] = ConstraintList
# Create a dictionary shows the flow edge on which each valve and other control component locates
VCO2FEdictionary, FE2VCOdictionary = locateValveAndCOonFE(valve_co_txt)
# Algorithm comparison, set ur as ['f1', 'f2']
ur = ['f1', 'f2']
NetxSPTime, NetxSPPath, NetxSPLength = netxsp_search(g, ur)
AstarTime, AstarPath, AstarLength = astar_search(g, pos, ur)
NetxSPVCOList = control_search(NetxSPPath, FE2VCOdictionary)
AstarVCOList = control_search(AstarPath, FE2VCOdictionary)
NetxSPControlNodeList, NetxSPControlEdgeList = findall_control_path(NetxSPVCOList, g_c)
AstarControlNodeList, AstarControlEdgeList = findall_control_path(AstarVCOList, g_c)
PathLength = [NetxSPLength, AstarLength]
CtrlNodeLists = [NetxSPControlNodeList, AstarControlNodeList]
# Update the flow edge info after we get RandomConstraintList and use it in Vespa_search
VespaTime = []
flagFN = []
for ii in a:
g_Vespa = g.copy()
VespaTimeii, VespaPathii, VespaLengthii, flag, _, _, _ = Vespa_search(g_Vespa, g_c, pos, ConstraintList, VCO2FEdictionary,
FE2VCOdictionary, ur, ii)
# Find all valves and other control components which may be involved giving the searched path
VespaVCOList = control_search(VespaPathii, FE2VCOdictionary)
VespaControlNodeList, VespaControlEdgeList = findall_control_path(VespaVCOList, g_c)
# add middle products into list
VespaTime.append(format(VespaTimeii, '.5f'))
PathLength.append(VespaLengthii)
flagFN.append(flag)
CtrlNodeLists.append(VespaControlNodeList)
# Calculate the false positive for each algorithm
l, t, nodeslist = calculate_false_pos(PathLength, ConstraintList, CtrlNodeLists, g_c, flagFN, g, ur, VCO2FEdictionary)
l_currentcase = t[2:] + VespaTime
Result_list_section.append(l_currentcase)
j += 3
print()
f = open(constraint_path, 'w', newline='')
z = csv.writer(f)
for k, v in ConstraintInfoAll.items():
z.writerow([k, v])
f.close()
outcsvpath = f"TestCaseFiles/DataCollector/benchmark-{i}.csv"
dictionary = dict(zip(ColumnDetail, Result_list_section))
with open(outcsvpath, 'w', newline='') as f:
dataframe = pd.DataFrame.from_dict(dictionary, orient='index', columns=Result_list_metric)
dataframe.to_csv(outcsvpath)
print()
f.close()