Debian Codegraph @

test/original/bm_mdp.py

raw symbols SCIP
1 import collections
2 from collections import defaultdict
3 from fractions import Fraction
4
5 import pyperf
6
7 # Disable @profile if not defined.
8 try:
9 # Python 2
10 import __builtin__ as builtins
11 except ImportError:
12 # Python 3
13 import builtins
14
15 try:
16 builtins.profile
17 except AttributeError:
18 # No line profiler, provide a pass-through version
19 def profile(func):
20 return func
21
22 builtins.profile = profile
23
24
25 @profile
26 def topoSort(roots, getParents):
27 """Return a topological sorting of nodes in a graph.
28
29 roots - list of root nodes to search from
30 getParents - function which returns the parents of a given node
31 """
32
33 results = []
34 visited = set()
35
36 # Use iterative version to avoid stack limits for large datasets
37 stack = [(node, 0) for node in roots]
38 while stack:
39 current, state = stack.pop()
40 if state == 0:
41 # before recursing
42 if current not in visited:
43 visited.add(current)
44 stack.append((current, 1))
45 stack.extend((parent, 0) for parent in getParents(current))
46 else:
47 # after recursing
48 assert current in visited
49 results.append(current)
50 return results
51
52
53 @profile
54 def getDamages(L, A, D, B, stab, te):
55 x = (2 * L) // 5
56 x = ((x + 2) * A * B) // (D * 50) + 2
57 if stab:
58 x += x // 2
59 x = int(x * te)
60 return [(x * z) // 255 for z in range(217, 256)]
61
62
63 @profile
64 def getCritDist(L, p, A1, A2, D1, D2, B, stab, te):
65 p = min(p, Fraction(1))
66 norm = getDamages(L, A1, D1, B, stab, te)
67 crit = getDamages(L * 2, A2, D2, B, stab, te)
68
69 dist = defaultdict(Fraction)
70 for mult, vals in zip([1 - p, p], [norm, crit]):
71 mult /= len(vals)
72 for x in vals:
73 dist[x] += mult
74 return dist
75
76
77 @profile
78 def plus12(x):
79 return x + x // 8
80
81
82 stats_t = collections.namedtuple("stats_t", ["atk", "df", "speed", "spec"])
83 NOMODS = stats_t(0, 0, 0, 0)
84
85
86 fixeddata_t = collections.namedtuple(
87 "fixeddata_t", ["maxhp", "stats", "lvl", "badges", "basespeed"]
88 )
89 halfstate_t = collections.namedtuple(
90 "halfstate_t", ["fixed", "hp", "status", "statmods", "stats"]
91 )
92
93
94 @profile
95 def applyHPChange(hstate, change):
96 hp = min(hstate.fixed.maxhp, max(0, hstate.hp + change))
97 return hstate._replace(hp=hp)
98
99
100 @profile
101 def applyBadgeBoosts(badges, stats):
102 return stats_t(*[(plus12(x) if b else x) for x, b in zip(stats, badges)])
103
104
105 attack_stats_t = collections.namedtuple(
106 "attack_stats_t", ["power", "isspec", "stab", "te", "crit"]
107 )
108 attack_data = {
109 "Ember": attack_stats_t(40, True, True, 0.5, False),
110 "Dig": attack_stats_t(100, False, False, 1, False),
111 "Slash": attack_stats_t(70, False, False, 1, True),
112 "Water Gun": attack_stats_t(40, True, True, 2, False),
113 "Bubblebeam": attack_stats_t(65, True, True, 2, False),
114 }
115
116
117 @profile
118 def _applyActionSide1(state, act):
119 me, them, extra = state
120
121 if act == "Super Potion":
122 me = applyHPChange(me, 50)
123 return {(me, them, extra): Fraction(1)}
124
125 mdata = attack_data[act]
126 aind = 3 if mdata.isspec else 0
127 dind = 3 if mdata.isspec else 1
128 pdiv = 64 if mdata.crit else 512
129 dmg_dist = getCritDist(
130 me.fixed.lvl,
131 Fraction(me.fixed.basespeed, pdiv),
132 me.stats[aind],
133 me.fixed.stats[aind],
134 them.stats[dind],
135 them.fixed.stats[dind],
136 mdata.power,
137 mdata.stab,
138 mdata.te,
139 )
140
141 dist = defaultdict(Fraction)
142 for dmg, p in dmg_dist.items():
143 them2 = applyHPChange(them, -dmg)
144 dist[me, them2, extra] += p
145 return dist
146
147
148 @profile
149 def _applyAction(state, side, act):
150 if side == 0:
151 return _applyActionSide1(state, act)
152 else:
153 me, them, extra = state
154 dist = _applyActionSide1((them, me, extra), act)
155 return {(k[1], k[0], k[2]): v for k, v in dist.items()}
156
157
158 class Battle(object):
159
160 @profile
161 def __init__(self):
162 self.successors = {}
163 self.min = defaultdict(float)
164 self.max = defaultdict(lambda: 1.0)
165 self.frozen = set()
166
167 self.win = 4, True
168 self.loss = 4, False
169 self.max[self.loss] = 0.0
170 self.min[self.win] = 1.0
171 self.frozen.update([self.win, self.loss])
172
173 @profile
174 def _getSuccessorsA(self, statep):
175 st, state = statep
176 for action in ["Dig", "Super Potion"]:
177 yield (1, state, action)
178
179 @profile
180 def _applyActionPair(self, state, side1, act1, side2, act2, dist, pmult):
181 for newstate, p in _applyAction(state, side1, act1).items():
182 if newstate[0].hp == 0:
183 newstatep = self.loss
184 elif newstate[1].hp == 0:
185 newstatep = self.win
186 else:
187 newstatep = 2, newstate, side2, act2
188 dist[newstatep] += p * pmult
189
190 @profile
191 def _getSuccessorsB(self, statep):
192 st, state, action = statep
193 dist = defaultdict(Fraction)
194 for eact, p in [
195 ("Water Gun", Fraction(64, 130)),
196 ("Bubblebeam", Fraction(66, 130)),
197 ]:
198 priority1 = state[0].stats.speed + 10000 * (action == "Super Potion")
199 priority2 = state[1].stats.speed + 10000 * (action == "X Defend")
200
201 if priority1 > priority2:
202 self._applyActionPair(state, 0, action, 1, eact, dist, p)
203 elif priority1 < priority2:
204 self._applyActionPair(state, 1, eact, 0, action, dist, p)
205 else:
206 self._applyActionPair(state, 0, action, 1, eact, dist, p / 2)
207 self._applyActionPair(state, 1, eact, 0, action, dist, p / 2)
208
209 return {k: float(p) for k, p in dist.items() if p > 0}
210
211 @profile
212 def _getSuccessorsC(self, statep):
213 st, state, side, action = statep
214 dist = defaultdict(Fraction)
215 for newstate, p in _applyAction(state, side, action).items():
216 if newstate[0].hp == 0:
217 newstatep = self.loss
218 elif newstate[1].hp == 0:
219 newstatep = self.win
220 else:
221 newstatep = 0, newstate
222 dist[newstatep] += p
223 return {k: float(p) for k, p in dist.items() if p > 0}
224
225 @profile
226 def getSuccessors(self, statep):
227 try:
228 return self.successors[statep]
229 except KeyError:
230 st = statep[0]
231 if st == 0:
232 result = list(self._getSuccessorsA(statep))
233 else:
234 if st == 1:
235 dist = self._getSuccessorsB(statep)
236 elif st == 2:
237 dist = self._getSuccessorsC(statep)
238 result = sorted(dist.items(), key=lambda t: (-t[1], t[0]))
239 self.successors[statep] = result
240 return result
241
242 @profile
243 def getSuccessorsList(self, statep):
244 if statep[0] == 4:
245 return []
246 temp = self.getSuccessors(statep)
247 if statep[0] != 0:
248 temp = list(zip(*temp))[0] if temp else []
249 return temp
250
251 @profile
252 def evaluate(self, tolerance=0.15):
253 badges = 1, 0, 0, 0
254
255 starfixed = fixeddata_t(59, stats_t(40, 44, 56, 50), 11, NOMODS, 115)
256 starhalf = halfstate_t(starfixed, 59, 0, NOMODS, stats_t(40, 44, 56, 50))
257 charfixed = fixeddata_t(63, stats_t(39, 34, 46, 38), 26, badges, 65)
258 charhalf = halfstate_t(
259 charfixed, 63, 0, NOMODS, applyBadgeBoosts(badges, stats_t(39, 34, 46, 38))
260 )
261 initial_state = charhalf, starhalf, 0
262 initial_statep = 0, initial_state
263
264 dmin, dmax, frozen = self.min, self.max, self.frozen
265 stateps = topoSort([initial_statep], self.getSuccessorsList)
266
267 itercount = 0
268 while dmax[initial_statep] - dmin[initial_statep] > tolerance:
269 itercount += 1
270
271 for sp in stateps:
272 if sp in frozen:
273 continue
274
275 if sp[0] == 0:
276 # choice node
277 dmin[sp] = max(dmin[sp2] for sp2 in self.getSuccessors(sp))
278 dmax[sp] = max(dmax[sp2] for sp2 in self.getSuccessors(sp))
279 else:
280 dmin[sp] = sum(dmin[sp2] * p for sp2, p in self.getSuccessors(sp))
281 dmax[sp] = sum(dmax[sp2] * p for sp2, p in self.getSuccessors(sp))
282
283 if dmin[sp] >= dmax[sp]:
284 dmax[sp] = dmin[sp] = (dmin[sp] + dmax[sp]) / 2
285 frozen.add(sp)
286 return (dmax[initial_statep] + dmin[initial_statep]) / 2
287
288
289 @profile
290 def bench_mdp(loops):
291 expected = 0.89873589887
292 max_diff = 1e-6
293 range_it = range(loops)
294
295 t0 = pyperf.perf_counter()
296 for _ in range_it:
297 result = Battle().evaluate(0.192)
298 dt = pyperf.perf_counter() - t0
299
300 if abs(result - expected) > max_diff:
301 raise Exception(
302 "invalid result: got %s, expected %s "
303 "(diff: %s, max diff: %s)" % (result, expected, result - expected, max_diff)
304 )
305 return dt
306
307
308 if __name__ == "__main__":
309 import time
310
311 start = time.perf_counter()
312 runner = pyperf.Runner()
313 runner.metadata["description"] = "MDP benchmark"
314 bench_mdp(1)
315 stop = time.perf_counter()
316 print("Time elapsed: ", stop - start)