view org/lpsolve.org @ 22:8992278bf399 tip

typo corrected, thanks to a reader.
author Robert McIntyre <rlm@mit.edu>
date Sun, 20 Sep 2015 11:25:30 -0700
parents f88b7d2c25d9
children
line wrap: on
line source
1 #+title: Discovering Effective Pok\eacute{}mon Types Using Linear Optimization
2 #+author: Robert McIntyre & Dylan Holmes
3 #+EMAIL: rlm@mit.edu
4 #+description: Using Lpsolve to find effective pokemon types in clojure.
5 #+keywords: Pokemon, clojure, linear optimization, lp_solve, LpSolve
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
9 * Introduction
10 This post continues the [[./types.org][previous one]] about pok\eacute{}mon types.
11 Pok\eacute{}mon is a game in which adorable creatures battle each
12 other using fantastic attacks. It was made into a several gameboy
13 games that all share the same battle system. Every pok\eacute{}mon in
14 the gameboy game has one or two /types/, such as Ground, Fire, Water,
15 etc. Every pok\eacute{}mon attack has exactly one type. Certain
16 defending types are weak or strong to other attacking types. For
17 example, Water attacks are strong against Fire pok\eacute{}mon, while
18 Electric attacks are weak against Ground Pok\eacute{}mon. In the
19 games, attacks can be either twice as effective as normal (Water
20 vs. Fire), neutrally effective (Normal vs. Normal), half as effective
21 (Fire vs. Water), or not effective at all (Electric vs. Ground). We
22 represent these strengths and weaknesses as the numbers 2, 1,
23 $\frac{1}{2}$, and 0, and call them the /susceptance/ of one type to
24 another.
26 If a pokemon has two types, then the strengths and weakness of each
27 type are /multiplied/ together. Thus Electric (2x weak to Ground)
28 combined with Flying (immune to Ground (0x)) is immune to Ground.
29 Fire (2x weak to Water) combined with Water (1/2x resistant to Water)
30 is neutral to Water. If both types are resistant to another type, then
31 the combination is doubly-resistant (1/4x) to that type. If both types
32 are weak to a certain type then the combination is double-weak (4x) to
33 that type.
35 In the [[./types.org][previous post]], we used the best-first search algorithm to find
36 the most effective Pok\eacute{}mon type combinations. Afterwards, we
37 realized that we could transform this search problem into a /linear
38 optimization problem/. This conversion offers several advantages:
39 first, search algorithms are comparatively slow, whereas linear
40 optimization algorithms are extremely fast; second, it is difficult to
41 determine whether a search problem has any solution, whereas it is
42 straightforward to determine whether a linear optimization problem has
43 any solution; finally, because systems of linear equations are so
44 common, many programming languages have linear equation solvers
45 written for them.
47 In this article, we will:
48 - Solve a simple linear optimization problem in C :: We demonstrate
49 how to use the linear programming C library, =lp_solve=, to
50 solve a simple linear optimization problem.
51 - Incorporate a C library into Clojure :: We will show how we gave
52 Clojure access to the linear programming C library, =lp_solve=.
53 - Find effective Pokemon types using linear programming :: Building
54 on our earlier code, we answer some questions that were
55 impossible to answer using best-first search.
56 - Present our results :: We found some cool examples and learned a lot
57 about the pok\eacute{}mon type system as a whole.
60 ** Immortal Types
62 In the game, pok\eacute{}mon can have either one type or two types. If
63 this restriction is lifted, is there any combination of types that is
64 resistant to all types? I call such a combination an /Immortal Type/,
65 since if that type's pattern was repeated over and over again towards
66 infinity, the resulting type would be immune to all attack types.
68 * Linear Programming
70 Linear programming is the process of finding an optimal solution to a
71 linear equation of several variables which are constrained by some linear
72 inequalities.
74 ** The Farmer's Problem
76 Let's solve the Farmer's Problem, an example linear programming problem
77 borrowed from http://lpsolve.sourceforge.net/5.5/formulate.htm.
80 #+BEGIN_QUOTE
81 *The Farmer's Problem:* Suppose a farmer has 75 acres on which to
82 plant two crops: wheat and barley. To produce these crops, it costs
83 the farmer (for seed, fertilizer, etc.) $120 per acre for the wheat
84 and $210 per acre for the barley. The farmer has $15000 available for
85 expenses. But after the harvest, the farmer must store the crops while
86 awaiting favorable market conditions. The farmer has storage space
87 for 4000 bushels. Each acre yields an average of 110 bushels of wheat
88 or 30 bushels of barley. If the net profit per bushel of wheat (after
89 all expenses have been subtracted) is $1.30 and for barley is $2.00,
90 how should the farmer plant the 75 acres to maximize profit?
91 #+END_QUOTE
93 The Farmer's Problem is to maximize profit subject to constraints on
94 available farmland, funds for expenses, and storage space.
96 | | Wheat | Barley | Maximum total |
97 |----------+----------------------+---------------------+--------------|
98 | / | < | > | <> |
99 | Farmland | \(w\) acres | \(b\) acres | 75 acres |
100 | Expense | $120 per acre | $210 per acre | $15000 |
101 | Storage | 110 bushels per acre | 30 bushels per acre | 4000 bushels |
102 |----------+----------------------+---------------------+--------------|
103 | Profit | $1.30 per bushel | $2.00 per bushel | |
105 ** Solution using LP Solve
106 In a new file, =farmer.lp=, we list the variables and constraints
107 of our problem using LP Solve syntax.
109 #+begin_src lpsolve :tangle ../lp/farmer.lp
110 /* Maximize Total Profit */
111 max: +143 wheat +60 barley;
114 /* -------- Constraints --------*/
116 /* the farmer can't spend more money than he has */
117 +120 wheat +210 barley <= 15000;
119 /* the harvest has to fit in his storage space */
120 +110 wheat +30 barley <= 4000;
122 /* he can't use more acres than he owns */
123 +wheat +barley <= 75;
124 #+end_src
126 Running the =lp_solve= program on =farmer.lp= yields the following output.
128 #+begin_src sh :exports both :results scalar
129 lp_solve ~/proj/pokemon-types/lp/farmer.lp
130 #+end_src
132 #+results:
133 :
134 : Value of objective function: 6315.62500000
135 :
136 : Actual values of the variables:
137 : wheat 21.875
138 : barley 53.125
141 This shows that the farmer can maximize his profit by planting 21.875
142 of the available acres with wheat and the remaining 53.125 acres with
143 barley; by doing so, he will make $6315.62(5) in profit.
145 * Incorporating =lp_solve= into Clojure
147 There is a [[http://lpsolve.sourceforge.net/5.5/Java/README.html][Java API]] written by Juergen Ebert which enables Java
148 programs to use =lp_solve=. Although Clojure can use this Java API
149 directly, the interaction between Java, C, and Clojure is clumsy:
151 ** The Farmer's Problem in Clojure
153 We are going to solve the same problem involving wheat and barley,
154 that we did above, but this time using clojure and the =lp_solve= API.
156 #+name: intro
157 #+begin_src clojure :results silent
158 (ns pokemon.lpsolve
159 (:import lpsolve.LpSolve)
160 (:require pokemon.types)
161 ;;(:require incanter.core)
162 (:require rlm.map-utils))
163 #+end_src
165 The =lp_solve= Java interface is available from the same site as
166 =lp_solve= itself, http://lpsolve.sourceforge.net/ Using it is the
167 same as many other =C= programs. There are excellent instructions to
168 get set up. The short version is that you must call Java with
169 =-Djava.library.path=/path/to/lpsolve/libraries= and also add the
170 libraries to your export =LD_LIBRARY_PATH= if you are using Linux. For
171 example, in my =.bashrc= file, I have the line
172 =LD_LIBRARY_PATH=$HOME/roBin/lpsolve:$LD_LIBRARY_PATH=. If everything
173 is set-up correctly,
175 #+name: body
176 #+begin_src clojure :results verbatim :exports both
177 (import 'lpsolve.LpSolve)
178 #+end_src
180 #+results:
181 : lpsolve.LpSolve
183 should run with no problems.
185 ** Making a DSL to talk with LpSolve
186 *** Problems
187 Since we are using a =C= wrapper, we have to deal with manual memory
188 management for the =C= structures which are wrapped by the =LpSolve=
189 object. Memory leaks in =LpSolve= instances can crash the JVM, so it's
190 very important to get it right. Also, the Java wrapper follows the
191 =C= tradition closely and defines many =static final int= constants
192 for the different states of the =LpSolve= instance instead of using Java
193 enums. The calling convention for adding rows and columns to
194 the constraint matrix is rather complicated and must be done column by
195 column or row by row, which can be error prone. Finally, I'd like to
196 gather all the important output information from the =LpSolve= instance
197 into a final, immutable structure.
199 In summary, the issues I'd like to address are:
201 - reliable memory management
202 - functional interface to =LpSolve=
203 - intelligible, immutable output
205 To deal with these issues I'll create four functions for interfacing
206 with =LpSolve=
208 #+name: declares
209 #+begin_src clojure :results silent
210 (in-ns 'pokemon.lpsolve)
212 ;; deal with automatic memory management for LpSolve instance.
213 (declare linear-program)
215 ;; functional interface to LpSolve
216 (declare lp-solve)
218 ;; immutable output from lp-solve
219 (declare solve get-results)
220 #+end_src
223 *** Memory Management
225 Every instance of =LpSolve= must be manually garbage collected via a
226 call to =deleteLP=. I use a non-hygienic macro similar to =with-open=
227 to ensure that =deleteLP= is always called.
229 #+name: memory-management
230 #+begin_src clojure :results silent
231 (in-ns 'pokemon.lpsolve)
232 (defmacro linear-program
233 "solve a linear programming problem using LpSolve syntax.
234 within the macro, the variable =lps= is bound to the LpSolve instance."
235 [& statements]
236 (list 'let '[lps (LpSolve/makeLp 0 0)]
237 (concat '(try)
238 statements
239 ;; always free the =C= data structures.
240 '((finally (.deleteLp lps))))))
241 #+end_src
244 The macro captures the variable =lps= within its body, providing for a
245 convenient way to access the object using any of the methods of the
246 =LpSolve= API without having to worry about when to call
247 =deleteLP=.
249 *** Sensible Results
250 The =linear-program= macro deletes the actual =lps= object once it is
251 done working, so it's important to collect the important results and
252 add return them in an immutable structure at the end.
254 #+name: get-results
255 #+begin_src clojure :results silent
256 (in-ns 'pokemon.lpsolve)
258 (defrecord LpSolution
259 [objective-value
260 optimal-values
261 variable-names
262 solution
263 status
264 model])
266 (defn model
267 "Returns a textual representation of the problem suitable for
268 direct input to the =lp_solve= program (lps format)"
269 [#^LpSolve lps]
270 (let [target (java.io.File/createTempFile "lps" ".lp")]
271 (.writeLp lps (.getPath target))
272 (slurp target)))
274 (defn results
275 "Given an LpSolve object, solves the object and returns a map of the
276 essential values which compose the solution."
277 [#^LpSolve lps]
278 (locking lps
279 (let [status (solve lps)
280 number-of-variables (.getNcolumns lps)
281 optimal-values (double-array number-of-variables)
282 optimal-values (do (.getVariables lps optimal-values)
283 (seq optimal-values))
284 variable-names
285 (doall
286 ;; The doall is necessary since the lps object might
287 ;; soon be deleted.
288 (map
289 #(.getColName lps (inc %))
290 (range number-of-variables)))
291 model (model lps)]
292 (LpSolution.
293 (.getObjective lps)
294 optimal-values
295 variable-names
296 (zipmap variable-names optimal-values)
297 status
298 model))))
300 #+end_src
302 Here I've created an object called =LpSolution= which stores the
303 important results from a session with =lp_solve=. Of note is the
304 =model= function which returns the problem in a form that can be
305 solved by other linear programming packages.
307 *** Solution Status of an LpSolve Object
309 #+name: solve
310 #+begin_src clojure :results silent
311 (in-ns 'pokemon.lpsolve)
313 (defn static-integer?
314 "does the field represent a static integer constant?"
315 [#^java.lang.reflect.Field field]
316 (and (java.lang.reflect.Modifier/isStatic (.getModifiers field))
317 (integer? (.get field nil))))
319 (defn integer-constants [class]
320 (filter static-integer? (.getFields class)))
322 (defn constant-map
323 "Takes a class and creates a map of the static constant integer
324 fields with their names. This helps with C wrappers where they have
325 just defined a bunch of integer constants instead of enums."
326 [class]
327 (let [integer-fields (integer-constants class)]
328 (into (sorted-map)
329 (zipmap (map #(.get % nil) integer-fields)
330 (map #(.getName %) integer-fields)))))
332 (alter-var-root #'constant-map memoize)
334 (defn solve
335 "Solve an instance of LpSolve and return a string representing the
336 status of the computation. Will only solve a particular LpSolve
337 instance once."
338 [#^LpSolve lps]
339 ((constant-map LpSolve)
340 (.solve lps)))
342 #+end_src
344 The =.solve= method of an =LpSolve= object only returns an integer code
345 to specify the status of the computation. The =solve= method here
346 uses reflection to look up the actual name of the status code and
347 returns a more helpful status message that is also resistant to
348 changes in the meanings of the code numbers.
350 *** The Farmer Example in Clojure, Pass 1
352 Now we can implement a nicer version of the examples from the
353 [[http://lpsolve.sourceforge.net/][=lp\_solve= website]]. The following is a more or less
354 line-by-line translation of the Java code from that example.
356 #+name: farmer-example
357 #+begin_src clojure :results silent
358 (in-ns 'pokemon.lpsolve)
359 (defn farmer-example []
360 (linear-program
361 (results
362 (doto lps
363 ;; name the columns
364 (.setColName 1 "wheat")
365 (.setColName 2 "barley")
366 (.setAddRowmode true)
367 ;; row 1 : 120x + 210y <= 15000
368 (.addConstraintex 2
369 (double-array [120 210])
370 (int-array [1 2])
371 LpSolve/LE
372 15e3)
373 ;; row 2 : 110x + 30y <= 4000
374 (.addConstraintex 2
375 (double-array [110 30])
376 (int-array [1 2])
377 LpSolve/LE
378 4e3)
379 ;; ;; row 3 : x + y <= 75
380 (.addConstraintex 2
381 (double-array [1 1])
382 (int-array [1 2])
383 LpSolve/LE
384 75)
385 (.setAddRowmode false)
387 ;; add constraints
388 (.setObjFnex 2
389 (double-array [143 60])
390 (int-array [1 2]))
392 ;; set this as a maximization problem
393 (.setMaxim)))))
395 #+end_src
397 #+begin_src clojure :results output :exports both
398 (clojure.pprint/pprint
399 (:solution (pokemon.lpsolve/farmer-example)))
400 #+end_src
402 #+results:
403 : {"barley" 53.12499999999999, "wheat" 21.875}
406 And it works as expected!
408 *** The Farmer Example in Clojure, Pass 2
409 We don't have to worry about memory management anymore, and the farmer
410 example is about half as long as the example from the =LpSolve=
411 website, but we can still do better. Solving linear problems is all
412 about the constraint matrix $A$ , the objective function $c$, and the
413 right-hand-side $b$, plus whatever other options one cares to set for
414 the particular instance of =lp_solve=. Why not make a version of
415 =linear-program= that takes care of initialization?
419 #+name: lp-solve
420 #+begin_src clojure :results silent
421 (in-ns 'pokemon.lpsolve)
422 (defn initialize-lpsolve-row-oriented
423 "fill in an lpsolve instance using a constraint matrix =A=, the
424 objective function =c=, and the right-hand-side =b="
425 [#^lpsolve.LpSolve lps A b c]
426 ;; set the name of the last column to _something_
427 ;; this appears to be necessary to ensure proper initialization.
428 (.setColName lps (count c) (str "C" (count c)))
430 ;; This is the recommended way to "fill-in" an lps instance from the
431 ;; documentation. First, set row mode, then set the objective
432 ;; function, then set each row of the problem, and then turn off row
433 ;; mode.
434 (.setAddRowmode lps true)
435 (.setObjFnex lps (count c)
436 (double-array c)
437 (int-array (range 1 (inc (count c)))))
438 (dorun
439 (for [n (range (count A))]
440 (let [row (nth A n)
441 row-length (int (count row))]
442 (.addConstraintex lps
443 row-length
444 (double-array row)
445 (int-array (range 1 (inc row-length)))
446 LpSolve/LE
447 (double (nth b n))))))
448 (.setAddRowmode lps false)
449 lps)
452 (defmacro lp-solve
453 "by default:,
454 minimize (* c x), subject to (<= (* A x) b),
455 using continuous variables. You may set any number of
456 other options as in the LpSolve API."
457 [A b c & lp-solve-forms]
458 ;; assume that A is a vector of vectors
459 (concat
460 (list 'linear-program
461 (list 'initialize-lpsolve-row-oriented 'lps A b c))
462 `~lp-solve-forms))
463 #+end_src
465 Now, we can use a much more functional approach to solving the
466 farmer's problem:
468 #+name: better-farmer
469 #+begin_src clojure :results silent
470 (in-ns 'pokemon.lpsolve)
471 (defn better-farmer-example []
472 (lp-solve [[120 210]
473 [110 30]
474 [1 1]]
475 [15000
476 4000
477 75]
478 [143 60]
479 (.setColName lps 1 "wheat")
480 (.setColName lps 2 "barley")
481 (.setMaxim lps)
482 (results lps)))
483 #+end_src
485 #+begin_src clojure :exports both :results verbatim
486 (vec (:solution (pokemon.lpsolve/better-farmer-example)))
487 #+end_src
489 #+results:
490 : [["barley" 53.12499999999999] ["wheat" 21.875]]
492 Notice that both the inputs to =better-farmer-example= and the results
493 are immutable.
495 * Using LpSolve to find Immortal Types
496 ** Converting the Pok\eacute{}mon problem into a linear form
497 How can the original question about pok\eacute{}mon types be converted
498 into a linear problem?
500 Pokemon types can be considered to be vectors of numbers representing
501 their susceptances to various attacking types, so Water might look
502 something like this.
504 #+begin_src clojure :results scalar :exports both
505 (:water (pokemon.types/defense-strengths))
506 #+end_src
508 #+results:
509 : [1 0.5 0.5 2 2 0.5 1 1 1 1 1 1 1 1 1 1 0.5]
511 Where the numbers represent the susceptibility of Water to the
512 attacking types in the following order:
514 #+begin_src clojure :results output :exports both
515 (clojure.pprint/pprint
516 (pokemon.types/type-names))
517 #+end_src
519 #+results:
520 #+begin_example
521 [:normal
522 :fire
523 :water
524 :electric
525 :grass
526 :ice
527 :fighting
528 :poison
529 :ground
530 :flying
531 :psychic
532 :bug
533 :rock
534 :ghost
535 :dragon
536 :dark
537 :steel]
538 #+end_example
541 So, for example, Water is resistant (x0.5) against Fire, which is
542 the second element in the list.
544 To combine types, these sorts of vectors are multiplied together
545 pair-wise to yield the resulting combination.
547 Unfortunately, we need some way to add two type vectors together
548 instead of multiplying them if we want to solve the problem with
549 =lp_solve=. Taking the log of the vector does just the trick.
551 If we make a matrix with each column being the log (base 2) of the
552 susceptance of each type, then finding an immortal type corresponds to
553 setting each constraint (the $b$ vector) to -1 (since log_2(1/2) = -1)
554 and setting the constraint vector $c$ to all ones, which means that we
555 want to find the immortal type which uses the least amount of types.
557 #+name: pokemon-lp
558 #+begin_src clojure :results silent
559 (in-ns 'pokemon.lpsolve)
561 (defn log-clamp-matrix [matrix]
562 ;; we have to clamp the Infinities to a more reasonable negative
563 ;; value because lp_solve does not play well with infinities in its
564 ;; constraint matrix.
565 (map (fn [row] (map #(if (= Double/NEGATIVE_INFINITY %) -1e3 %)
566 (map #(/ (Math/log %) (Math/log 2)) row)))
567 (apply mapv vector ;; transpose
568 matrix)))
570 ;; constraint matrices
571 (defn log-defense-matrix []
572 (log-clamp-matrix
573 (doall (map (pokemon.types/defense-strengths)
574 (pokemon.types/type-names)))))
576 (defn log-attack-matrix []
577 (apply mapv vector (log-defense-matrix)))
579 ;; target vectors
580 (defn all-resistant []
581 (doall (map (constantly -1) (pokemon.types/type-names))))
583 (defn all-weak []
584 (doall (map (constantly 1) (pokemon.types/type-names))))
586 (defn all-neutral []
587 (doall (map (constantly 0) (pokemon.types/type-names))))
589 ;; objective functions
590 (defn number-of-types []
591 (doall (map (constantly 1) (pokemon.types/type-names))))
593 (defn set-constraints
594 "sets all the constraints for an lpsolve instance to the given
595 constraint. =constraint= here is one of the LpSolve constants such
596 as LpSolve/EQ."
597 [#^LpSolve lps constraint]
598 (dorun (map (fn [index] (.setConstrType lps index constraint))
599 ;; ONE based indexing!!!
600 (range 1 (inc (.getNrows lps))))))
602 (defn set-discrete
603 "sets every variable in an lps problem to be a discrete rather than
604 continuous variable"
605 [#^LpSolve lps]
606 (dorun (map (fn [index] (.setInt lps index true))
607 ;; ONE based indexing!!!
608 (range 1 (inc (.getNcolumns lps))))))
610 (defn set-variable-names
611 "sets the variable names of the problem given a vector of names"
612 [#^LpSolve lps names]
613 (dorun
614 (keep-indexed
615 (fn [index name]
616 (.setColName lps (inc index) (str name)))
617 ;; ONE based indexing!!!
618 names)))
620 (defn poke-solve
621 ([poke-matrix target objective-function constraint min-num-types]
622 ;; must have at least one type
623 (let [poke-matrix
624 (concat poke-matrix
625 [(map (constantly 1)
626 (range (count (first poke-matrix))))])
627 target (concat target [min-num-types])]
628 (lp-solve poke-matrix target objective-function
629 (set-constraints lps constraint)
630 ;; must have more than min-num-types
631 (.setConstrType lps (count target) LpSolve/GE)
632 (set-discrete lps)
633 (set-variable-names lps (pokemon.types/type-names))
634 (results lps))))
635 ([poke-matrix target objective-function constraint]
636 ;; at least one type
637 (poke-solve poke-matrix target objective-function constraint 1)))
639 (defn solution
640 "If the results of an lpsolve operation are feasible, returns the
641 results. Otherwise, returns the error."
642 [results]
643 (if (not (= (:status results) "OPTIMAL"))
644 (:status results)
645 (:solution results)))
646 #+end_src
648 With this, we are finally able to get some results.
650 ** Results
651 #+name: results
652 #+begin_src clojure :results silent
653 (in-ns 'pokemon.lpsolve)
655 (defn best-defense-type
656 "finds a type combination which is resistant to all attacks."
657 []
658 (poke-solve
659 (log-defense-matrix) (all-resistant) (number-of-types) LpSolve/LE))
661 (defn worst-attack-type
662 "finds the attack type which is not-very-effective against all pure
663 defending types (each single defending type is resistant to this
664 attack combination"
665 []
666 (poke-solve
667 (log-attack-matrix) (all-resistant) (number-of-types) LpSolve/LE))
669 (defn worst-defense-type
670 "finds a defending type that is weak to all single attacking types."
671 []
672 (poke-solve
673 (log-defense-matrix) (all-weak) (number-of-types) LpSolve/GE))
675 (defn best-attack-type
676 "finds an attack type which is super effective against all single
677 defending types"
678 []
679 (poke-solve
680 (log-attack-matrix) (all-weak) (number-of-types) LpSolve/GE))
682 (defn solid-defense-type
683 "finds a defense type which is either neutral or resistant to all
684 single attacking types"
685 []
686 (poke-solve
687 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/LE))
689 (defn solid-attack-type
690 "finds an attack type which is either neutral or super-effective to
691 all single attacking types."
692 []
693 (poke-solve
694 (log-attack-matrix) (all-neutral) (number-of-types) LpSolve/GE))
696 (defn weak-defense-type
697 "finds a defense type which is either neutral or weak to all single
698 attacking types"
699 []
700 (poke-solve
701 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/GE))
703 (defn neutral-defense-type
704 "finds a defense type which is perfectly neutral to all attacking
705 types."
706 []
707 (poke-solve
708 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/EQ))
710 #+end_src
712 *** Strongest Attack/Defense Combinations
714 #+begin_src clojure :results output :exports both
715 (clojure.pprint/pprint
716 (pokemon.lpsolve/solution (pokemon.lpsolve/best-defense-type)))
717 #+end_src
719 #+results:
720 #+begin_example
721 {":normal" 0.0,
722 ":ground" 1.0,
723 ":poison" 2.0,
724 ":flying" 1.0,
725 ":fighting" 0.0,
726 ":dragon" 0.0,
727 ":fire" 0.0,
728 ":dark" 1.0,
729 ":ice" 0.0,
730 ":steel" 1.0,
731 ":ghost" 0.0,
732 ":electric" 0.0,
733 ":bug" 0.0,
734 ":psychic" 0.0,
735 ":grass" 0.0,
736 ":water" 2.0,
737 ":rock" 0.0}
738 #+end_example
740 # #+results-old:
741 # : [[":normal" 0.0] [":ground" 1.0] [":poison" 0.0] [":flying" 1.0] [":fighting" 0.0] [":dragon" 1.0] [":fire" 0.0] [":dark" 0.0] [":ice" 0.0] [":steel" 2.0] [":ghost" 1.0] [":electric" 0.0] [":bug" 0.0] [":psychic" 0.0] [":grass" 0.0] [":water" 2.0] [":rock" 0.0]]
744 This is the immortal type combination we've been looking for. By
745 combining Steel, Water, Poison, and three types which each have complete
746 immunities to various other types, we've created a type that is resistant to
747 all attacking types.
749 #+begin_src clojure :results output :exports both
750 (clojure.pprint/pprint
751 (pokemon.types/susceptibility
752 [:poison :poison :water :water :steel :ground :flying :dark]))
753 #+end_src
755 #+results:
756 #+begin_example
757 {:water 1/2,
758 :psychic 0,
759 :dragon 1/2,
760 :fire 1/2,
761 :ice 1/2,
762 :grass 1/2,
763 :ghost 1/4,
764 :poison 0,
765 :flying 1/2,
766 :normal 1/2,
767 :rock 1/2,
768 :electric 0,
769 :ground 0,
770 :fighting 1/2,
771 :dark 1/4,
772 :steel 1/8,
773 :bug 1/8}
774 #+end_example
776 # #+results-old:
777 # : {:water 1/4, :psychic 1/4, :dragon 1/2, :fire 1/2, :ice 1/2, :grass 1/2, :ghost 1/2, :poison 0, :flying 1/4, :normal 0, :rock 1/4, :electric 0, :ground 0, :fighting 0, :dark 1/2, :steel 1/16, :bug 1/16}
780 Cool!
782 #+begin_src clojure :results output :exports both
783 (clojure.pprint/pprint
784 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-defense-type)))
785 #+end_src
787 #+results:
788 #+begin_example
789 {":normal" 0.0,
790 ":ground" 0.0,
791 ":poison" 0.0,
792 ":flying" 0.0,
793 ":fighting" 0.0,
794 ":dragon" 0.0,
795 ":fire" 0.0,
796 ":dark" 1.0,
797 ":ice" 0.0,
798 ":steel" 0.0,
799 ":ghost" 1.0,
800 ":electric" 0.0,
801 ":bug" 0.0,
802 ":psychic" 0.0,
803 ":grass" 0.0,
804 ":water" 0.0,
805 ":rock" 0.0}
806 #+end_example
808 Dark and Ghost are the best dual-type combo, and are resistant or
809 neutral to all types.
811 #+begin_src clojure :results output :exports both
812 (clojure.pprint/pprint
813 (pokemon.types/old-school
814 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-defense-type))))
815 #+end_src
817 #+results:
818 #+begin_example
819 {":normal" 0.0,
820 ":ground" 0.0,
821 ":poison" 0.0,
822 ":flying" 0.0,
823 ":fighting" 0.0,
824 ":dragon" 0.0,
825 ":fire" 0.0,
826 ":ice" 0.0,
827 ":ghost" 1.0,
828 ":electric" 0.0,
829 ":bug" 0.0,
830 ":psychic" 1.0,
831 ":grass" 0.0,
832 ":water" 0.0,
833 ":rock" 0.0}
834 #+end_example
836 Ghost and Psychic are a powerful dual type combo in the original games,
837 due to a glitch which made Psychic immune to Ghost type attacks, even
838 though the game claims that Ghost is strong against Psychic.
840 #+begin_src clojure :results verbatim :exports both
841 (pokemon.lpsolve/solution (pokemon.lpsolve/best-attack-type))
842 #+end_src
844 #+results:
845 : INFEASIBLE
847 #+begin_src clojure :results verbatim :exports both
848 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-attack-type))
849 #+end_src
851 #+results:
852 : INFEASIBLE
855 #+begin_src clojure :results verbatim :exports both
856 (pokemon.types/old-school
857 (pokemon.lpsolve/solution (pokemon.lpsolve/best-attack-type)))
858 #+end_src
860 #+results:
861 : INFEASIBLE
864 #+begin_src clojure :results output :exports both
865 (clojure.pprint/pprint
866 (pokemon.types/old-school
867 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-attack-type))))
868 #+end_src
870 #+results:
871 #+begin_example
872 {":normal" 0.0,
873 ":ground" 0.0,
874 ":poison" 0.0,
875 ":flying" 0.0,
876 ":fighting" 0.0,
877 ":dragon" 1.0,
878 ":fire" 0.0,
879 ":ice" 0.0,
880 ":ghost" 0.0,
881 ":electric" 0.0,
882 ":bug" 0.0,
883 ":psychic" 0.0,
884 ":grass" 0.0,
885 ":water" 0.0,
886 ":rock" 0.0}
887 #+end_example
889 The best attacking type combination is Dragon from the original games.
890 It is neutral against all the original types except for Dragon, which
891 it is strong against. There is no way to make an attacking type that
892 is strong against every type, or even one that is strong or neutral
893 against every type, in the new games.
896 *** Weakest Attack/Defense Combinations
898 #+begin_src clojure :results output :exports both
899 (clojure.pprint/pprint
900 (pokemon.types/old-school
901 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-attack-type))))
902 #+end_src
904 #+results:
905 #+begin_example
906 {":normal" 5.0,
907 ":ground" 0.0,
908 ":poison" 0.0,
909 ":flying" 0.0,
910 ":fighting" 0.0,
911 ":dragon" 0.0,
912 ":fire" 1.0,
913 ":ice" 2.0,
914 ":ghost" 1.0,
915 ":electric" 1.0,
916 ":bug" 1.0,
917 ":psychic" 0.0,
918 ":grass" 3.0,
919 ":water" 2.0,
920 ":rock" 0.0}
921 #+end_example
923 # #+results-old:
924 # : [[":normal" 5.0] [":ground" 1.0] [":poison" 0.0] [":flying" 0.0] [":fighting" 2.0] [":dragon" 0.0] [":fire" 0.0] [":ice" 4.0] [":ghost" 1.0] [":electric" 4.0] [":bug" 0.0] [":psychic" 0.0] [":grass" 0.0] [":water" 1.0] [":rock" 1.0]]
926 #+begin_src clojure :results output :exports both
927 (clojure.pprint/pprint
928 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-attack-type)))
929 #+end_src
931 #+results:
932 #+begin_example
933 {":normal" 4.0,
934 ":ground" 1.0,
935 ":poison" 1.0,
936 ":flying" 0.0,
937 ":fighting" 1.0,
938 ":dragon" 0.0,
939 ":fire" 0.0,
940 ":dark" 0.0,
941 ":ice" 4.0,
942 ":steel" 0.0,
943 ":ghost" 1.0,
944 ":electric" 3.0,
945 ":bug" 0.0,
946 ":psychic" 1.0,
947 ":grass" 1.0,
948 ":water" 1.0,
949 ":rock" 2.0}
950 #+end_example
952 # #+results-old:
953 # : [[":normal" 4.0] [":ground" 1.0] [":poison" 1.0] [":flying" 0.0] [":fighting" 2.0] [":dragon" 0.0] [":fire" 0.0] [":dark" 0.0] [":ice" 5.0] [":steel" 0.0] [":ghost" 1.0] [":electric" 5.0] [":bug" 0.0] [":psychic" 1.0] [":grass" 0.0] [":water" 1.0] [":rock" 2.0]]
956 This is an extremely interesting type combination, in that it uses
957 quite a few types.
959 #+begin_src clojure :results verbatim :exports both
960 (reduce + (vals (:solution (pokemon.lpsolve/worst-attack-type))))
961 #+end_src
963 #+results:
964 : 20.0
966 20 types is the /minimum/ number of types before the attacking
967 combination is not-very-effective or worse against all defending
968 types. This would probably have been impossible to discover using
969 best-first search, since it involves such an intricate type
970 combination.
972 It's so interesting that it takes 20 types to make an attack type that
973 is weak to all types that the combination merits further
974 investigation.
976 Unfortunately, all of the tools that we've written so far are focused
977 on defense type combinations. However, it is possible to make every
978 tool attack-oriented via a simple macro.
980 #+name: attack-oriented
981 #+begin_src clojure :results silent
982 (in-ns 'pokemon.lpsolve)
984 (defmacro attack-mode [& forms]
985 `(let [attack-strengths# pokemon.types/attack-strengths
986 defense-strengths# pokemon.types/defense-strengths]
987 (binding [pokemon.types/attack-strengths
988 defense-strengths#
989 pokemon.types/defense-strengths
990 attack-strengths#]
991 ~@forms)))
992 #+end_src
994 Now all the tools from =pokemon.types= will work for attack
995 combinations.
997 #+begin_src clojure :results output :exports both
998 (clojure.pprint/pprint
999 (pokemon.types/susceptibility [:water]))
1000 #+end_src
1002 #+results:
1003 #+begin_example
1004 {:water 1/2,
1005 :psychic 1,
1006 :dragon 1,
1007 :fire 1/2,
1008 :ice 1/2,
1009 :grass 2,
1010 :ghost 1,
1011 :poison 1,
1012 :flying 1,
1013 :normal 1,
1014 :rock 1,
1015 :electric 2,
1016 :ground 1,
1017 :fighting 1,
1018 :dark 1,
1019 :steel 1/2,
1020 :bug 1}
1021 #+end_example
1024 #+begin_src clojure :results output :exports both
1025 (clojure.pprint/pprint
1026 (pokemon.lpsolve/attack-mode
1027 (pokemon.types/susceptibility [:water])))
1028 #+end_src
1030 #+results:
1031 #+begin_example
1032 {:water 1/2,
1033 :psychic 1,
1034 :dragon 1/2,
1035 :fire 2,
1036 :ice 1,
1037 :grass 1/2,
1038 :ghost 1,
1039 :poison 1,
1040 :flying 1,
1041 :normal 1,
1042 :rock 2,
1043 :electric 1,
1044 :ground 2,
1045 :fighting 1,
1046 :dark 1,
1047 :steel 1,
1048 :bug 1}
1049 #+end_example
1051 Now =pokemon.types/susceptibility= reports the /attack-type/
1052 combination's effectiveness against other types.
1054 The 20 type combo achieves its goal in a very clever way.
1056 First, it weakens its effectiveness to other types at the expense of
1057 making it very strong against flying.
1059 #+begin_src clojure :results output :exports both
1060 (clojure.pprint/pprint
1061 (pokemon.lpsolve/attack-mode
1062 (pokemon.types/susceptibility
1063 [:normal :normal :normal :normal
1064 :ice :ice :ice :ice
1065 :electric :electric :electric
1066 :rock :rock])))
1067 #+end_src
1069 #+results:
1070 #+begin_example
1071 {:water 1/2,
1072 :psychic 1,
1073 :dragon 2,
1074 :fire 1/4,
1075 :ice 1/4,
1076 :grass 2,
1077 :ghost 0,
1078 :poison 1,
1079 :flying 512,
1080 :normal 1,
1081 :rock 1/16,
1082 :electric 1/8,
1083 :ground 0,
1084 :fighting 1/4,
1085 :dark 1,
1086 :steel 1/1024,
1087 :bug 4}
1088 #+end_example
1090 Then, it removes it's strengths against Flying, Normal, and Fighting
1091 by adding Ghost and Ground.
1093 #+begin_src clojure :results output :exports both
1094 (clojure.pprint/pprint
1095 (pokemon.lpsolve/attack-mode
1096 (pokemon.types/susceptibility
1097 [:normal :normal :normal :normal
1098 :ice :ice :ice :ice
1099 :electric :electric :electric
1100 :rock :rock
1101 ;; Spot resistances
1102 :ghost :ground])))
1103 #+end_src
1105 #+results:
1106 #+begin_example
1107 {:water 1/2,
1108 :psychic 2,
1109 :dragon 2,
1110 :fire 1/2,
1111 :ice 1/4,
1112 :grass 1,
1113 :ghost 0,
1114 :poison 2,
1115 :flying 0,
1116 :normal 0,
1117 :rock 1/8,
1118 :electric 1/4,
1119 :ground 0,
1120 :fighting 1/4,
1121 :dark 1/2,
1122 :steel 1/1024,
1123 :bug 2}
1124 #+end_example
1126 Adding the pair Psychic and Fighting takes care of its strength
1127 against Psychic and makes it ineffective against Dark, which is immune
1128 to Psychic.
1130 Adding the pair Grass and Poison makes takes care of its strength
1131 against poison and makes it ineffective against Steel, which is immune
1132 to poison.
1134 #+begin_src clojure :results output :exports both
1135 (clojure.pprint/pprint
1136 (pokemon.lpsolve/attack-mode
1137 (pokemon.types/susceptibility
1138 [;; setup
1139 :normal :normal :normal :normal
1140 :ice :ice :ice :ice
1141 :electric :electric :electric
1142 :rock :rock
1143 ;; Spot resistances
1144 :ghost :ground
1145 ;; Pair resistances
1146 :psychic :fighting
1147 :grass :poison])))
1148 #+end_src
1150 #+results:
1151 #+begin_example
1152 {:water 1,
1153 :psychic 1/2,
1154 :dragon 1,
1155 :fire 1/4,
1156 :ice 1/2,
1157 :grass 1,
1158 :ghost 0,
1159 :poison 1/2,
1160 :flying 0,
1161 :normal 0,
1162 :rock 1/4,
1163 :electric 1/4,
1164 :ground 0,
1165 :fighting 1/2,
1166 :dark 0,
1167 :steel 0,
1168 :bug 1/2}
1169 #+end_example
1171 Can you see the final step?
1173 It's adding the Water type, which is weak against Water, Dragon, and
1174 Grass and strong against Rock and Fire.
1176 #+begin_src clojure :results output :exports both
1177 (clojure.pprint/pprint
1178 (pokemon.lpsolve/attack-mode
1179 (pokemon.types/susceptibility
1180 [;; setup
1181 :normal :normal :normal :normal
1182 :ice :ice :ice :ice
1183 :electric :electric :electric
1184 :rock :rock
1185 ;; Spot resistances
1186 :ghost :ground
1187 ;; Pair resistances
1188 :psychic :fighting
1189 :grass :poison
1190 ;; completion
1191 :water])))
1192 #+end_src
1194 #+results:
1195 #+begin_example
1196 {:water 1/2,
1197 :psychic 1/2,
1198 :dragon 1/2,
1199 :fire 1/2,
1200 :ice 1/2,
1201 :grass 1/2,
1202 :ghost 0,
1203 :poison 1/2,
1204 :flying 0,
1205 :normal 0,
1206 :rock 1/2,
1207 :electric 1/4,
1208 :ground 0,
1209 :fighting 1/2,
1210 :dark 0,
1211 :steel 0,
1212 :bug 1/2}
1213 #+end_example
1215 Which makes a particularly beautiful combination which is ineffective
1216 against all defending types.
1219 # #+begin_src clojure :results scalar :exports both
1220 # (with-out-str (clojure.contrib.pprint/pprint (seq (attack-mode (pokemon.types/susceptibility [:normal :normal :normal :normal :ice :ice :ice :ice :electric :electric :electric :rock :rock :ground :ghost :psychic :fighting :grass :poison])))))
1221 # #+end_src
1223 # #+results:
1224 # | [:water 1] | [:psychic 1/2] | [:dragon 1] | [:fire 1/4] | [:ice 1/2] | [:grass 1] | [:ghost 0] | [:poison 1/2] | [:flying 0] | [:normal 0] | [:rock 1/4] | [:electric 1/4] | [:ground 0] | [:fighting 1/2] | [:dark 0] | [:steel 0] | [:bug 1/2] |
1227 Is there anything else that's interesting?
1229 #+begin_src clojure :exports both
1230 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-defense-type))
1231 #+end_src
1233 #+results:
1234 : INFEASIBLE
1236 #+begin_src clojure :exports both
1237 (pokemon.types/old-school
1238 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-defense-type)))
1239 #+end_src
1241 #+results:
1242 : INFEASIBLE
1244 #+begin_src clojure :exports both
1245 (pokemon.lpsolve/solution (pokemon.lpsolve/weak-defense-type))
1246 #+end_src
1248 #+results:
1249 : INFEASIBLE
1251 #+begin_src clojure :exports both
1252 (pokemon.types/old-school
1253 (pokemon.lpsolve/solution (pokemon.lpsolve/weak-defense-type)))
1254 #+end_src
1256 #+results:
1257 : INFEASIBLE
1259 #+begin_src clojure :exports both
1260 (pokemon.lpsolve/solution (pokemon.lpsolve/neutral-defense-type))
1261 #+end_src
1263 #+results:
1264 : INFEASIBLE
1266 #+begin_src clojure :exports both
1267 (pokemon.types/old-school
1268 (pokemon.lpsolve/solution (pokemon.lpsolve/neutral-defense-type)))
1269 #+end_src
1271 #+results:
1272 : INFEASIBLE
1274 There is no way to produce a defense-type that is weak to all types.
1275 This is probably because there are many types that are completely
1276 immune to some types, such as Flying, which is immune to Ground. A
1277 perfectly weak type could not use any of these types.
1279 * Summary
1281 Overall, the pok\eacute{}mon type system is slanted towards defense
1282 rather than offense. While it is possible to create superior
1283 defensive types and exceptionally weak attack types, it is not
1284 possible to create exceptionally weak defensive types or very powerful
1285 attack types.
1287 Using the =lp_solve= library was more complicated than the best-first
1288 search, but yielded results quickly and efficiently. Expressing the
1289 problem in a linear form does have its drawbacks, however --- it's
1290 hard to ask questions such as "what is the best 3-type defensive combo
1291 in terms of susceptibility?", since susceptibility is not a linear
1292 function of a combo's types. It is also hard to get all the solutions
1293 to a particular problem, such as all the pokemon type combinations of
1294 length 8 which are immortal defense types.
1296 * COMMENT main-program
1297 #+begin_src clojure :tangle ../src/pokemon/lpsolve.clj :noweb yes :exports none
1298 <<intro>>
1299 <<body>>
1300 <<declares>>
1301 <<memory-management>>
1302 <<get-results>>
1303 <<solve>>
1304 <<farmer-example>>
1305 <<lp-solve>>
1306 <<better-farmer>>
1307 <<pokemon-lp>>
1308 <<results>>
1309 <<attack-oriented>>
1310 #+end_src