Mercurial > pokemon-types
view org/lpsolve.org @ 21:f88b7d2c25d9
lol.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 17 Sep 2013 17:42:51 -0400 |
parents | 47fa6dc56e30 |
children | 8992278bf399 |
line wrap: on
line source
1 #+title: Discovering Effective Pok\eacute{}mon Types Using Linear Optimization2 #+author: Robert McIntyre & Dylan Holmes3 #+EMAIL: rlm@mit.edu4 #+description: Using Lpsolve to find effective pokemon types in clojure.5 #+keywords: Pokemon, clojure, linear optimization, lp_solve, LpSolve6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org9 * Introduction10 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 each12 other using fantastic attacks. It was made into a several gameboy13 games that all share the same battle system. Every pok\eacute{}mon in14 the gameboy game has one or two /types/, such as Ground, Fire, Water,15 etc. Every pok\eacute{}mon attack has exactly one type. Certain16 defending types are weak or strong to other attacking types. For17 example, Water attacks are strong against Fire pok\eacute{}mon, while18 Electric attacks are weak against Ground Pok\eacute{}mon. In the19 games, attacks can be either twice as effective as normal (Water20 vs. Fire), neutrally effective (Normal vs. Normal), half as effective21 (Fire vs. Water), or not effective at all (Electric vs. Ground). We22 represent these strengths and weaknesses as the numbers 2, 1,23 $\frac{1}{2}$, and 0, and call them the /susceptance/ of one type to24 another.26 If a pokemon has two types, then the strengths and weakness of each27 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, then31 the combination is doubly-resistant (1/4x) to that type. If both types32 are weak to a certain type then the combination is double-weak (4x) to33 that type.35 In the [[./types.org][previous post]], we used the best-first search algorithm to find36 the most effective Pok\eacute{}mon type combinations. Afterwards, we37 realized that we could transform this search problem into a /linear38 optimization problem/. This conversion offers several advantages:39 first, search algorithms are comparatively slow, whereas linear40 optimization algorithms are extremely fast; second, it is difficult to41 determine whether a search problem has any solution, whereas it is42 straightforward to determine whether a linear optimization problem has43 any solution; finally, because systems of linear equations are so44 common, many programming languages have linear equation solvers45 written for them.47 In this article, we will:48 - Solve a simple linear optimization problem in C :: We demonstrate49 how to use the linear programming C library, =lp_solve=, to50 solve a simple linear optimization problem.51 - Incorporate a C library into Clojure :: We will show how we gave52 Clojure access to the linear programming C library, =lp_solve=.53 - Find effective Pokemon types using linear programming :: Building54 on our earlier code, we answer some questions that were55 impossible to answer using best-first search.56 - Present our results :: We found some cool examples and learned a lot57 about the pok\eacute{}mon type system as a whole.60 ** Immortal Types62 In the game, pok\eacute{}mon can have either one type or two types. If63 this restriction is lifted, is there any combination of types that is64 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 towards66 infinity, the resulting type would be immune to all attack types.68 * Linear Programming70 Linear programming is the process of finding an optimal solution to a71 linear equation of several variables which are constrained by some linear72 inequalities.74 ** The Farmer's Problem76 Let's solve the Farmer's Problem, an example linear programming problem77 borrowed from http://lpsolve.sourceforge.net/5.5/formulate.htm.80 #+BEGIN_QUOTE81 *The Farmer's Problem:* Suppose a farmer has 75 acres on which to82 plant two crops: wheat and barley. To produce these crops, it costs83 the farmer (for seed, fertilizer, etc.) $120 per acre for the wheat84 and $210 per acre for the barley. The farmer has $15000 available for85 expenses. But after the harvest, the farmer must store the crops while86 awaiting favorable market conditions. The farmer has storage space87 for 4000 bushels. Each acre yields an average of 110 bushels of wheat88 or 30 bushels of barley. If the net profit per bushel of wheat (after89 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_QUOTE93 The Farmer's Problem is to maximize profit subject to constraints on94 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 Solve106 In a new file, =farmer.lp=, we list the variables and constraints107 of our problem using LP Solve syntax.109 #+begin_src lpsolve :tangle ../lp/farmer.lp110 /* 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_src126 Running the =lp_solve= program on =farmer.lp= yields the following output.128 lol130 #+begin_src sh :exports both :results scalar131 lp_solve ~/proj/pokemon-types/lp/farmer.lp132 #+end_src134 #+results:135 :136 : Value of objective function: 6315.62500000137 :138 : Actual values of the variables:139 : wheat 21.875140 : barley 53.125143 This shows that the farmer can maximize his profit by planting 21.875144 of the available acres with wheat and the remaining 53.125 acres with145 barley; by doing so, he will make $6315.62(5) in profit.147 * Incorporating =lp_solve= into Clojure149 There is a [[http://lpsolve.sourceforge.net/5.5/Java/README.html][Java API]] written by Juergen Ebert which enables Java150 programs to use =lp_solve=. Although Clojure can use this Java API151 directly, the interaction between Java, C, and Clojure is clumsy:153 ** The Farmer's Problem in Clojure155 We are going to solve the same problem involving wheat and barley,156 that we did above, but this time using clojure and the =lp_solve= API.158 #+name: intro159 #+begin_src clojure :results silent160 (ns pokemon.lpsolve161 (:import lpsolve.LpSolve)162 (:require pokemon.types)163 ;;(:require incanter.core)164 (:require rlm.map-utils))165 #+end_src167 The =lp_solve= Java interface is available from the same site as168 =lp_solve= itself, http://lpsolve.sourceforge.net/ Using it is the169 same as many other =C= programs. There are excellent instructions to170 get set up. The short version is that you must call Java with171 =-Djava.library.path=/path/to/lpsolve/libraries= and also add the172 libraries to your export =LD_LIBRARY_PATH= if you are using Linux. For173 example, in my =.bashrc= file, I have the line174 =LD_LIBRARY_PATH=$HOME/roBin/lpsolve:$LD_LIBRARY_PATH=. If everything175 is set-up correctly,177 #+name: body178 #+begin_src clojure :results verbatim :exports both179 (import 'lpsolve.LpSolve)180 #+end_src182 #+results:183 : lpsolve.LpSolve185 should run with no problems.187 ** Making a DSL to talk with LpSolve188 *** Problems189 Since we are using a =C= wrapper, we have to deal with manual memory190 management for the =C= structures which are wrapped by the =LpSolve=191 object. Memory leaks in =LpSolve= instances can crash the JVM, so it's192 very important to get it right. Also, the Java wrapper follows the193 =C= tradition closely and defines many =static final int= constants194 for the different states of the =LpSolve= instance instead of using Java195 enums. The calling convention for adding rows and columns to196 the constraint matrix is rather complicated and must be done column by197 column or row by row, which can be error prone. Finally, I'd like to198 gather all the important output information from the =LpSolve= instance199 into a final, immutable structure.201 In summary, the issues I'd like to address are:203 - reliable memory management204 - functional interface to =LpSolve=205 - intelligible, immutable output207 To deal with these issues I'll create four functions for interfacing208 with =LpSolve=210 #+name: declares211 #+begin_src clojure :results silent212 (in-ns 'pokemon.lpsolve)214 ;; deal with automatic memory management for LpSolve instance.215 (declare linear-program)217 ;; functional interface to LpSolve218 (declare lp-solve)220 ;; immutable output from lp-solve221 (declare solve get-results)222 #+end_src225 *** Memory Management227 Every instance of =LpSolve= must be manually garbage collected via a228 call to =deleteLP=. I use a non-hygienic macro similar to =with-open=229 to ensure that =deleteLP= is always called.231 #+name: memory-management232 #+begin_src clojure :results silent233 (in-ns 'pokemon.lpsolve)234 (defmacro linear-program235 "solve a linear programming problem using LpSolve syntax.236 within the macro, the variable =lps= is bound to the LpSolve instance."237 [& statements]238 (list 'let '[lps (LpSolve/makeLp 0 0)]239 (concat '(try)240 statements241 ;; always free the =C= data structures.242 '((finally (.deleteLp lps))))))243 #+end_src246 The macro captures the variable =lps= within its body, providing for a247 convenient way to access the object using any of the methods of the248 =LpSolve= API without having to worry about when to call249 =deleteLP=.251 *** Sensible Results252 The =linear-program= macro deletes the actual =lps= object once it is253 done working, so it's important to collect the important results and254 add return them in an immutable structure at the end.256 #+name: get-results257 #+begin_src clojure :results silent258 (in-ns 'pokemon.lpsolve)260 (defrecord LpSolution261 [objective-value262 optimal-values263 variable-names264 solution265 status266 model])268 (defn model269 "Returns a textual representation of the problem suitable for270 direct input to the =lp_solve= program (lps format)"271 [#^LpSolve lps]272 (let [target (java.io.File/createTempFile "lps" ".lp")]273 (.writeLp lps (.getPath target))274 (slurp target)))276 (defn results277 "Given an LpSolve object, solves the object and returns a map of the278 essential values which compose the solution."279 [#^LpSolve lps]280 (locking lps281 (let [status (solve lps)282 number-of-variables (.getNcolumns lps)283 optimal-values (double-array number-of-variables)284 optimal-values (do (.getVariables lps optimal-values)285 (seq optimal-values))286 variable-names287 (doall288 ;; The doall is necessary since the lps object might289 ;; soon be deleted.290 (map291 #(.getColName lps (inc %))292 (range number-of-variables)))293 model (model lps)]294 (LpSolution.295 (.getObjective lps)296 optimal-values297 variable-names298 (zipmap variable-names optimal-values)299 status300 model))))302 #+end_src304 Here I've created an object called =LpSolution= which stores the305 important results from a session with =lp_solve=. Of note is the306 =model= function which returns the problem in a form that can be307 solved by other linear programming packages.309 *** Solution Status of an LpSolve Object311 #+name: solve312 #+begin_src clojure :results silent313 (in-ns 'pokemon.lpsolve)315 (defn static-integer?316 "does the field represent a static integer constant?"317 [#^java.lang.reflect.Field field]318 (and (java.lang.reflect.Modifier/isStatic (.getModifiers field))319 (integer? (.get field nil))))321 (defn integer-constants [class]322 (filter static-integer? (.getFields class)))324 (defn constant-map325 "Takes a class and creates a map of the static constant integer326 fields with their names. This helps with C wrappers where they have327 just defined a bunch of integer constants instead of enums."328 [class]329 (let [integer-fields (integer-constants class)]330 (into (sorted-map)331 (zipmap (map #(.get % nil) integer-fields)332 (map #(.getName %) integer-fields)))))334 (alter-var-root #'constant-map memoize)336 (defn solve337 "Solve an instance of LpSolve and return a string representing the338 status of the computation. Will only solve a particular LpSolve339 instance once."340 [#^LpSolve lps]341 ((constant-map LpSolve)342 (.solve lps)))344 #+end_src346 The =.solve= method of an =LpSolve= object only returns an integer code347 to specify the status of the computation. The =solve= method here348 uses reflection to look up the actual name of the status code and349 returns a more helpful status message that is also resistant to350 changes in the meanings of the code numbers.352 *** The Farmer Example in Clojure, Pass 1354 Now we can implement a nicer version of the examples from the355 [[http://lpsolve.sourceforge.net/][=lp\_solve= website]]. The following is a more or less356 line-by-line translation of the Java code from that example.358 #+name: farmer-example359 #+begin_src clojure :results silent360 (in-ns 'pokemon.lpsolve)361 (defn farmer-example []362 (linear-program363 (results364 (doto lps365 ;; name the columns366 (.setColName 1 "wheat")367 (.setColName 2 "barley")368 (.setAddRowmode true)369 ;; row 1 : 120x + 210y <= 15000370 (.addConstraintex 2371 (double-array [120 210])372 (int-array [1 2])373 LpSolve/LE374 15e3)375 ;; row 2 : 110x + 30y <= 4000376 (.addConstraintex 2377 (double-array [110 30])378 (int-array [1 2])379 LpSolve/LE380 4e3)381 ;; ;; row 3 : x + y <= 75382 (.addConstraintex 2383 (double-array [1 1])384 (int-array [1 2])385 LpSolve/LE386 75)387 (.setAddRowmode false)389 ;; add constraints390 (.setObjFnex 2391 (double-array [143 60])392 (int-array [1 2]))394 ;; set this as a maximization problem395 (.setMaxim)))))397 #+end_src399 #+begin_src clojure :results output :exports both400 (clojure.pprint/pprint401 (:solution (pokemon.lpsolve/farmer-example)))402 #+end_src404 #+results:405 : {"barley" 53.12499999999999, "wheat" 21.875}408 And it works as expected!410 *** The Farmer Example in Clojure, Pass 2411 We don't have to worry about memory management anymore, and the farmer412 example is about half as long as the example from the =LpSolve=413 website, but we can still do better. Solving linear problems is all414 about the constraint matrix $A$ , the objective function $c$, and the415 right-hand-side $b$, plus whatever other options one cares to set for416 the particular instance of =lp_solve=. Why not make a version of417 =linear-program= that takes care of initialization?421 #+name: lp-solve422 #+begin_src clojure :results silent423 (in-ns 'pokemon.lpsolve)424 (defn initialize-lpsolve-row-oriented425 "fill in an lpsolve instance using a constraint matrix =A=, the426 objective function =c=, and the right-hand-side =b="427 [#^lpsolve.LpSolve lps A b c]428 ;; set the name of the last column to _something_429 ;; this appears to be necessary to ensure proper initialization.430 (.setColName lps (count c) (str "C" (count c)))432 ;; This is the recommended way to "fill-in" an lps instance from the433 ;; documentation. First, set row mode, then set the objective434 ;; function, then set each row of the problem, and then turn off row435 ;; mode.436 (.setAddRowmode lps true)437 (.setObjFnex lps (count c)438 (double-array c)439 (int-array (range 1 (inc (count c)))))440 (dorun441 (for [n (range (count A))]442 (let [row (nth A n)443 row-length (int (count row))]444 (.addConstraintex lps445 row-length446 (double-array row)447 (int-array (range 1 (inc row-length)))448 LpSolve/LE449 (double (nth b n))))))450 (.setAddRowmode lps false)451 lps)454 (defmacro lp-solve455 "by default:,456 minimize (* c x), subject to (<= (* A x) b),457 using continuous variables. You may set any number of458 other options as in the LpSolve API."459 [A b c & lp-solve-forms]460 ;; assume that A is a vector of vectors461 (concat462 (list 'linear-program463 (list 'initialize-lpsolve-row-oriented 'lps A b c))464 `~lp-solve-forms))465 #+end_src467 Now, we can use a much more functional approach to solving the468 farmer's problem:470 #+name: better-farmer471 #+begin_src clojure :results silent472 (in-ns 'pokemon.lpsolve)473 (defn better-farmer-example []474 (lp-solve [[120 210]475 [110 30]476 [1 1]]477 [15000478 4000479 75]480 [143 60]481 (.setColName lps 1 "wheat")482 (.setColName lps 2 "barley")483 (.setMaxim lps)484 (results lps)))485 #+end_src487 #+begin_src clojure :exports both :results verbatim488 (vec (:solution (pokemon.lpsolve/better-farmer-example)))489 #+end_src491 #+results:492 : [["barley" 53.12499999999999] ["wheat" 21.875]]494 Notice that both the inputs to =better-farmer-example= and the results495 are immutable.497 * Using LpSolve to find Immortal Types498 ** Converting the Pok\eacute{}mon problem into a linear form499 How can the original question about pok\eacute{}mon types be converted500 into a linear problem?502 Pokemon types can be considered to be vectors of numbers representing503 their susceptances to various attacking types, so Water might look504 something like this.506 #+begin_src clojure :results scalar :exports both507 (:water (pokemon.types/defense-strengths))508 #+end_src510 #+results:511 : [1 0.5 0.5 2 2 0.5 1 1 1 1 1 1 1 1 1 1 0.5]513 Where the numbers represent the susceptibility of Water to the514 attacking types in the following order:516 #+begin_src clojure :results output :exports both517 (clojure.pprint/pprint518 (pokemon.types/type-names))519 #+end_src521 #+results:522 #+begin_example523 [:normal524 :fire525 :water526 :electric527 :grass528 :ice529 :fighting530 :poison531 :ground532 :flying533 :psychic534 :bug535 :rock536 :ghost537 :dragon538 :dark539 :steel]540 #+end_example543 So, for example, Water is resistant (x0.5) against Fire, which is544 the second element in the list.546 To combine types, these sorts of vectors are multiplied together547 pair-wise to yield the resulting combination.549 Unfortunately, we need some way to add two type vectors together550 instead of multiplying them if we want to solve the problem with551 =lp_solve=. Taking the log of the vector does just the trick.553 If we make a matrix with each column being the log (base 2) of the554 susceptance of each type, then finding an immortal type corresponds to555 setting each constraint (the $b$ vector) to -1 (since log_2(1/2) = -1)556 and setting the constraint vector $c$ to all ones, which means that we557 want to find the immortal type which uses the least amount of types.559 #+name: pokemon-lp560 #+begin_src clojure :results silent561 (in-ns 'pokemon.lpsolve)563 (defn log-clamp-matrix [matrix]564 ;; we have to clamp the Infinities to a more reasonable negative565 ;; value because lp_solve does not play well with infinities in its566 ;; constraint matrix.567 (map (fn [row] (map #(if (= Double/NEGATIVE_INFINITY %) -1e3 %)568 (map #(/ (Math/log %) (Math/log 2)) row)))569 (apply mapv vector ;; transpose570 matrix)))572 ;; constraint matrices573 (defn log-defense-matrix []574 (log-clamp-matrix575 (doall (map (pokemon.types/defense-strengths)576 (pokemon.types/type-names)))))578 (defn log-attack-matrix []579 (apply mapv vector (log-defense-matrix)))581 ;; target vectors582 (defn all-resistant []583 (doall (map (constantly -1) (pokemon.types/type-names))))585 (defn all-weak []586 (doall (map (constantly 1) (pokemon.types/type-names))))588 (defn all-neutral []589 (doall (map (constantly 0) (pokemon.types/type-names))))591 ;; objective functions592 (defn number-of-types []593 (doall (map (constantly 1) (pokemon.types/type-names))))595 (defn set-constraints596 "sets all the constraints for an lpsolve instance to the given597 constraint. =constraint= here is one of the LpSolve constants such598 as LpSolve/EQ."599 [#^LpSolve lps constraint]600 (dorun (map (fn [index] (.setConstrType lps index constraint))601 ;; ONE based indexing!!!602 (range 1 (inc (.getNrows lps))))))604 (defn set-discrete605 "sets every variable in an lps problem to be a discrete rather than606 continuous variable"607 [#^LpSolve lps]608 (dorun (map (fn [index] (.setInt lps index true))609 ;; ONE based indexing!!!610 (range 1 (inc (.getNcolumns lps))))))612 (defn set-variable-names613 "sets the variable names of the problem given a vector of names"614 [#^LpSolve lps names]615 (dorun616 (keep-indexed617 (fn [index name]618 (.setColName lps (inc index) (str name)))619 ;; ONE based indexing!!!620 names)))622 (defn poke-solve623 ([poke-matrix target objective-function constraint min-num-types]624 ;; must have at least one type625 (let [poke-matrix626 (concat poke-matrix627 [(map (constantly 1)628 (range (count (first poke-matrix))))])629 target (concat target [min-num-types])]630 (lp-solve poke-matrix target objective-function631 (set-constraints lps constraint)632 ;; must have more than min-num-types633 (.setConstrType lps (count target) LpSolve/GE)634 (set-discrete lps)635 (set-variable-names lps (pokemon.types/type-names))636 (results lps))))637 ([poke-matrix target objective-function constraint]638 ;; at least one type639 (poke-solve poke-matrix target objective-function constraint 1)))641 (defn solution642 "If the results of an lpsolve operation are feasible, returns the643 results. Otherwise, returns the error."644 [results]645 (if (not (= (:status results) "OPTIMAL"))646 (:status results)647 (:solution results)))648 #+end_src650 With this, we are finally able to get some results.652 ** Results653 #+name: results654 #+begin_src clojure :results silent655 (in-ns 'pokemon.lpsolve)657 (defn best-defense-type658 "finds a type combination which is resistant to all attacks."659 []660 (poke-solve661 (log-defense-matrix) (all-resistant) (number-of-types) LpSolve/LE))663 (defn worst-attack-type664 "finds the attack type which is not-very-effective against all pure665 defending types (each single defending type is resistant to this666 attack combination"667 []668 (poke-solve669 (log-attack-matrix) (all-resistant) (number-of-types) LpSolve/LE))671 (defn worst-defense-type672 "finds a defending type that is weak to all single attacking types."673 []674 (poke-solve675 (log-defense-matrix) (all-weak) (number-of-types) LpSolve/GE))677 (defn best-attack-type678 "finds an attack type which is super effective against all single679 defending types"680 []681 (poke-solve682 (log-attack-matrix) (all-weak) (number-of-types) LpSolve/GE))684 (defn solid-defense-type685 "finds a defense type which is either neutral or resistant to all686 single attacking types"687 []688 (poke-solve689 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/LE))691 (defn solid-attack-type692 "finds an attack type which is either neutral or super-effective to693 all single attacking types."694 []695 (poke-solve696 (log-attack-matrix) (all-neutral) (number-of-types) LpSolve/GE))698 (defn weak-defense-type699 "finds a defense type which is either neutral or weak to all single700 attacking types"701 []702 (poke-solve703 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/GE))705 (defn neutral-defense-type706 "finds a defense type which is perfectly neutral to all attacking707 types."708 []709 (poke-solve710 (log-defense-matrix) (all-neutral) (number-of-types) LpSolve/EQ))712 #+end_src714 *** Strongest Attack/Defense Combinations716 #+begin_src clojure :results output :exports both717 (clojure.pprint/pprint718 (pokemon.lpsolve/solution (pokemon.lpsolve/best-defense-type)))719 #+end_src721 #+results:722 #+begin_example723 {":normal" 0.0,724 ":ground" 1.0,725 ":poison" 2.0,726 ":flying" 1.0,727 ":fighting" 0.0,728 ":dragon" 0.0,729 ":fire" 0.0,730 ":dark" 1.0,731 ":ice" 0.0,732 ":steel" 1.0,733 ":ghost" 0.0,734 ":electric" 0.0,735 ":bug" 0.0,736 ":psychic" 0.0,737 ":grass" 0.0,738 ":water" 2.0,739 ":rock" 0.0}740 #+end_example742 # #+results-old:743 # : [[":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]]746 This is the immortal type combination we've been looking for. By747 combining Steel, Water, Poison, and three types which each have complete748 immunities to various other types, we've created a type that is resistant to749 all attacking types.751 #+begin_src clojure :results output :exports both752 (clojure.pprint/pprint753 (pokemon.types/susceptibility754 [:poison :poison :water :water :steel :ground :flying :dark]))755 #+end_src757 #+results:758 #+begin_example759 {:water 1/2,760 :psychic 0,761 :dragon 1/2,762 :fire 1/2,763 :ice 1/2,764 :grass 1/2,765 :ghost 1/4,766 :poison 0,767 :flying 1/2,768 :normal 1/2,769 :rock 1/2,770 :electric 0,771 :ground 0,772 :fighting 1/2,773 :dark 1/4,774 :steel 1/8,775 :bug 1/8}776 #+end_example778 # #+results-old:779 # : {: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}782 Cool!784 #+begin_src clojure :results output :exports both785 (clojure.pprint/pprint786 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-defense-type)))787 #+end_src789 #+results:790 #+begin_example791 {":normal" 0.0,792 ":ground" 0.0,793 ":poison" 0.0,794 ":flying" 0.0,795 ":fighting" 0.0,796 ":dragon" 0.0,797 ":fire" 0.0,798 ":dark" 1.0,799 ":ice" 0.0,800 ":steel" 0.0,801 ":ghost" 1.0,802 ":electric" 0.0,803 ":bug" 0.0,804 ":psychic" 0.0,805 ":grass" 0.0,806 ":water" 0.0,807 ":rock" 0.0}808 #+end_example810 Dark and Ghost are the best dual-type combo, and are resistant or811 neutral to all types.813 #+begin_src clojure :results output :exports both814 (clojure.pprint/pprint815 (pokemon.types/old-school816 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-defense-type))))817 #+end_src819 #+results:820 #+begin_example821 {":normal" 0.0,822 ":ground" 0.0,823 ":poison" 0.0,824 ":flying" 0.0,825 ":fighting" 0.0,826 ":dragon" 0.0,827 ":fire" 0.0,828 ":ice" 0.0,829 ":ghost" 1.0,830 ":electric" 0.0,831 ":bug" 0.0,832 ":psychic" 1.0,833 ":grass" 0.0,834 ":water" 0.0,835 ":rock" 0.0}836 #+end_example838 Ghost and Psychic are a powerful dual type combo in the original games,839 due to a glitch which made Psychic immune to Ghost type attacks, even840 though the game claims that Ghost is strong against Psychic.842 #+begin_src clojure :results verbatim :exports both843 (pokemon.lpsolve/solution (pokemon.lpsolve/best-attack-type))844 #+end_src846 #+results:847 : INFEASIBLE849 #+begin_src clojure :results verbatim :exports both850 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-attack-type))851 #+end_src853 #+results:854 : INFEASIBLE857 #+begin_src clojure :results verbatim :exports both858 (pokemon.types/old-school859 (pokemon.lpsolve/solution (pokemon.lpsolve/best-attack-type)))860 #+end_src862 #+results:863 : INFEASIBLE866 #+begin_src clojure :results output :exports both867 (clojure.pprint/pprint868 (pokemon.types/old-school869 (pokemon.lpsolve/solution (pokemon.lpsolve/solid-attack-type))))870 #+end_src872 #+results:873 #+begin_example874 {":normal" 0.0,875 ":ground" 0.0,876 ":poison" 0.0,877 ":flying" 0.0,878 ":fighting" 0.0,879 ":dragon" 1.0,880 ":fire" 0.0,881 ":ice" 0.0,882 ":ghost" 0.0,883 ":electric" 0.0,884 ":bug" 0.0,885 ":psychic" 0.0,886 ":grass" 0.0,887 ":water" 0.0,888 ":rock" 0.0}889 #+end_example891 The best attacking type combination is Dragon from the original games.892 It is neutral against all the original types except for Dragon, which893 it is strong against. There is no way to make an attacking type that894 is strong against every type, or even one that is strong or neutral895 against every type, in the new games.898 *** Weakest Attack/Defense Combinations900 #+begin_src clojure :results output :exports both901 (clojure.pprint/pprint902 (pokemon.types/old-school903 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-attack-type))))904 #+end_src906 #+results:907 #+begin_example908 {":normal" 5.0,909 ":ground" 0.0,910 ":poison" 0.0,911 ":flying" 0.0,912 ":fighting" 0.0,913 ":dragon" 0.0,914 ":fire" 1.0,915 ":ice" 2.0,916 ":ghost" 1.0,917 ":electric" 1.0,918 ":bug" 1.0,919 ":psychic" 0.0,920 ":grass" 3.0,921 ":water" 2.0,922 ":rock" 0.0}923 #+end_example925 # #+results-old:926 # : [[":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]]928 #+begin_src clojure :results output :exports both929 (clojure.pprint/pprint930 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-attack-type)))931 #+end_src933 #+results:934 #+begin_example935 {":normal" 4.0,936 ":ground" 1.0,937 ":poison" 1.0,938 ":flying" 0.0,939 ":fighting" 1.0,940 ":dragon" 0.0,941 ":fire" 0.0,942 ":dark" 0.0,943 ":ice" 4.0,944 ":steel" 0.0,945 ":ghost" 1.0,946 ":electric" 3.0,947 ":bug" 0.0,948 ":psychic" 1.0,949 ":grass" 1.0,950 ":water" 1.0,951 ":rock" 2.0}952 #+end_example954 # #+results-old:955 # : [[":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]]958 This is an extremely interesting type combination, in that it uses959 quite a few types.961 #+begin_src clojure :results verbatim :exports both962 (reduce + (vals (:solution (pokemon.lpsolve/worst-attack-type))))963 #+end_src965 #+results:966 : 20.0968 20 types is the /minimum/ number of types before the attacking969 combination is not-very-effective or worse against all defending970 types. This would probably have been impossible to discover using971 best-first search, since it involves such an intricate type972 combination.974 It's so interesting that it takes 20 types to make an attack type that975 is weak to all types that the combination merits further976 investigation.978 Unfortunately, all of the tools that we've written so far are focused979 on defense type combinations. However, it is possible to make every980 tool attack-oriented via a simple macro.982 #+name: attack-oriented983 #+begin_src clojure :results silent984 (in-ns 'pokemon.lpsolve)986 (defmacro attack-mode [& forms]987 `(let [attack-strengths# pokemon.types/attack-strengths988 defense-strengths# pokemon.types/defense-strengths]989 (binding [pokemon.types/attack-strengths990 defense-strengths#991 pokemon.types/defense-strengths992 attack-strengths#]993 ~@forms)))994 #+end_src996 Now all the tools from =pokemon.types= will work for attack997 combinations.999 #+begin_src clojure :results output :exports both1000 (clojure.pprint/pprint1001 (pokemon.types/susceptibility [:water]))1002 #+end_src1004 #+results:1005 #+begin_example1006 {:water 1/2,1007 :psychic 1,1008 :dragon 1,1009 :fire 1/2,1010 :ice 1/2,1011 :grass 2,1012 :ghost 1,1013 :poison 1,1014 :flying 1,1015 :normal 1,1016 :rock 1,1017 :electric 2,1018 :ground 1,1019 :fighting 1,1020 :dark 1,1021 :steel 1/2,1022 :bug 1}1023 #+end_example1026 #+begin_src clojure :results output :exports both1027 (clojure.pprint/pprint1028 (pokemon.lpsolve/attack-mode1029 (pokemon.types/susceptibility [:water])))1030 #+end_src1032 #+results:1033 #+begin_example1034 {:water 1/2,1035 :psychic 1,1036 :dragon 1/2,1037 :fire 2,1038 :ice 1,1039 :grass 1/2,1040 :ghost 1,1041 :poison 1,1042 :flying 1,1043 :normal 1,1044 :rock 2,1045 :electric 1,1046 :ground 2,1047 :fighting 1,1048 :dark 1,1049 :steel 1,1050 :bug 1}1051 #+end_example1053 Now =pokemon.types/susceptibility= reports the /attack-type/1054 combination's effectiveness against other types.1056 The 20 type combo achieves its goal in a very clever way.1058 First, it weakens its effectiveness to other types at the expense of1059 making it very strong against flying.1061 #+begin_src clojure :results output :exports both1062 (clojure.pprint/pprint1063 (pokemon.lpsolve/attack-mode1064 (pokemon.types/susceptibility1065 [:normal :normal :normal :normal1066 :ice :ice :ice :ice1067 :electric :electric :electric1068 :rock :rock])))1069 #+end_src1071 #+results:1072 #+begin_example1073 {:water 1/2,1074 :psychic 1,1075 :dragon 2,1076 :fire 1/4,1077 :ice 1/4,1078 :grass 2,1079 :ghost 0,1080 :poison 1,1081 :flying 512,1082 :normal 1,1083 :rock 1/16,1084 :electric 1/8,1085 :ground 0,1086 :fighting 1/4,1087 :dark 1,1088 :steel 1/1024,1089 :bug 4}1090 #+end_example1092 Then, it removes it's strengths against Flying, Normal, and Fighting1093 by adding Ghost and Ground.1095 #+begin_src clojure :results output :exports both1096 (clojure.pprint/pprint1097 (pokemon.lpsolve/attack-mode1098 (pokemon.types/susceptibility1099 [:normal :normal :normal :normal1100 :ice :ice :ice :ice1101 :electric :electric :electric1102 :rock :rock1103 ;; Spot resistances1104 :ghost :ground])))1105 #+end_src1107 #+results:1108 #+begin_example1109 {:water 1/2,1110 :psychic 2,1111 :dragon 2,1112 :fire 1/2,1113 :ice 1/4,1114 :grass 1,1115 :ghost 0,1116 :poison 2,1117 :flying 0,1118 :normal 0,1119 :rock 1/8,1120 :electric 1/4,1121 :ground 0,1122 :fighting 1/4,1123 :dark 1/2,1124 :steel 1/1024,1125 :bug 2}1126 #+end_example1128 Adding the pair Psychic and Fighting takes care of its strength1129 against Psychic and makes it ineffective against Dark, which is immune1130 to Psychic.1132 Adding the pair Grass and Poison makes takes care of its strength1133 against poison and makes it ineffective against Steel, which is immune1134 to poison.1136 #+begin_src clojure :results output :exports both1137 (clojure.pprint/pprint1138 (pokemon.lpsolve/attack-mode1139 (pokemon.types/susceptibility1140 [;; setup1141 :normal :normal :normal :normal1142 :ice :ice :ice :ice1143 :electric :electric :electric1144 :rock :rock1145 ;; Spot resistances1146 :ghost :ground1147 ;; Pair resistances1148 :psychic :fighting1149 :grass :poison])))1150 #+end_src1152 #+results:1153 #+begin_example1154 {:water 1,1155 :psychic 1/2,1156 :dragon 1,1157 :fire 1/4,1158 :ice 1/2,1159 :grass 1,1160 :ghost 0,1161 :poison 1/2,1162 :flying 0,1163 :normal 0,1164 :rock 1/4,1165 :electric 1/4,1166 :ground 0,1167 :fighting 1/2,1168 :dark 0,1169 :steel 0,1170 :bug 1/2}1171 #+end_example1173 Can you see the final step?1175 It's adding the Water type, which is weak against Water, Dragon, and1176 Grass and strong against Rock and Fire.1178 #+begin_src clojure :results output :exports both1179 (clojure.pprint/pprint1180 (pokemon.lpsolve/attack-mode1181 (pokemon.types/susceptibility1182 [;; setup1183 :normal :normal :normal :normal1184 :ice :ice :ice :ice1185 :electric :electric :electric1186 :rock :rock1187 ;; Spot resistances1188 :ghost :ground1189 ;; Pair resistances1190 :psychic :fighting1191 :grass :poison1192 ;; completion1193 :water])))1194 #+end_src1196 #+results:1197 #+begin_example1198 {:water 1/2,1199 :psychic 1/2,1200 :dragon 1/2,1201 :fire 1/2,1202 :ice 1/2,1203 :grass 1/2,1204 :ghost 0,1205 :poison 1/2,1206 :flying 0,1207 :normal 0,1208 :rock 1/2,1209 :electric 1/4,1210 :ground 0,1211 :fighting 1/2,1212 :dark 0,1213 :steel 0,1214 :bug 1/2}1215 #+end_example1217 Which makes a particularly beautiful combination which is ineffective1218 against all defending types.1221 # #+begin_src clojure :results scalar :exports both1222 # (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])))))1223 # #+end_src1225 # #+results:1226 # | [: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] |1229 Is there anything else that's interesting?1231 #+begin_src clojure :exports both1232 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-defense-type))1233 #+end_src1235 #+results:1236 : INFEASIBLE1238 #+begin_src clojure :exports both1239 (pokemon.types/old-school1240 (pokemon.lpsolve/solution (pokemon.lpsolve/worst-defense-type)))1241 #+end_src1243 #+results:1244 : INFEASIBLE1246 #+begin_src clojure :exports both1247 (pokemon.lpsolve/solution (pokemon.lpsolve/weak-defense-type))1248 #+end_src1250 #+results:1251 : INFEASIBLE1253 #+begin_src clojure :exports both1254 (pokemon.types/old-school1255 (pokemon.lpsolve/solution (pokemon.lpsolve/weak-defense-type)))1256 #+end_src1258 #+results:1259 : INFEASIBLE1261 #+begin_src clojure :exports both1262 (pokemon.lpsolve/solution (pokemon.lpsolve/neutral-defense-type))1263 #+end_src1265 #+results:1266 : INFEASIBLE1268 #+begin_src clojure :exports both1269 (pokemon.types/old-school1270 (pokemon.lpsolve/solution (pokemon.lpsolve/neutral-defense-type)))1271 #+end_src1273 #+results:1274 : INFEASIBLE1276 There is no way to produce a defense-type that is weak to all types.1277 This is probably because there are many types that are completely1278 immune to some types, such as Flying, which is immune to Ground. A1279 perfectly weak type could not use any of these types.1281 * Summary1283 Overall, the pok\eacute{}mon type system is slanted towards defense1284 rather than offense. While it is possible to create superior1285 defensive types and exceptionally weak attack types, it is not1286 possible to create exceptionally weak defensive types or very powerful1287 attack types.1289 Using the =lp_solve= library was more complicated than the best-first1290 search, but yielded results quickly and efficiently. Expressing the1291 problem in a linear form does have its drawbacks, however --- it's1292 hard to ask questions such as "what is the best 3-type defensive combo1293 in terms of susceptibility?", since susceptibility is not a linear1294 function of a combo's types. It is also hard to get all the solutions1295 to a particular problem, such as all the pokemon type combinations of1296 length 8 which are immortal defense types.1298 * COMMENT main-program1299 #+begin_src clojure :tangle ../src/pokemon/lpsolve.clj :noweb yes :exports none1300 <<intro>>1301 <<body>>1302 <<declares>>1303 <<memory-management>>1304 <<get-results>>1305 <<solve>>1306 <<farmer-example>>1307 <<lp-solve>>1308 <<better-farmer>>1309 <<pokemon-lp>>1310 <<results>>1311 <<attack-oriented>>1312 #+end_src