-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_bnlearn_graph.py
More file actions
391 lines (275 loc) · 10.4 KB
/
run_bnlearn_graph.py
File metadata and controls
391 lines (275 loc) · 10.4 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import random
import sys
import os
import multiprocessing as mp
from datetime import datetime
from src.testable_implications.ci_defs import algMap, algListGMP, algListCIBF, algListCI
from src.graph.classes.graph_defs import latentNodeType, directedEdgeType, bidirectedEdgeType
from src.inference.utils.set_utils import SetUtils as su
from src.inference.utils.graph_utils import GraphUtils as gu
from src.editor.sections.edges_section import EdgesSection
from src.editor.sections.nodes_section import NodesSection
from src.editor.classes.bidirected_options_parser import BidirectedOptionsParser
from src.editor.classes.latent_options_parser import LatentOptionsParser
from src.editor.input_parser import InputParser
from src.testable_implications.conditional_independencies import ConditionalIndependencies as cu
from src.experiment.experiment_utils import ExperimentUtils as eu
defaultTimeout = 60
ranges = range(0,10,1)
defaultLatentFranctionsToTest = list(map(lambda x: x/10.0, ranges))
numSampleOfFailure = 0
UOfFailure = 0
reportFileName = 'bnlearn_report'
fileName = ''
def parseGraph(fileContent):
parsedData = parseInput(fileContent)
if parsedData is None:
return None
return parsedData['graph']
def parseInput(fileContent):
parser = InputParser()
parser.sections = [getNodesSection(), getEdgesSection()]
parsedData = parser.parse(fileContent)
return parsedData
def getNodesSection():
nodeTypeParsers = {}
nodeTypeParsers[latentNodeType.id_] = LatentOptionsParser()
return NodesSection(nodeTypeParsers)
def getEdgesSection():
edgeTypeParsers = {}
edgeTypeParsers[bidirectedEdgeType.id_] = BidirectedOptionsParser()
return EdgesSection(edgeTypeParsers)
# an internal function to organize and finalize measured parameters
# def getFullParams(G, alg, CI, runtime, listCIBFParams):
# n = len(G.nodes)
# m = len(G.edges)
# md = len(list(filter(lambda e: e['type_'] == directedEdgeType.id_, G.edges)))
# mb = len(list(filter(lambda e: e['type_'] == bidirectedEdgeType.id_, G.edges)))
# CIsize = len(CI)
# s = 1
# if alg == algListCIBF.id_:
# Snum = listCIBFParams['Snum']
# Splusnum = listCIBFParams['Splusnum']
# s = listCIBFParams['s']
# elif alg == algListCI.id_:
# V = su.intersection(gu.topoSort(G), G.nodes, 'name')
# ACsizes = []
# for X in V:
# VleqX = V[:V.index(X)+1]
# GVleqX = gu.subgraph(G, VleqX)
# R = cu.C(GVleqX,X)
# ACsizes.append(len(R))
# if len(ACsizes) > 0:
# s = max(ACsizes)
# params = []
# if alg == algListGMP.id_:
# params = [n, m, md, mb, CIsize, runtime]
# elif alg == algListCIBF.id_:
# params = [n, m, md, mb, CIsize, runtime, s, Snum, Splusnum]
# elif alg == algListCI.id_:
# params = [n, m, md, mb, CIsize, runtime, s]
# return params
# def runAlgorithm(queue, G, alg, specs):
# orgVordered = specs['Vordered']
# if orgVordered is not None:
# Vordered = su.intersection(orgVordered, G.nodes, 'name')
# else:
# Vordered = None
# CI = queue.get()
# listCIBFParams = queue.get()
# if alg == algListGMP.id_:
# CIs = cu.ListGMP(G, G.nodes)
# elif alg == algListCIBF.id_:
# CIs = cu.ListCIBF(G, G.nodes, True, Vordered, listCIBFParams)
# elif alg == algListCI.id_:
# CIs = cu.ListCI(G, G.nodes, Vordered)
# CI.extend(CIs)
# queue.put(CI)
# queue.put(listCIBFParams)
# returns a pair: (status of sucessful run, measured params)
def tryRunAlgorithm(G, alg, timeout=defaultTimeout):
CI = []
listCIBFParams = {}
# use queue to pass values between processes
queue = mp.Queue()
queue.put(CI)
queue.put(listCIBFParams)
p = mp.Process(target=eu.runAlgorithm, args=(queue, G, alg, specs))
start = datetime.now()
p.start()
p.join(timeout=timeout)
if p.is_alive():
p.terminate()
p.join()
return (False, None)
end = datetime.now()
CI = queue.get()
listCIBFParams = queue.get()
runtime = end - start
params = eu.getFullParams(G, alg, CI, runtime, listCIBFParams)
return (True, params)
# def runAlgorithmAndMeasureParams(G, alg, specs):
# timeout = specs['timeout']
# CI = []
# listCIBFParams = {}
# # use queue to pass values between processes
# queue = mp.Queue()
# queue.put(CI)
# queue.put(listCIBFParams)
# p = mp.Process(target=runAlgorithm, args=(queue, G, alg, specs))
# start = datetime.now()
# p.start()
# p.join(timeout=timeout)
# if p.is_alive():
# p.terminate()
# p.join()
# currentAlg = algMap[alg]
# paramNames = currentAlg.params
# params = ['-'] * len(paramNames)
# return params
# end = datetime.now()
# CI = queue.get()
# listCIBFParams = queue.get()
# runtime = eu.roundToNearestSecond(end - start)
# params = getFullParams(G, alg, CI, runtime, listCIBFParams)
# return params
def testProjectedGraphs(G, alg, specs):
U = specs['U']
numBatches = specs['numBatches']
writeToCsv = specs['writeToCsv']
paramsCollectionText = []
paramsCollection = []
for i in range(numBatches):
Gp = eu.applyProjection(G, U)
params = eu.runAlgorithmAndMeasureParams(Gp, alg, specs)
paramsToStr = list(map(lambda n: str(n), params))
paramsBatchText = [paramsToStr]
paramsCollectionText.append(paramsBatchText)
paramsBatch = [params]
paramsCollection.append(paramsBatch)
for paramsBatchTextBlocks in paramsCollectionText:
print(' '.join(paramsBatchTextBlocks))
global fileName
suffix = ''
if alg == algListGMP.id_:
suffix = 'gmp'
elif alg == algListCIBF.id_:
suffix = 'lmp'
elif alg == algListCI.id_:
suffix = 'clmp'
if writeToCsv:
fullFileName = reportFileName + '_' + fileName.replace('.txt', '') + '_' + suffix
eu.writeParamsToCsv(fullFileName, paramsCollection)
else:
for paramsBatchTextBlocks in paramsCollectionText:
print(' '.join(paramsBatchTextBlocks))
def testProjectedGraphsBatch(G, alg, specs):
numBatches = specs['numBatches']
numDivisions = specs['numDivisions']
randomSeed = specs['randomSeed']
fixOrdering = specs['fixOrdering']
writeToCsv = specs['writeToCsv']
if fixOrdering:
Vordered = su.intersection(gu.topoSort(G), G.nodes, 'name')
specs['Vordered'] = Vordered
else:
specs['Vordered'] = None
paramsCollectionText = []
paramsCollection = []
offset = 0
if randomSeed is not None:
random.seed(randomSeed)
for i in range(numBatches):
paramsBatchText = []
paramsBatch = []
line = 'Running a batch of samples [' + str(i * numDivisions + 1) + ', ' + str((i+1) * numDivisions) + ']'
print(line)
for j in range(numDivisions):
U = j * 0.1 + offset
Gp = eu.applyProjection(G, U)
params = eu.runAlgorithmAndMeasureParams(Gp, alg, specs)
paramsToStr = list(map(lambda n: str(n), params))
paramsBatchText.extend(paramsToStr)
paramsBatch.append(params)
paramsCollectionText.append(paramsBatchText)
paramsCollection.append(paramsBatch)
global fileName
suffix = ''
if alg == algListGMP.id_:
suffix = 'gmp'
elif alg == algListCIBF.id_:
suffix = 'lmp'
elif alg == algListCI.id_:
suffix = 'clmp'
if writeToCsv:
fullFileName = reportFileName + '_' + fileName.replace('.txt', '') + '_' + suffix
eu.writeParamsToCsv(fullFileName, paramsCollection)
else:
for paramsBatchTextBlocks in paramsCollectionText:
print(' '.join(paramsBatchTextBlocks))
def tryTestProjectedGraphs(G, alg, numBatches, latentFractionsToTest=defaultLatentFranctionsToTest, timeout=defaultTimeout):
paramsCollection = []
global numSampleOfFailure
numSampleOfFailure = 1
for i in range(numBatches):
paramsCollection.append([])
for U in latentFractionsToTest:
Gp = eu.applyProjection(G, U)
(successfullyRun, params) = tryRunAlgorithm(Gp, alg, timeout)
if not successfullyRun:
global UOfFailure
UOfFailure = U
return False
paramsToStr = list(map(lambda n: str(n), params))
paramsCollection[i].extend(paramsToStr)
numSampleOfFailure = numSampleOfFailure + 1
for line in paramsCollection:
print(' '.join(line))
return True
if __name__ == '__main__':
if len(sys.argv) != 3:
print('Please specify 2 arguments: 1) the name of the task (\'gmp\', \'lmp\', or \'clmp\'), and 2) input file path (e.g., graphs/bif/sm/cancer.txt).')
sys.exit()
task = sys.argv[1]
filePath = sys.argv[2]
supportedTasks = ['gmp', 'lmp', 'clmp']
if task not in supportedTasks:
print('Please specify a valid task to run (\'gmp\', \'lmp\', or \'clmp\').')
sys.exit()
if task == 'gmp':
algorithm = algListGMP.id_
elif task == 'lmp':
algorithm = algListCIBF.id_
elif task == 'clmp':
algorithm = algListCI.id_
specs = {
'U': 0.2,
'numBatches': 10,
'numDivisions': 10,
# 'randomSeed': 0,
'randomSeed': None,
'timeout': 1 * 60 * 60,
# 'timeout': None,
'fixOrdering': True,
# 'writeToCsv': False
'writeToCsv': True
}
# UsToTest = [0.1]
try:
filePath = os.path.normpath(filePath)
path, file = os.path.split(filePath)
fileName = file
with open(filePath, 'r') as f:
fileContent = f.read()
G = parseGraph(fileContent)
if G is not None:
testProjectedGraphsBatch(G, algorithm, specs)
# testProjectedGraphs(G, algorithm, specs)
# if not tryTestProjectedGraphs(G, algorithm, numBatches, UsToTest, timeout):
# currentAlg = algMap[algorithm]
# line = currentAlg.name + ' timed out with U: ' + str(UOfFailure) + ' on sample ' + str(numSampleOfFailure) + '.'
# print(line)
f.close()
except IOError:
line = 'Please specify the input file correctly.'
print(line)