1 /* Planeteer: Give trade route advice for Planets: The Exploration of Space
2 * Copyright (C) 2011 Scott Worley <sworley@chkno.net>
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 var funds = flag.Int("funds", 0,
29 var start = flag.String("start", "",
30 "The planet to start at")
32 var flight_plan_string = flag.String("flight_plan", "",
33 "Your hyper-holes for the day, comma-separated.")
35 var end_string = flag.String("end", "",
36 "A comma-separated list of acceptable ending planets.")
38 var planet_data_file = flag.String("planet_data_file", "planet-data",
39 "The file to read planet data from")
41 var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
43 var hold = flag.Int("hold", 300, "Size of your cargo hold")
45 var start_edens = flag.Int("start_edens", 0,
46 "How many Eden Warp Units are you starting with?")
48 var end_edens = flag.Int("end_edens", 0,
49 "How many Eden Warp Units would you like to keep (not use)?")
51 var cloak = flag.Bool("cloak", false,
52 "Make sure to end with a Device of Cloaking")
54 var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
56 var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
58 var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
60 var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
62 var visit_string = flag.String("visit", "",
63 "A comma-separated list of planets to make sure to visit")
65 func visit() []string {
66 if *visit_string == "" {
69 return strings.Split(*visit_string, ",")
72 func flight_plan() []string {
73 if *flight_plan_string == "" {
76 return strings.Split(*flight_plan_string, ",")
79 func end() map[string]bool {
80 if *end_string == "" {
83 m := make(map[string]bool)
84 for _, p := range strings.Split(*end_string, ",") {
90 type Commodity struct {
97 /* Use relative prices rather than absolute prices because you
98 can get relative prices without traveling to each planet. */
99 RelativePrices map[string]int
101 type planet_data struct {
102 Commodities map[string]Commodity
103 Planets map[string]Planet
104 p2i, c2i map[string]int // Generated; not read from file
105 i2p, i2c []string // Generated; not read from file
108 func ReadData() (data planet_data) {
109 f, err := os.Open(*planet_data_file)
114 err = json.NewDecoder(f).Decode(&data)
121 /* This program operates by filling in a state table representing the best
122 * possible trips you could make; the ones that makes you the most money.
123 * This is feasible because we don't look at all the possible trips.
124 * We define a list of things that are germane to this game and then only
125 * consider the best outcome in each possible game state.
127 * Each cell in the table represents a state in the game. In each cell,
128 * we track two things: 1. the most money you could possibly have while in
129 * that state and 2. one possible way to get into that state with that
132 * A basic analysis can be done with a two-dimensional table: location and
133 * fuel. planeteer-1.0 used this two-dimensional table. This version
134 * adds features mostly by adding dimensions to this table.
136 * Note that the sizes of each dimension are data driven. Many dimensions
137 * collapse to one possible value (ie, disappear) if the corresponding
138 * feature is not enabled.
140 * The order of the dimensions in the list of constants below determines
141 * their layout in RAM. The cargo-based 'dimensions' are not completely
142 * independent -- some combinations are illegal and not used. They are
143 * handled as three dimensions rather than one for simplicity. Placing
144 * these dimensions first causes the unused cells in the table to be
145 * grouped together in large blocks. This keeps them from polluting
146 * cache lines, and if they are large enough, prevent the memory manager
147 * from allocating pages for these areas at all.
149 * If the table gets too big to fit in RAM:
150 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
151 * 24 combinations, only 15 are legal: a 38% savings.
152 * * Reduce the size of the Fuel dimension to 3. We only ever look
153 * backwards 2 units, so just rotate the logical values through
154 * the same 3 physical addresses. This is good for an 82% savings.
155 * * Reduce the size of the Edens dimension from 3 to 2, for the
156 * same reasons as Fuel above. 33% savings.
157 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
161 // The official list of dimensions:
163 // Name Num Size Description
164 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
165 Cloaks // 2 2 # of Devices of Cloaking (0 or 1)
166 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
167 Fuel // 4 17 Hyper jump power left (0 - 16)
168 Location // 5 26 Location (which planet)
169 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
170 BuyFighters // 7 2 Errand: Buy fighter drones
171 BuyShields // 8 2 Errand: Buy shield batteries
172 Visit // 9 2**N Visit: Stop by these N planets in the route
177 func bint(b bool) int {
184 func DimensionSizes(data planet_data) []int {
185 eden_capacity := data.Commodities["Eden Warp Units"].Limit
186 if *start_edens > eden_capacity {
187 eden_capacity = *start_edens
189 cloak_capacity := bint(*cloak)
190 dims := make([]int, NumDimensions)
191 dims[Edens] = eden_capacity + 1
192 dims[Cloaks] = cloak_capacity + 1
193 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
194 dims[Fuel] = *fuel + 1
195 dims[Location] = len(data.Planets)
196 dims[Hold] = len(data.Commodities) + 1
197 dims[BuyFighters] = bint(*drones > 0) + 1
198 dims[BuyShields] = bint(*batteries > 0) + 1
199 dims[Visit] = 1 << uint(len(visit()))
201 // Remind myself to add a line above when adding new dimensions
202 for i, dim := range dims {
210 func StateTableSize(dims []int) int {
212 for _, size := range dims {
222 func EncodeIndex(dims, addr []int) int {
224 if addr[0] > dims[0] {
227 for i := 1; i < NumDimensions; i++ {
228 if addr[i] < 0 || addr[i] > dims[i] {
231 index = index*dims[i] + addr[i]
236 func DecodeIndex(dims []int, index int) []int {
237 addr := make([]int, NumDimensions)
238 for i := NumDimensions - 1; i > 0; i-- {
239 addr[i] = index % dims[i]
246 func InitializeStateTable(data planet_data, dims []int) []State {
247 table := make([]State, StateTableSize(dims))
249 addr := make([]int, NumDimensions)
251 addr[Edens] = *start_edens
252 addr[Location] = data.p2i[*start]
253 table[EncodeIndex(dims, addr)].value = *funds
258 /* These four fill procedures fill in the cell at address addr by
259 * looking at all the possible ways to reach this cell and selecting
262 * The other obvious implementation choice is to do this the other way
263 * around -- for each cell, conditionally overwrite all the other cells
264 * that are reachable *from* the considered cell. We choose gathering
265 * reads over scattering writes to avoid having to take a bunch of locks.
268 func UpdateCell(table []State, here, there, value_difference int) {
269 possible_value := table[there].value + value_difference
270 if table[there].value > 0 && possible_value > table[here].value {
271 table[here].value = possible_value
272 table[here].from = there
276 func FillCellByArriving(data planet_data, dims []int, table []State, addr []int) {
277 my_index := EncodeIndex(dims, addr)
278 other := make([]int, NumDimensions)
281 /* Travel here via a 2-fuel unit jump */
282 if addr[Fuel]+2 < dims[Fuel] {
283 other[Fuel] = addr[Fuel] + 2
284 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
285 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
286 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
289 other[Location] = addr[Location]
290 other[Fuel] = addr[Fuel]
293 /* Travel here via a hyper hole */
294 if addr[Fuel]+1 < dims[Fuel] {
295 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
296 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
297 other[Fuel] = addr[Fuel] + 1
298 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
299 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
301 other[Location] = addr[Location]
302 other[Fuel] = addr[Fuel]
306 /* Travel here via Eden Warp Unit */
307 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 1 {
308 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
310 other[Edens] = addr[Edens] + 1
311 other[UnusedCargo] = addr[UnusedCargo] - 1
312 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
313 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
315 other[Location] = addr[Location]
316 other[UnusedCargo] = addr[UnusedCargo]
317 other[Edens] = addr[Edens]
322 func FillCellBySelling(data planet_data, dims []int, table []State, addr []int) {
324 // Can't sell and still have cargo
327 if addr[UnusedCargo] > 0 {
328 // Can't sell everything and still have 'unused' holds
331 my_index := EncodeIndex(dims, addr)
332 other := make([]int, NumDimensions)
334 planet := data.i2p[addr[Location]]
335 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
336 commodity := data.i2c[other[Hold]]
337 if !data.Commodities[commodity].CanSell {
341 relative_price, available := data.Planets[planet].RelativePrices[commodity]
345 base_price := data.Commodities[commodity].BasePrice
346 absolute_price := float64(base_price) * float64(relative_price) / 100.0
347 sell_price := int(absolute_price * 0.9)
349 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
351 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
352 sale_value := quantity * sell_price
353 UpdateCell(table, my_index, EncodeIndex(dims, other), sale_value)
356 other[UnusedCargo] = addr[UnusedCargo]
359 func FillCellByBuying(data planet_data, dims []int, table []State, addr []int) {
361 // Can't buy and then have nothing
364 my_index := EncodeIndex(dims, addr)
365 other := make([]int, NumDimensions)
367 planet := data.i2p[addr[Location]]
368 commodity := data.i2c[addr[Hold]]
369 if !data.Commodities[commodity].CanSell {
372 relative_price, available := data.Planets[planet].RelativePrices[commodity]
376 base_price := data.Commodities[commodity].BasePrice
377 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
378 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
379 total_price := quantity * absolute_price
381 other[UnusedCargo] = 0
382 UpdateCell(table, my_index, EncodeIndex(dims, other), -total_price)
383 other[UnusedCargo] = addr[UnusedCargo]
384 other[Hold] = addr[Hold]
387 func FillCellByMisc(data planet_data, dims []int, table []State, addr []int) {
388 my_index := EncodeIndex(dims, addr)
389 other := make([]int, NumDimensions)
392 /* Buy a Device of Cloaking */
393 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
394 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
396 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
398 if other[Hold] != 0 {
399 other[UnusedCargo] = addr[UnusedCargo] + 1
401 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price)
402 other[UnusedCargo] = addr[UnusedCargo]
403 other[Cloaks] = addr[Cloaks]
407 /* Silly: Dump a Device of Cloaking */
409 /* Buy Fighter Drones */
410 if addr[BuyFighters] == 1 {
411 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
413 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
414 other[BuyFighters] = 0
415 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * *drones)
416 other[BuyFighters] = addr[BuyFighters]
420 /* Buy Shield Batteries */
421 if addr[BuyShields] == 1 {
422 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
424 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
425 other[BuyShields] = 0
426 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * *batteries)
427 other[BuyShields] = addr[BuyShields]
431 /* Visit this planet */
435 func FillCellByBuyingEdens(data planet_data, dims []int, table []State, addr []int) {
436 my_index := EncodeIndex(dims, addr)
437 other := make([]int, NumDimensions)
440 /* Buy Eden warp units */
441 eden_limit := data.Commodities["Eden Warp Units"].Limit
442 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
443 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
445 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
446 for quantity := addr[Edens]; quantity > 0; quantity-- {
447 other[Edens] = addr[Edens] - quantity
449 other[UnusedCargo] = addr[UnusedCargo] + quantity
451 if other[UnusedCargo] < dims[UnusedCargo] {
452 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * quantity)
455 other[Edens] = addr[Edens]
456 other[UnusedCargo] = addr[UnusedCargo]
461 func FillStateTable2Iteration(data planet_data, dims []int, table []State,
462 addr []int, f func(planet_data, []int, []State, []int)) {
463 /* TODO: Justify the safety of the combination of this dimension
464 * iteration and the various phases f. */
465 for addr[Hold] = 0; addr[Hold] < dims[Hold]; addr[Hold]++ {
466 for addr[Cloaks] = 0; addr[Cloaks] < dims[Cloaks]; addr[Cloaks]++ {
467 for addr[UnusedCargo] = 0; addr[UnusedCargo] < dims[UnusedCargo]; addr[UnusedCargo]++ {
468 for addr[BuyFighters] = 0; addr[BuyFighters] < dims[BuyFighters]; addr[BuyFighters]++ {
469 for addr[BuyShields] = 0; addr[BuyShields] < dims[BuyShields]; addr[BuyShields]++ {
470 for addr[Visit] = 0; addr[Visit] < dims[Visit]; addr[Visit]++ {
471 f(data, dims, table, addr)
480 func FillStateTable2(data planet_data, dims []int, table []State,
481 addr []int, barrier chan<- bool) {
482 FillStateTable2Iteration(data, dims, table, addr, FillCellByArriving)
483 FillStateTable2Iteration(data, dims, table, addr, FillCellBySelling)
484 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuying)
485 FillStateTable2Iteration(data, dims, table, addr, FillCellByMisc)
486 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuyingEdens)
492 /* Filling the state table is a set of nested for loops NumDimensions deep.
493 * We split this into two procedures: 1 and 2. #1 is the outer, slowest-
494 * changing indexes. #1 fires off many calls to #2 that run in parallel.
495 * The order of the nesting of the dimensions, the order of iteration within
496 * each dimension, and where the 1 / 2 split is placed are carefully chosen
497 * to make this arrangement safe.
499 * Outermost two layers: Go from high-energy states (lots of fuel, edens) to
500 * low-energy state. These must be processed sequentially and in this order
501 * because you travel through high-energy states to get to the low-energy
504 * Third layer: Planet. This is a good layer to parallelize on. There's
505 * high enough cardinality that we don't have to mess with parallelizing
506 * multiple layers for good utilization (on 2011 machines). Each thread
507 * works on one planet's states and need not synchronize with peer threads.
509 func FillStateTable1(data planet_data, dims []int, table []State) {
510 barrier := make(chan bool, len(data.Planets))
511 eden_capacity := data.Commodities["Eden Warp Units"].Limit
512 work_units := (float64(*fuel) + 1) * (float64(eden_capacity) + 1)
514 for fuel_remaining := *fuel; fuel_remaining >= 0; fuel_remaining-- {
515 /* Make an Eden-buying pass (Eden vendors' energy gradient
516 * along the Edens dimension runs backwards) */
517 for edens_remaining := 0; edens_remaining <= eden_capacity; edens_remaining++ {
518 for planet := range data.Planets {
519 if _, available := data.Planets[planet].RelativePrices["Eden Warp Units"]; available {
520 addr := make([]int, len(dims))
521 addr[Edens] = edens_remaining
522 addr[Fuel] = fuel_remaining
523 addr[Location] = data.p2i[planet]
524 FillStateTable2(data, dims, table, addr, nil)
528 for edens_remaining := eden_capacity; edens_remaining >= 0; edens_remaining-- {
529 /* Do the brunt of the work */
530 for planet := range data.Planets {
531 addr := make([]int, len(dims))
532 addr[Edens] = edens_remaining
533 addr[Fuel] = fuel_remaining
534 addr[Location] = data.p2i[planet]
535 go FillStateTable2(data, dims, table, addr, barrier)
537 for _ = range data.Planets {
541 print(fmt.Sprintf("\r%3.0f%%", 100*work_done/work_units))
547 func FindBestState(data planet_data, dims []int, table []State) int {
548 addr := make([]int, NumDimensions)
549 addr[Edens] = *end_edens
550 addr[Cloaks] = dims[Cloaks] - 1
551 addr[BuyFighters] = dims[BuyFighters] - 1
552 addr[BuyShields] = dims[BuyShields] - 1
553 addr[Visit] = dims[Visit] - 1
554 // Fuel, Hold, UnusedCargo left at 0
557 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
558 if len(end()) == 0 || end()[data.i2p[addr[Location]]] {
559 index := EncodeIndex(dims, addr)
560 if table[index].value > max_value {
561 max_value = table[index].value
569 func Commas(n int) (s string) {
573 s = fmt.Sprintf(",%03d", r) + s
577 s = fmt.Sprint(r) + s
581 func DescribePath(data planet_data, dims []int, table []State, start int) (description []string) {
582 for index := start; index > 0 && table[index].from > 0; index = table[index].from {
584 addr := DecodeIndex(dims, index)
585 prev := DecodeIndex(dims, table[index].from)
586 if addr[Fuel] != prev[Fuel] {
587 from := data.i2p[prev[Location]]
588 to := data.i2p[addr[Location]]
589 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
591 if addr[Edens] == prev[Edens] - 1 {
592 from := data.i2p[prev[Location]]
593 to := data.i2p[addr[Location]]
594 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
596 if addr[Hold] != prev[Hold] {
598 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
599 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
600 } else if prev[Hold] == 0 {
601 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
602 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
604 panic("Switched cargo?")
608 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
609 // TODO: Dump cloaks, convert from cargo?
610 line += "Buy a Cloak"
612 if addr[Edens] > prev[Edens] {
613 line += fmt.Sprint("Buy ", addr[Edens] - prev[Edens], " Eden Warp Units")
615 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
616 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
618 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
619 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
622 line = fmt.Sprint(prev, " -> ", addr)
624 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value)) + line)
629 // (Example of a use case for generics in Go)
630 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
631 e2i := make(map[string]int, len(*m)+start_at)
632 i2e := make([]string, len(*m)+start_at)
641 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
642 e2i := make(map[string]int, len(*m)+start_at)
643 i2e := make([]string, len(*m)+start_at)
656 if *drone_price > 0 {
657 temp := data.Commodities["Fighter Drones"]
658 temp.BasePrice = *drone_price
659 data.Commodities["Fighter Drones"] = temp
661 if *battery_price > 0 {
662 temp := data.Commodities["Shield Batterys"]
663 temp.BasePrice = *battery_price
664 data.Commodities["Shield Batterys"] = temp
666 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
667 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
668 dims := DimensionSizes(data)
669 table := InitializeStateTable(data, dims)
670 FillStateTable1(data, dims, table)
671 best := FindBestState(data, dims, table)
673 print("Cannot acheive success criteria\n")
675 description := DescribePath(data, dims, table, best)
676 for i := len(description) - 1; i >= 0; i-- {
677 fmt.Println(description[i])