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/>.
24 import "runtime/pprof"
27 var funds = flag.Int("funds", 0,
30 var start = flag.String("start", "",
31 "The planet to start at")
33 var flight_plan_string = flag.String("flight_plan", "",
34 "Your hyper-holes for the day, comma-separated.")
36 var end_string = flag.String("end", "",
37 "A comma-separated list of acceptable ending planets.")
39 var planet_data_file = flag.String("planet_data_file", "planet-data",
40 "The file to read planet data from")
42 var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
44 var hold = flag.Int("hold", 300, "Size of your cargo hold")
46 var start_edens = flag.Int("start_edens", 0,
47 "How many Eden Warp Units are you starting with?")
49 var end_edens = flag.Int("end_edens", 0,
50 "How many Eden Warp Units would you like to keep (not use)?")
52 var cloak = flag.Bool("cloak", false,
53 "Make sure to end with a Device of Cloaking")
55 var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
57 var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
59 var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
61 var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
63 var visit_string = flag.String("visit", "",
64 "A comma-separated list of planets to make sure to visit")
66 var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
69 var visit_cache []string
70 func visit() []string {
71 if visit_cache == nil {
72 if *visit_string == "" {
75 visit_cache = strings.Split(*visit_string, ",")
80 var flight_plan_cache []string
81 func flight_plan() []string {
82 if flight_plan_cache == nil {
83 if *flight_plan_string == "" {
86 flight_plan_cache = strings.Split(*flight_plan_string, ",")
88 return flight_plan_cache
91 var end_cache map[string]bool
92 func end() map[string]bool {
94 if *end_string == "" {
97 m := make(map[string]bool)
98 for _, p := range strings.Split(*end_string, ",") {
106 type Commodity struct {
114 /* Use relative prices rather than absolute prices because you
115 can get relative prices without traveling to each planet. */
116 RelativePrices map[string]int
118 type planet_data struct {
119 Commodities map[string]Commodity
120 Planets map[string]Planet
121 p2i, c2i map[string]int // Generated; not read from file
122 i2p, i2c []string // Generated; not read from file
125 func ReadData() (data planet_data) {
126 f, err := os.Open(*planet_data_file)
131 err = json.NewDecoder(f).Decode(&data)
138 /* This program operates by filling in a state table representing the best
139 * possible trips you could make; the ones that makes you the most money.
140 * This is feasible because we don't look at all the possible trips.
141 * We define a list of things that are germane to this game and then only
142 * consider the best outcome in each possible game state.
144 * Each cell in the table represents a state in the game. In each cell,
145 * we track two things: 1. the most money you could possibly have while in
146 * that state and 2. one possible way to get into that state with that
149 * A basic analysis can be done with a two-dimensional table: location and
150 * fuel. planeteer-1.0 used this two-dimensional table. This version
151 * adds features mostly by adding dimensions to this table.
153 * Note that the sizes of each dimension are data driven. Many dimensions
154 * collapse to one possible value (ie, disappear) if the corresponding
155 * feature is not enabled.
157 * The order of the dimensions in the list of constants below determines
158 * their layout in RAM. The cargo-based 'dimensions' are not completely
159 * independent -- some combinations are illegal and not used. They are
160 * handled as three dimensions rather than one for simplicity. Placing
161 * these dimensions first causes the unused cells in the table to be
162 * grouped together in large blocks. This keeps them from polluting
163 * cache lines, and if they are large enough, prevent the memory manager
164 * from allocating pages for these areas at all.
166 * If the table gets too big to fit in RAM:
167 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
168 * 24 combinations, only 15 are legal: a 38% savings.
169 * * Reduce the size of the Fuel dimension to 3. We only ever look
170 * backwards 2 units, so just rotate the logical values through
171 * the same 3 physical addresses. This is good for an 82% savings.
172 * * Reduce the size of the Edens dimension from 3 to 2, for the
173 * same reasons as Fuel above. 33% savings.
174 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
178 // The official list of dimensions:
180 // Name Num Size Description
181 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
182 Cloaks // 2 2 # of Devices of Cloaking (0 or 1)
183 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
184 Fuel // 4 17 Hyper jump power left (0 - 16)
185 Location // 5 26 Location (which planet)
186 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
187 BuyFighters // 7 2 Errand: Buy fighter drones
188 BuyShields // 8 2 Errand: Buy shield batteries
189 Visit // 9 2**N Visit: Stop by these N planets in the route
194 func bint(b bool) int {
201 func DimensionSizes(data planet_data) []int {
202 eden_capacity := data.Commodities["Eden Warp Units"].Limit
203 if *start_edens > eden_capacity {
204 eden_capacity = *start_edens
206 cloak_capacity := bint(*cloak)
207 dims := make([]int, NumDimensions)
208 dims[Edens] = eden_capacity + 1
209 dims[Cloaks] = cloak_capacity + 1
210 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
211 dims[Fuel] = *fuel + 1
212 dims[Location] = len(data.Planets)
213 dims[Hold] = len(data.Commodities) + 1
214 dims[BuyFighters] = bint(*drones > 0) + 1
215 dims[BuyShields] = bint(*batteries > 0) + 1
216 dims[Visit] = 1 << uint(len(visit()))
218 // Remind myself to add a line above when adding new dimensions
219 for i, dim := range dims {
227 func StateTableSize(dims []int) int {
229 for _, size := range dims {
239 func EncodeIndex(dims, addr []int) int {
241 if addr[0] > dims[0] {
244 for i := 1; i < NumDimensions; i++ {
245 if addr[i] < 0 || addr[i] > dims[i] {
248 index = index*dims[i] + addr[i]
253 func DecodeIndex(dims []int, index int) []int {
254 addr := make([]int, NumDimensions)
255 for i := NumDimensions - 1; i > 0; i-- {
256 addr[i] = index % dims[i]
263 func InitializeStateTable(data planet_data, dims []int) []State {
264 table := make([]State, StateTableSize(dims))
266 addr := make([]int, NumDimensions)
268 addr[Edens] = *start_edens
269 addr[Location] = data.p2i[*start]
270 table[EncodeIndex(dims, addr)].value = *funds
275 /* These four fill procedures fill in the cell at address addr by
276 * looking at all the possible ways to reach this cell and selecting
279 * The other obvious implementation choice is to do this the other way
280 * around -- for each cell, conditionally overwrite all the other cells
281 * that are reachable *from* the considered cell. We choose gathering
282 * reads over scattering writes to avoid having to take a bunch of locks.
285 func UpdateCell(table []State, here, there, value_difference int) {
286 possible_value := table[there].value + value_difference
287 if table[there].value > 0 && possible_value > table[here].value {
288 table[here].value = possible_value
289 table[here].from = there
293 func FillCellByArriving(data planet_data, dims []int, table []State, addr []int) {
294 my_index := EncodeIndex(dims, addr)
295 other := make([]int, NumDimensions)
298 /* Travel here via a 2-fuel unit jump */
299 if addr[Fuel]+2 < dims[Fuel] {
300 other[Fuel] = addr[Fuel] + 2
301 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
302 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
303 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
306 other[Location] = addr[Location]
307 other[Fuel] = addr[Fuel]
310 /* Travel here via a hyper hole */
311 if addr[Fuel]+1 < dims[Fuel] {
312 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
313 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
314 other[Fuel] = addr[Fuel] + 1
315 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
316 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
318 other[Location] = addr[Location]
319 other[Fuel] = addr[Fuel]
323 /* Travel here via Eden Warp Unit */
324 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 1 {
325 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
327 other[Edens] = addr[Edens] + 1
328 other[UnusedCargo] = addr[UnusedCargo] - 1
329 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
330 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
332 other[Location] = addr[Location]
333 other[UnusedCargo] = addr[UnusedCargo]
334 other[Edens] = addr[Edens]
339 func FillCellBySelling(data planet_data, dims []int, table []State, addr []int) {
340 if data.Planets[data.i2p[addr[Location]]].Private {
341 // Can't do commerce on private planets
345 // Can't sell and still have cargo
348 if addr[UnusedCargo] > 0 {
349 // Can't sell everything and still have 'unused' holds
352 my_index := EncodeIndex(dims, addr)
353 other := make([]int, NumDimensions)
355 planet := data.i2p[addr[Location]]
356 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
357 commodity := data.i2c[other[Hold]]
358 if !data.Commodities[commodity].CanSell {
362 relative_price, available := data.Planets[planet].RelativePrices[commodity]
366 base_price := data.Commodities[commodity].BasePrice
367 absolute_price := float64(base_price) * float64(relative_price) / 100.0
368 sell_price := int(absolute_price * 0.9)
370 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
372 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
373 sale_value := quantity * sell_price
374 UpdateCell(table, my_index, EncodeIndex(dims, other), sale_value)
377 other[UnusedCargo] = addr[UnusedCargo]
380 func FillCellByBuying(data planet_data, dims []int, table []State, addr []int) {
381 if data.Planets[data.i2p[addr[Location]]].Private {
382 // Can't do commerce on private planets
386 // Can't buy and then have nothing
389 my_index := EncodeIndex(dims, addr)
390 other := make([]int, NumDimensions)
392 planet := data.i2p[addr[Location]]
393 commodity := data.i2c[addr[Hold]]
394 if !data.Commodities[commodity].CanSell {
397 relative_price, available := data.Planets[planet].RelativePrices[commodity]
401 base_price := data.Commodities[commodity].BasePrice
402 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
403 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
404 total_price := quantity * absolute_price
406 other[UnusedCargo] = 0
407 UpdateCell(table, my_index, EncodeIndex(dims, other), -total_price)
408 other[UnusedCargo] = addr[UnusedCargo]
409 other[Hold] = addr[Hold]
412 func FillCellByMisc(data planet_data, dims []int, table []State, addr []int) {
413 my_index := EncodeIndex(dims, addr)
414 other := make([]int, NumDimensions)
417 /* Buy a Device of Cloaking */
418 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
419 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
421 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
423 if other[Hold] != 0 {
424 other[UnusedCargo] = addr[UnusedCargo] + 1
426 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price)
427 other[UnusedCargo] = addr[UnusedCargo]
428 other[Cloaks] = addr[Cloaks]
432 /* Silly: Dump a Device of Cloaking */
434 /* Buy Fighter Drones */
435 if addr[BuyFighters] == 1 {
436 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
438 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
439 other[BuyFighters] = 0
440 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * *drones)
441 other[BuyFighters] = addr[BuyFighters]
445 /* Buy Shield Batteries */
446 if addr[BuyShields] == 1 {
447 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
449 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
450 other[BuyShields] = 0
451 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * *batteries)
452 other[BuyShields] = addr[BuyShields]
456 /* Visit this planet */
458 for i = 0; i < uint(len(visit())); i++ {
459 if addr[Visit] & (1 << i) != 0 && visit()[i] == data.i2p[addr[Location]] {
460 other[Visit] = addr[Visit] & ^(1 << i)
461 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
464 other[Visit] = addr[Visit]
468 func FillCellByBuyingEdens(data planet_data, dims []int, table []State, addr []int) {
469 my_index := EncodeIndex(dims, addr)
470 other := make([]int, NumDimensions)
473 /* Buy Eden warp units */
474 eden_limit := data.Commodities["Eden Warp Units"].Limit
475 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
476 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
478 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
479 for quantity := addr[Edens]; quantity > 0; quantity-- {
480 other[Edens] = addr[Edens] - quantity
482 other[UnusedCargo] = addr[UnusedCargo] + quantity
484 if other[UnusedCargo] < dims[UnusedCargo] {
485 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price * quantity)
488 other[Edens] = addr[Edens]
489 other[UnusedCargo] = addr[UnusedCargo]
494 func FillStateTable2Iteration(data planet_data, dims []int, table []State,
495 addr []int, f func(planet_data, []int, []State, []int)) {
496 /* TODO: Justify the safety of the combination of this dimension
497 * iteration and the various phases f. */
498 for addr[Hold] = 0; addr[Hold] < dims[Hold]; addr[Hold]++ {
499 for addr[Cloaks] = 0; addr[Cloaks] < dims[Cloaks]; addr[Cloaks]++ {
500 for addr[UnusedCargo] = 0; addr[UnusedCargo] < dims[UnusedCargo]; addr[UnusedCargo]++ {
501 for addr[BuyFighters] = 0; addr[BuyFighters] < dims[BuyFighters]; addr[BuyFighters]++ {
502 for addr[BuyShields] = 0; addr[BuyShields] < dims[BuyShields]; addr[BuyShields]++ {
503 for addr[Visit] = 0; addr[Visit] < dims[Visit]; addr[Visit]++ {
504 f(data, dims, table, addr)
513 func FillStateTable2(data planet_data, dims []int, table []State,
514 addr []int, barrier chan<- bool) {
515 FillStateTable2Iteration(data, dims, table, addr, FillCellByArriving)
516 FillStateTable2Iteration(data, dims, table, addr, FillCellBySelling)
517 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuying)
518 FillStateTable2Iteration(data, dims, table, addr, FillCellByMisc)
519 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuyingEdens)
525 /* Filling the state table is a set of nested for loops NumDimensions deep.
526 * We split this into two procedures: 1 and 2. #1 is the outer, slowest-
527 * changing indexes. #1 fires off many calls to #2 that run in parallel.
528 * The order of the nesting of the dimensions, the order of iteration within
529 * each dimension, and where the 1 / 2 split is placed are carefully chosen
530 * to make this arrangement safe.
532 * Outermost two layers: Go from high-energy states (lots of fuel, edens) to
533 * low-energy state. These must be processed sequentially and in this order
534 * because you travel through high-energy states to get to the low-energy
537 * Third layer: Planet. This is a good layer to parallelize on. There's
538 * high enough cardinality that we don't have to mess with parallelizing
539 * multiple layers for good utilization (on 2011 machines). Each thread
540 * works on one planet's states and need not synchronize with peer threads.
542 func FillStateTable1(data planet_data, dims []int, table []State) {
543 barrier := make(chan bool, len(data.Planets))
544 eden_capacity := data.Commodities["Eden Warp Units"].Limit
545 work_units := (float64(*fuel) + 1) * (float64(eden_capacity) + 1)
547 for fuel_remaining := *fuel; fuel_remaining >= 0; fuel_remaining-- {
548 /* Make an Eden-buying pass (Eden vendors' energy gradient
549 * along the Edens dimension runs backwards) */
550 for edens_remaining := 0; edens_remaining <= eden_capacity; edens_remaining++ {
551 for planet := range data.Planets {
552 if _, available := data.Planets[planet].RelativePrices["Eden Warp Units"]; available {
553 addr := make([]int, len(dims))
554 addr[Edens] = edens_remaining
555 addr[Fuel] = fuel_remaining
556 addr[Location] = data.p2i[planet]
557 FillStateTable2(data, dims, table, addr, nil)
561 for edens_remaining := eden_capacity; edens_remaining >= 0; edens_remaining-- {
562 /* Do the brunt of the work */
563 for planet := range data.Planets {
564 addr := make([]int, len(dims))
565 addr[Edens] = edens_remaining
566 addr[Fuel] = fuel_remaining
567 addr[Location] = data.p2i[planet]
568 go FillStateTable2(data, dims, table, addr, barrier)
570 for _ = range data.Planets {
574 print(fmt.Sprintf("\r%3.0f%%", 100*work_done/work_units))
580 func FindBestState(data planet_data, dims []int, table []State) int {
581 addr := make([]int, NumDimensions)
582 addr[Edens] = *end_edens
583 addr[Cloaks] = dims[Cloaks] - 1
584 addr[BuyFighters] = dims[BuyFighters] - 1
585 addr[BuyShields] = dims[BuyShields] - 1
586 addr[Visit] = dims[Visit] - 1
587 // Hold and UnusedCargo left at 0
590 for addr[Fuel] = 0; addr[Fuel] < 2; addr[Fuel]++ {
591 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
592 if len(end()) == 0 || end()[data.i2p[addr[Location]]] {
593 index := EncodeIndex(dims, addr)
594 if table[index].value > max_value {
595 max_value = table[index].value
604 func Commas(n int) (s string) {
608 s = fmt.Sprintf(",%03d", r) + s
612 s = fmt.Sprint(r) + s
616 func DescribePath(data planet_data, dims []int, table []State, start int) (description []string) {
617 for index := start; index > 0 && table[index].from > 0; index = table[index].from {
619 addr := DecodeIndex(dims, index)
620 prev := DecodeIndex(dims, table[index].from)
621 if addr[Fuel] != prev[Fuel] {
622 from := data.i2p[prev[Location]]
623 to := data.i2p[addr[Location]]
624 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
626 if addr[Edens] == prev[Edens] - 1 {
627 from := data.i2p[prev[Location]]
628 to := data.i2p[addr[Location]]
629 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
631 if addr[Hold] != prev[Hold] {
633 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
634 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
635 } else if prev[Hold] == 0 {
636 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
637 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
639 panic("Switched cargo?")
643 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
644 // TODO: Dump cloaks, convert from cargo?
645 line += "Buy a Cloak"
647 if addr[Edens] > prev[Edens] {
648 line += fmt.Sprint("Buy ", addr[Edens] - prev[Edens], " Eden Warp Units")
650 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
651 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
653 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
654 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
656 if addr[Visit] != prev[Visit] {
657 // TODO: verify that the bit chat changed is addr[Location]
658 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
661 line = fmt.Sprint(prev, " -> ", addr)
663 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value)) + line)
668 // (Example of a use case for generics in Go)
669 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
670 e2i := make(map[string]int, len(*m)+start_at)
671 i2e := make([]string, len(*m)+start_at)
680 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
681 e2i := make(map[string]int, len(*m)+start_at)
682 i2e := make([]string, len(*m)+start_at)
694 if *cpuprofile != "" {
695 f, err := os.Create(*cpuprofile)
699 pprof.StartCPUProfile(f)
700 defer pprof.StopCPUProfile()
703 if *drone_price > 0 {
704 temp := data.Commodities["Fighter Drones"]
705 temp.BasePrice = *drone_price
706 data.Commodities["Fighter Drones"] = temp
708 if *battery_price > 0 {
709 temp := data.Commodities["Shield Batterys"]
710 temp.BasePrice = *battery_price
711 data.Commodities["Shield Batterys"] = temp
713 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
714 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
715 dims := DimensionSizes(data)
716 table := InitializeStateTable(data, dims)
717 FillStateTable1(data, dims, table)
718 best := FindBestState(data, dims, table)
720 print("Cannot acheive success criteria\n")
722 description := DescribePath(data, dims, table, best)
723 for i := len(description) - 1; i >= 0; i-- {
724 fmt.Println(description[i])