]> git.scottworley.com Git - planeteer/blame - planeteer.go
DescribePath()
[planeteer] / planeteer.go
CommitLineData
d07f3caa
SW
1/* Planeteer: Give trade route advice for Planets: The Exploration of Space
2 * Copyright (C) 2011 Scott Worley <sworley@chkno.net>
3 *
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.
8 *
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.
13 *
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/>.
16 */
17
18package main
19
20import "flag"
c45c1bca 21import "fmt"
d07f3caa
SW
22import "json"
23import "os"
c45c1bca
SW
24import "strings"
25
330093c1
SW
26var funds = flag.Int("funds", 0,
27 "Starting funds")
28
c45c1bca
SW
29var start = flag.String("start", "",
30 "The planet to start at")
d07f3caa 31
e346cb37 32var flight_plan_string = flag.String("flight_plan", "",
544108c4
SW
33 "Your hidey-holes for the day, comma-separated.")
34
c45c1bca 35var end = flag.String("end", "",
e9ff66cf 36 "A comma-separated list of acceptable ending planets.")
c45c1bca
SW
37
38var planet_data_file = flag.String("planet_data_file", "planet-data",
d07f3caa
SW
39 "The file to read planet data from")
40
e9ff66cf
SW
41var fuel = flag.Int("fuel", 16, "Reactor units")
42
43var hold = flag.Int("hold", 300, "Size of your cargo hold")
c45c1bca
SW
44
45var start_edens = flag.Int("start_edens", 0,
46 "How many Eden Warp Units are you starting with?")
47
48var end_edens = flag.Int("end_edens", 0,
49 "How many Eden Warp Units would you like to keep (not use)?")
50
51var cloak = flag.Bool("cloak", false,
52 "Make sure to end with a Device of Cloaking")
53
e9ff66cf 54var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
c45c1bca 55
e9ff66cf 56var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
c45c1bca
SW
57
58var visit_string = flag.String("visit", "",
59 "A comma-separated list of planets to make sure to visit")
60
61func visit() []string {
e346cb37
SW
62 if *visit_string == "" {
63 return []string{}
64 }
c45c1bca
SW
65 return strings.Split(*visit_string, ",")
66}
67
e346cb37
SW
68func flight_plan() []string {
69 if *flight_plan_string == "" {
70 return []string{}
71 }
72 return strings.Split(*flight_plan_string, ",")
73}
74
9b3b3d9a 75type Commodity struct {
9b3b3d9a
SW
76 BasePrice int
77 CanSell bool
78 Limit int
79}
12bc2cd7 80type Planet struct {
12bc2cd7
SW
81 BeaconOn bool
82 /* Use relative prices rather than absolute prices because you
83 can get relative prices without traveling to each planet. */
0e94bdac 84 RelativePrices map[string]int
12bc2cd7 85}
d07f3caa 86type planet_data struct {
0e94bdac
SW
87 Commodities map[string]Commodity
88 Planets map[string]Planet
e7e4bc13
SW
89 p2i, c2i map[string]int // Generated; not read from file
90 i2p, i2c []string // Generated; not read from file
d07f3caa
SW
91}
92
93func ReadData() (data planet_data) {
c45c1bca 94 f, err := os.Open(*planet_data_file)
d07f3caa
SW
95 if err != nil {
96 panic(err)
97 }
98 defer f.Close()
99 err = json.NewDecoder(f).Decode(&data)
100 if err != nil {
101 panic(err)
102 }
103 return
104}
105
c45c1bca
SW
106/* This program operates by filling in a state table representing the best
107 * possible trips you could make; the ones that makes you the most money.
108 * This is feasible because we don't look at all the possible trips.
109 * We define a list of things that are germane to this game and then only
110 * consider the best outcome in each possible game state.
111 *
112 * Each cell in the table represents a state in the game. In each cell,
113 * we track two things: 1. the most money you could possibly have while in
114 * that state and 2. one possible way to get into that state with that
115 * amount of money.
116 *
117 * A basic analysis can be done with a two-dimensional table: location and
118 * fuel. planeteer-1.0 used this two-dimensional table. This version
119 * adds features mostly by adding dimensions to this table.
120 *
121 * Note that the sizes of each dimension are data driven. Many dimensions
122 * collapse to one possible value (ie, disappear) if the corresponding
123 * feature is not enabled.
e7e4bc13
SW
124 *
125 * The order of the dimensions in the list of constants below determines
126 * their layout in RAM. The cargo-based 'dimensions' are not completely
127 * independent -- some combinations are illegal and not used. They are
128 * handled as three dimensions rather than one for simplicity. Placing
129 * these dimensions first causes the unused cells in the table to be
130 * grouped together in large blocks. This keeps them from polluting
131 * cache lines, and if they are large enough, prevent the memory manager
132 * from allocating pages for these areas at all.
e346cb37
SW
133 *
134 * If the table gets too big to fit in RAM:
135 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
136 * 24 combinations, only 15 are legal: a 38% savings.
137 * * Reduce the size of the Fuel dimension to 3. We only ever look
138 * backwards 2 units, so just rotate the logical values through
139 * the same 3 physical addresses. This is good for an 82% savings.
140 * * Reduce the size of the Edens dimension from 3 to 2, for the
141 * same reasons as Fuel above. 33% savings.
142 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
143 *
c45c1bca
SW
144 */
145
146// The official list of dimensions:
147const (
e9ff66cf 148 // Name Num Size Description
0e94bdac
SW
149 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
150 Cloaks // 2 2 # of Devices of Cloaking (0 or 1)
151 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
152 Fuel // 4 17 Reactor power left (0 - 16)
153 Location // 5 26 Location (which planet)
154 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
155 NeedFighters // 7 2 Errand: Buy fighter drones (needed or not)
156 NeedShields // 8 2 Errand: Buy shield batteries (needed or not)
157 Visit // 9 2**N Visit: Stop by these N planets in the route
c45c1bca
SW
158
159 NumDimensions
160)
161
162func bint(b bool) int {
0e94bdac
SW
163 if b {
164 return 1
165 }
c45c1bca
SW
166 return 0
167}
168
169func DimensionSizes(data planet_data) []int {
170 eden_capacity := data.Commodities["Eden Warp Units"].Limit
330093c1
SW
171 if *start_edens > eden_capacity {
172 eden_capacity = *start_edens
173 }
c45c1bca 174 cloak_capacity := bint(*cloak)
64d87250
SW
175 dims := make([]int, NumDimensions)
176 dims[Edens] = eden_capacity + 1
177 dims[Cloaks] = cloak_capacity + 1
178 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
179 dims[Fuel] = *fuel + 1
180 dims[Location] = len(data.Planets)
181 dims[Hold] = len(data.Commodities)
182 dims[NeedFighters] = bint(*drones > 0) + 1
183 dims[NeedShields] = bint(*batteries > 0) + 1
184 dims[Visit] = 1 << uint(len(visit()))
2f4ed5ca
SW
185
186 // Remind myself to add a line above when adding new dimensions
187 for i, dim := range dims {
188 if dim < 1 {
189 panic(i)
190 }
191 }
c45c1bca
SW
192 return dims
193}
194
195func StateTableSize(dims []int) int {
e346cb37 196 product := 1
c45c1bca 197 for _, size := range dims {
e346cb37 198 product *= size
c45c1bca 199 }
e346cb37 200 return product
c45c1bca
SW
201}
202
203type State struct {
544108c4 204 value, from int
c45c1bca
SW
205}
206
c45c1bca
SW
207func EncodeIndex(dims, addr []int) int {
208 index := addr[0]
e346cb37
SW
209 if addr[0] > dims[0] {
210 panic(0)
211 }
330093c1 212 for i := 1; i < NumDimensions; i++ {
e346cb37
SW
213 if addr[i] > dims[i] {
214 panic(i)
215 }
0e94bdac 216 index = index*dims[i] + addr[i]
c45c1bca
SW
217 }
218 return index
219}
220
221func DecodeIndex(dims []int, index int) []int {
330093c1
SW
222 addr := make([]int, NumDimensions)
223 for i := NumDimensions - 1; i > 0; i-- {
c45c1bca
SW
224 addr[i] = index % dims[i]
225 index /= dims[i]
226 }
227 addr[0] = index
228 return addr
229}
230
330093c1
SW
231func InitializeStateTable(data planet_data, dims []int) []State {
232 table := make([]State, StateTableSize(dims))
233
234 addr := make([]int, NumDimensions)
235 addr[Fuel] = *fuel
236 addr[Edens] = *start_edens
237 addr[Location] = data.p2i[*start]
238 table[EncodeIndex(dims, addr)].value = *funds
239
240 return table
e346cb37
SW
241}
242
330093c1
SW
243/* These four fill procedures fill in the cell at address addr by
244 * looking at all the possible ways to reach this cell and selecting
245 * the best one.
544108c4
SW
246 *
247 * The other obvious implementation choice is to do this the other way
248 * around -- for each cell, conditionally overwrite all the other cells
249 * that are reachable *from* the considered cell. We choose gathering
250 * reads over scattering writes to avoid having to take a bunch of locks.
544108c4 251 */
330093c1
SW
252
253func UpdateCell(table []State, here, there, value_difference int) {
254 possible_value := table[there].value + value_difference
255 if table[there].value > 0 && possible_value > table[here].value {
256 table[here].value = possible_value
257 table[here].from = there
258 }
259}
260
261func FillCellByArriving(data planet_data, dims []int, table []State, addr []int) {
e346cb37
SW
262 my_index := EncodeIndex(dims, addr)
263 other := make([]int, NumDimensions)
264 copy(other, addr)
265
266 /* Travel here via a 2-fuel unit jump */
330093c1 267 if addr[Fuel]+2 < dims[Fuel] {
e346cb37 268 other[Fuel] = addr[Fuel] + 2
330093c1
SW
269 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
270 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
e346cb37
SW
271 }
272 other[Location] = addr[Location]
273 other[Fuel] = addr[Fuel]
274 }
275
276 /* Travel here via a hidey hole */
330093c1 277 if addr[Fuel]+1 < dims[Fuel] {
e346cb37
SW
278 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
279 if hole_index < len(flight_plan()) {
280 other[Fuel] = addr[Fuel] + 1
281 other[Location] = data.p2i[flight_plan()[hole_index]]
330093c1
SW
282 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
283 other[Location] = addr[Location]
e346cb37
SW
284 other[Fuel] = addr[Fuel]
285 }
286 }
287
544108c4 288 /* Travel here via Eden Warp Unit */
330093c1
SW
289 for other[Edens] = addr[Edens] + 1; other[Edens] < dims[Edens]; other[Edens]++ {
290 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
291 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
292 }
293 }
294 other[Location] = addr[Location]
295 other[Edens] = addr[Edens]
296}
297
298func FillCellBySelling(data planet_data, dims []int, table []State, addr []int) {
299 if addr[Hold] > 0 {
300 // Can't sell and still have cargo
301 return
302 }
303 if addr[UnusedCargo] > 0 {
304 // Can't sell everything and still have 'unused' holds
305 return
306 }
307 my_index := EncodeIndex(dims, addr)
308 other := make([]int, NumDimensions)
309 copy(other, addr)
310 planet := data.i2p[addr[Location]]
311 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
312 commodity := data.i2c[other[Hold]]
313 if !data.Commodities[commodity].CanSell {
314 // TODO: Dump cargo
315 continue
316 }
317 relative_price, available := data.Planets[planet].RelativePrices[commodity]
318 if !available {
319 continue
320 }
321 base_price := data.Commodities[commodity].BasePrice
322 absolute_price := relative_price * base_price
323 sell_price := int(float64(absolute_price) * 0.9)
324
325 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
326
327 quantity := *hold - other[UnusedCargo] // TODO: Partial sales
328 sale_value := quantity * sell_price
329 UpdateCell(table, my_index, EncodeIndex(dims, other), sale_value)
330 }
331 }
332 other[UnusedCargo] = addr[UnusedCargo]
333}
334
335func FillCellByBuying(data planet_data, dims []int, table []State, addr []int) {
336 if addr[Hold] == 0 {
337 // Can't buy and then have nothing
338 return
339 }
340 my_index := EncodeIndex(dims, addr)
341 other := make([]int, NumDimensions)
342 copy(other, addr)
343 planet := data.i2p[addr[Location]]
344 commodity := data.i2c[addr[Hold]]
345 if !data.Commodities[commodity].CanSell {
346 return
347 }
348 relative_price, available := data.Planets[planet].RelativePrices[commodity]
349 if !available {
350 return
351 }
352 base_price := data.Commodities[commodity].BasePrice
353 absolute_price := relative_price * base_price
354 quantity := *hold - addr[UnusedCargo]
355 total_price := quantity * absolute_price
356 other[Hold] = 0
357 UpdateCell(table, my_index, EncodeIndex(dims, other), -total_price)
358}
359
360func FillCellByMisc(data planet_data, dims []int, table []State, addr []int) {
544108c4
SW
361 /* Buy Eden warp units */
362 /* Buy a Device of Cloaking */
363 /* Silly: Dump a Device of Cloaking */
364 /* Buy Fighter Drones */
365 /* Buy Shield Batteries */
544108c4 366 /* Visit this planet */
e7e4bc13
SW
367}
368
330093c1
SW
369func FillStateTable2Iteration(data planet_data, dims []int, table []State,
370addr []int, f func(planet_data, []int, []State, []int)) {
371 /* TODO: Justify the safety of the combination of this dimension
372 * iteration and the various phases f. */
e7e4bc13
SW
373 for addr[Hold] = 0; addr[Hold] < dims[Hold]; addr[Hold]++ {
374 for addr[Cloaks] = 0; addr[Cloaks] < dims[Cloaks]; addr[Cloaks]++ {
a1f10151 375 for addr[UnusedCargo] = 0; addr[UnusedCargo] < dims[UnusedCargo]; addr[UnusedCargo]++ {
330093c1
SW
376 for addr[NeedFighters] = 0; addr[NeedFighters] < dims[NeedFighters]; addr[NeedFighters]++ {
377 for addr[NeedShields] = 0; addr[NeedShields] < dims[NeedShields]; addr[NeedShields]++ {
378 for addr[Visit] = 0; addr[Visit] < dims[Visit]; addr[Visit]++ {
379 f(data, dims, table, addr)
e7e4bc13
SW
380 }
381 }
382 }
383 }
384 }
385 }
330093c1
SW
386}
387
388func FillStateTable2(data planet_data, dims []int, table []State,
389fuel_remaining, edens_remaining int, planet string, barrier chan<- bool) {
390 addr := make([]int, len(dims))
391 addr[Edens] = edens_remaining
392 addr[Fuel] = fuel_remaining
393 addr[Location] = data.p2i[planet]
394 FillStateTable2Iteration(data, dims, table, addr, FillCellByArriving)
395 FillStateTable2Iteration(data, dims, table, addr, FillCellBySelling)
396 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuying)
397 FillStateTable2Iteration(data, dims, table, addr, FillCellByMisc)
e7e4bc13
SW
398 barrier <- true
399}
400
401/* Filling the state table is a set of nested for loops NumDimensions deep.
402 * We split this into two procedures: 1 and 2. #1 is the outer, slowest-
403 * changing indexes. #1 fires off many calls to #2 that run in parallel.
404 * The order of the nesting of the dimensions, the order of iteration within
405 * each dimension, and where the 1 / 2 split is placed are carefully chosen
406 * to make this arrangement safe.
407 *
408 * Outermost two layers: Go from high-energy states (lots of fuel, edens) to
409 * low-energy state. These must be processed sequentially and in this order
410 * because you travel through high-energy states to get to the low-energy
411 * states.
412 *
413 * Third layer: Planet. This is a good layer to parallelize on. There's
414 * high enough cardinality that we don't have to mess with parallelizing
415 * multiple layers for good utilization (on 2011 machines). Each thread
416 * works on one planet's states and need not synchronize with peer threads.
417 */
e346cb37 418func FillStateTable1(data planet_data, dims []int, table []State) {
e7e4bc13
SW
419 barrier := make(chan bool, len(data.Planets))
420 eden_capacity := data.Commodities["Eden Warp Units"].Limit
421 work_units := (float64(*fuel) + 1) * (float64(eden_capacity) + 1)
422 work_done := 0.0
423 for fuel_remaining := *fuel; fuel_remaining >= 0; fuel_remaining-- {
a1f10151 424 for edens_remaining := eden_capacity; edens_remaining >= 0; edens_remaining-- {
e7e4bc13
SW
425 for planet := range data.Planets {
426 go FillStateTable2(data, dims, table, fuel_remaining,
427 edens_remaining, planet, barrier)
428 }
429 for _ = range data.Planets {
430 <-barrier
431 }
432 work_done++
a1f10151 433 fmt.Printf("\r%3.0f%%", 100*work_done/work_units)
e7e4bc13
SW
434 }
435 }
e346cb37 436 print("\n")
e7e4bc13
SW
437}
438
ad4de13f
SW
439func FindBestState(data planet_data, dims []int, table []State) int {
440 addr := make([]int, NumDimensions)
441 addr[Edens] = *end_edens
442 addr[Cloaks] = dims[Cloaks] - 1
443 addr[NeedFighters] = dims[NeedFighters] - 1
444 addr[NeedShields] = dims[NeedShields] - 1
445 addr[Visit] = dims[Visit] - 1
446 // Fuel, Hold, UnusedCargo left at 0
447 var max_index int
448 max_value := 0
449 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
450 index := EncodeIndex(dims, addr)
451 if table[index].value > max_value {
452 max_value = table[index].value
453 max_index = index
454 }
455 }
456 return max_index
457}
458
2f4a9ae8
SW
459func DescribePath(data planet_data, dims []int, table []State, start int) (description []string) {
460 for index := start; index > 0 && table[index].from > 0; index = table[index].from {
461 line := fmt.Sprintf("%10v", table[index].value)
462 addr := DecodeIndex(dims, index)
463 prev := DecodeIndex(dims, table[index].from)
464 if addr[Location] != prev[Location] {
465 from := data.i2p[prev[Location]]
466 to := data.i2p[addr[Location]]
467 if addr[Fuel] != prev[Fuel] {
468 line += fmt.Sprintf(" Jump from %v to %v (%v reactor units)", from, to, prev[Fuel]-addr[Fuel])
469 } else if addr[Edens] != prev[Edens] {
470 line += fmt.Sprintf(" Eden warp from %v to %v", from, to)
471 } else {
472 panic("Traveling without fuel?")
473 }
474 }
475 if addr[Hold] != prev[Hold] {
476 if addr[Hold] == 0 {
477 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
478 line += fmt.Sprintf(" Sell %v %v", quantity, data.i2c[prev[Hold]])
479 } else if prev[Hold] == 0 {
480 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
481 line += fmt.Sprintf(" Buy %v %v", quantity, data.i2c[addr[Hold]])
482 } else {
483 panic("Switched cargo?")
484 }
485
486 }
487 description = append(description, line)
488 }
489 return
490}
491
c45c1bca 492// (Example of a use case for generics in Go)
e7e4bc13 493func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
a1f10151
SW
494 e2i := make(map[string]int, len(*m)+start_at)
495 i2e := make([]string, len(*m)+start_at)
e7e4bc13 496 i := start_at
c45c1bca 497 for e := range *m {
e7e4bc13
SW
498 e2i[e] = i
499 i2e[i] = e
c45c1bca
SW
500 i++
501 }
e7e4bc13 502 return e2i, i2e
c45c1bca 503}
e7e4bc13 504func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
a1f10151
SW
505 e2i := make(map[string]int, len(*m)+start_at)
506 i2e := make([]string, len(*m)+start_at)
e7e4bc13 507 i := start_at
c45c1bca 508 for e := range *m {
e7e4bc13
SW
509 e2i[e] = i
510 i2e[i] = e
c45c1bca
SW
511 i++
512 }
e7e4bc13 513 return e2i, i2e
c45c1bca
SW
514}
515
d07f3caa
SW
516func main() {
517 flag.Parse()
518 data := ReadData()
e7e4bc13
SW
519 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
520 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
c45c1bca 521 dims := DimensionSizes(data)
330093c1 522 table := InitializeStateTable(data, dims)
e346cb37 523 FillStateTable1(data, dims, table)
ad4de13f
SW
524 best := FindBestState(data, dims, table)
525 fmt.Printf("Best state: %v (%v) with $%v\n",
526 best, DecodeIndex(dims, best), table[best].value)
2f4a9ae8
SW
527 description := DescribePath(data, dims, table, best)
528 for i := len(description) - 1; i >= 0; i-- {
529 print(description[i], "\n")
530 }
d07f3caa 531}