-
Notifications
You must be signed in to change notification settings - Fork 2
/
run_random_mis_algo.py
executable file
·80 lines (60 loc) · 2.33 KB
/
run_random_mis_algo.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
#!/usr/bin/env python
import argparse
import glob
import os
import sys
import networkx as nx
import numpy as np
from utils.graph_funcs import graph_from_file, is_indset
from utils.helper_funcs import hamming_weight
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--graph', type=str, default=None,
help='glob path to the benchmark graph(s)')
parser.add_argument('--reps', type=int, default=1,
help='num reps')
args = parser.parse_args()
return args
def main():
args = parse_args()
all_graphs = glob.glob(args.graph)
savepath = 'benchmark_results/random_mis/'
if not os.path.isdir(savepath):
os.mkdir(savepath)
graphtype = args.graph.split('/')[1]
savepath += graphtype + '/'
if not os.path.isdir(savepath):
os.mkdir(savepath)
for graphfn in all_graphs:
graphname = graphfn.split('/')[-1].strip('.txt')
cur_savepath = savepath + '{}/'.format(graphname)
if not os.path.isdir(cur_savepath):
os.mkdir(cur_savepath)
G = graph_from_file(graphfn)
nq = len(G.nodes)
print('Loaded graph: {}, with {} nodes'.format(graphfn, nq))
for rep in range(1, args.reps+1):
cur_mis = ['0'] * len(G.nodes)
visited = [0] * len(G.nodes)
counter = 0
while sum(visited) < len(G.nodes):
unvisited = [i for i, val in enumerate(visited) if val == 0]
new_node = np.random.choice(unvisited)
neighbors = list(G.neighbors(new_node))
neighbor_vals = [int(cur_mis[n]) for n in neighbors]
if sum(neighbor_vals) == 0:
cur_mis[new_node] = '1'
visited[new_node] = 1
mis = ''.join(cur_mis)
valid = is_indset(''.join(cur_mis[::-1]), G)
if valid:
print('\tRep {}, found MIS with size {}'.format(rep, hamming_weight(mis)))
else:
raise Exception('MIS WAS NOT VALID!!')
savefn = 'random_mis_rep{}.txt'.format(rep)
with open(cur_savepath+savefn, 'w') as fn:
fn.write(graphfn + '\n')
fn.write(mis + '\n')
fn.write(str(hamming_weight(mis)) + '\n')
if __name__ == '__main__':
main()