-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathakpu.py
190 lines (175 loc) · 7.28 KB
/
akpu.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
181
182
183
184
185
186
187
188
189
190
# implements a k-local search on the space of policies
from SetFactor import SetFactor, SetFactorProduct, ParetoSetFactorSumBProduct, BucketingPruning, ParetoSet
from Variable import Variable
from GraphUtils import FindOrder, ComputeLowerBound, BuildDomainGraph, FindPrefix
from chainID import sampleChainID
import resource, time, sys
from random import sample
def VariableElimination(Factors, Ordering, verbose=True, Approximate=True, maxtables=100):
""" Variable Elimination algorithm """
start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
tw = 0 # elimination width
wtw = 0 # weigthed width
delta_mem = 0
max_memory = 0
max_tables = 0
for var in Ordering:
if verbose:
print "-%6s\t" % var.label,
sys.stdout.flush()
B = []
for f in Factors:
if var in f.scope:
B.append(f)
for f in B:
Factors.remove(f)
if Approximate:
f = BucketingPruning(ParetoSetFactorSumBProduct(B,[var]),maxtables)
else:
f = ParetoSetFactorSumBProduct(B,[var])
max_tables = max(max_tables,f.num_tables)
Factors.append(f)
delta_mem = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - start_mem
max_memory = max(delta_mem, max_memory)
if verbose:
dim = "%dx%d" % (f.num_tables,f.dimension)
print "[width: %3d,\tdim: %10s,\tsize:%10d,\tmem: %d MB]" % (len(f.scope),dim,f.num_tables*f.dimension,delta_mem / 1000000.0)
tw = max(tw, len(f.scope))
wtw = max(wtw, f.dimension)
sys.stdout.flush()
f = Factors.pop()
while len(Factors) > 0:
fp = Factors.pop()
f = SetFactorProduct(f,fp)
max_tables = max(max_tables,f.num_tables)
return ParetoSet(f), tw, wtw, max_memory, max_tables
def main(args):
print "[Solve ID by local search]"
N,M,K,T=int(args[1]),int(args[2]),int(args[3]),int(args[4])
from Factor import Factor
# sample network
ChanceVars, DecVars, CPT, Strategy, Utility = sampleChainID(N,M)
print "SPU"
print
sys.stdout.flush()
SPUvalue, SPUit, SPUtime, SPUsize = run(ChanceVars, DecVars, CPT, Strategy, Utility, 1, False, 4*N, False)
print "Exact"
print
sys.stdout.flush()
sol = len(DecVars)*[ None ]
for n in range(len(DecVars)):
sol[n] = Factor([DecVars[n]], defaultValue=1.0/M)
kPUvalue, kPUit, kPUtime, kPUsize = run(ChanceVars, DecVars, CPT, sol, Utility, K, True, 2*N, False)
print "Approximate"
print
sys.stdout.flush()
sol2 = len(DecVars)*[ None ]
for n in range(len(DecVars)):
sol2[n] = Factor([DecVars[n]], defaultValue=1.0/M)
akPUvalue, akPUit, akPUtime, akPUsize = run(ChanceVars, DecVars, CPT, sol2, Utility, K, True, 2*N, True, T)
print
print "METHOD \tTIME(s) \tMAX SIZE \tVALUE"
print "SPU \t%10s\t%10s\t%g" % (str(SPUtime), str(SPUsize), SPUvalue)
print "Exact \t%10s\t%10s\t%g" % (str(kPUtime), str(kPUsize), kPUvalue)
print "Approximate\t%10s\t%10s\t%g" % (str(akPUtime), str(akPUsize), akPUvalue)
def run(ChanceVars, DecVars, CPT, Strategy, Utility, NSize, verbose=True, maxiterations=50, Approximate=True, numtables=100):
start = time.clock()
if verbose:
sys.stdout.flush()
N = len(Strategy)
OrderedVariables = DecVars + ChanceVars[::-1] # reverse topological order
# create chance setfactors
CFactors = []
for n in range(len(ChanceVars)):
f = SetFactor(CPT[n].scope)
f.addTable(CPT[n].values)
CFactors.append(f)
# create policy setfactors (uniform)
DFactors = []
for n in range(len(DecVars)):
f = SetFactor(Strategy[n].scope,defaultValue=1.0/DecVars[n].cardinality)
f.addTable(Strategy[n].values) # uncomment to allow intial point to be passed as argument
#f.addEmptyTable() # uncomment to for uniform as initial strategy
DFactors.append(f)
# create utility setfactor
UFactor = SetFactor(Utility.scope)
UFactor.addTable(Utility.values)
# baseline value (clearly non-optimal)
if verbose:
print "trying initial strategy...",
sys.stdout.flush()
stime = time.clock()
Z, tw, wtw, mem, max_tables = VariableElimination(CFactors+DFactors+[UFactor], OrderedVariables, False)
etime = time.clock() - stime
MEU = Z.tables[0][0]
if verbose:
print "done. \033[91m[%gs]\033[0m" % etime
print "Maximum memory usage: %d MB" % (mem/1000000.0)
print "Incumbent:", MEU
# maximum number of iterations
iteration = 0
previousMEU = 0.0
while iteration < maxiterations: # and previousMEU != MEU:
previousMEU = MEU
if verbose:
print "#%d" % (iteration + 1)
sys.stdout.flush()
# sample k decision variables
d = iteration % N
others = [i for i in range(N) if i != d]
ksearch = sample(others,NSize-1)+[d] # ensure all variables are selected at least once (with enough iterations)
# find best action for D[d]
if verbose:
print "optimizing for", ' '.join(DecVars[d].label for d in ksearch), "..."
sys.stdout.flush()
Policies = []
for d in ksearch:
P = SetFactor( [ DecVars[d] ], defaultValue=0.0 )
for j in range(DecVars[d].cardinality):
P.addEmptyTable()
P.tables[j][j] = 1.0
P.labels[j] = ' '+DecVars[d].label+'='+str(j)
Policies.append(P)
StaticPolicies = [ DFactors[n] for n in range(N) if n not in ksearch ]
# check expected value of new strategy
if verbose:
print "running variable elimination...",
sys.stdout.flush()
stime = time.clock()
Z, tw, wtw, mem, max_tables = VariableElimination(CFactors+StaticPolicies+Policies+[UFactor], OrderedVariables, False, Approximate, numtables)
etime = time.clock() - stime
assert(Z.num_tables == 1)
E = Z.tables[0][0]
if verbose:
print "done. \033[91m[%gs]\033[0m" % etime
print "Max Tables: %d" % max_tables
print "Memory usage: %d MB" % (mem/1000000.0)
## print "Effective weigthed treewidth:", wtw
print "Improvement:", (E-MEU)
if E > MEU:
# save best policies
policies = Z.labels[0].split()
#print Z.labels[0]
for p in policies:
var,value = p.split('=')
var = int(var[1:])
assert(var in ksearch)
value = int(value)
for i in range(Strategy[var].dimension):
Strategy[var].values[i] = 0.0
Strategy[var].values[value] = 1.0
MEU = E
iteration += 1
if verbose:
print "Incumbent:", MEU
totaltime = time.clock()-start
if verbose:
print "Total elapsed time: \033[91m%gs\033[0m" % totaltime
print "Iterations:", iteration
print "Best solution:", MEU
return MEU, iteration, totaltime, max_tables
if __name__ == '__main__':
if len(sys.argv) < 5:
print "Usage:", sys.argv[0], "num_vars num_var_cardinality neighborhood-size max-num-tables"
exit(0)
main(sys.argv)