]> git.scottworley.com Git - planeteer/blob - planeteer.go
d5c359aaacf5f65bcc3791508da9342ba31cbc69
[planeteer] / planeteer.go
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
18 package main
19
20 import "flag"
21 import "fmt"
22 import "json"
23 import "os"
24 import "strings"
25
26 var funds = flag.Int("funds", 0,
27 "Starting funds")
28
29 var start = flag.String("start", "",
30 "The planet to start at")
31
32 var flight_plan_string = flag.String("flight_plan", "",
33 "Your hidey-holes for the day, comma-separated.")
34
35 var end = flag.String("end", "",
36 "A comma-separated list of acceptable ending planets.")
37
38 var planet_data_file = flag.String("planet_data_file", "planet-data",
39 "The file to read planet data from")
40
41 var fuel = flag.Int("fuel", 16, "Reactor units")
42
43 var hold = flag.Int("hold", 300, "Size of your cargo hold")
44
45 var start_edens = flag.Int("start_edens", 0,
46 "How many Eden Warp Units are you starting with?")
47
48 var end_edens = flag.Int("end_edens", 0,
49 "How many Eden Warp Units would you like to keep (not use)?")
50
51 var cloak = flag.Bool("cloak", false,
52 "Make sure to end with a Device of Cloaking")
53
54 var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
55
56 var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
57
58 var visit_string = flag.String("visit", "",
59 "A comma-separated list of planets to make sure to visit")
60
61 func visit() []string {
62 if *visit_string == "" {
63 return []string{}
64 }
65 return strings.Split(*visit_string, ",")
66 }
67
68 func flight_plan() []string {
69 if *flight_plan_string == "" {
70 return []string{}
71 }
72 return strings.Split(*flight_plan_string, ",")
73 }
74
75 type Commodity struct {
76 BasePrice int
77 CanSell bool
78 Limit int
79 }
80 type Planet struct {
81 BeaconOn bool
82 /* Use relative prices rather than absolute prices because you
83 can get relative prices without traveling to each planet. */
84 RelativePrices map[string]int
85 }
86 type planet_data struct {
87 Commodities map[string]Commodity
88 Planets map[string]Planet
89 p2i, c2i map[string]int // Generated; not read from file
90 i2p, i2c []string // Generated; not read from file
91 }
92
93 func ReadData() (data planet_data) {
94 f, err := os.Open(*planet_data_file)
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
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.
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.
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 *
144 */
145
146 // The official list of dimensions:
147 const (
148 // Name Num Size Description
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
158
159 NumDimensions
160 )
161
162 func bint(b bool) int {
163 if b {
164 return 1
165 }
166 return 0
167 }
168
169 func DimensionSizes(data planet_data) []int {
170 eden_capacity := data.Commodities["Eden Warp Units"].Limit
171 if *start_edens > eden_capacity {
172 eden_capacity = *start_edens
173 }
174 cloak_capacity := bint(*cloak)
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) + 1
182 dims[NeedFighters] = bint(*drones > 0) + 1
183 dims[NeedShields] = bint(*batteries > 0) + 1
184 dims[Visit] = 1 << uint(len(visit()))
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 }
192 return dims
193 }
194
195 func StateTableSize(dims []int) int {
196 product := 1
197 for _, size := range dims {
198 product *= size
199 }
200 return product
201 }
202
203 type State struct {
204 value, from int
205 }
206
207 func EncodeIndex(dims, addr []int) int {
208 index := addr[0]
209 if addr[0] > dims[0] {
210 panic(0)
211 }
212 for i := 1; i < NumDimensions; i++ {
213 if addr[i] > dims[i] {
214 panic(i)
215 }
216 index = index*dims[i] + addr[i]
217 }
218 return index
219 }
220
221 func DecodeIndex(dims []int, index int) []int {
222 addr := make([]int, NumDimensions)
223 for i := NumDimensions - 1; i > 0; i-- {
224 addr[i] = index % dims[i]
225 index /= dims[i]
226 }
227 addr[0] = index
228 return addr
229 }
230
231 func 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
241 }
242
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.
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.
251 */
252
253 func 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
261 func FillCellByArriving(data planet_data, dims []int, table []State, addr []int) {
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 */
267 if addr[Fuel]+2 < dims[Fuel] {
268 other[Fuel] = addr[Fuel] + 2
269 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
270 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
271 }
272 other[Location] = addr[Location]
273 other[Fuel] = addr[Fuel]
274 }
275
276 /* Travel here via a hidey hole */
277 if addr[Fuel]+1 < dims[Fuel] {
278 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
279 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
280 other[Fuel] = addr[Fuel] + 1
281 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
282 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
283 }
284 other[Location] = addr[Location]
285 other[Fuel] = addr[Fuel]
286 }
287 }
288
289 /* Travel here via Eden Warp Unit */
290 for other[Edens] = addr[Edens] + 1; other[Edens] < dims[Edens]; other[Edens]++ {
291 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
292 UpdateCell(table, my_index, EncodeIndex(dims, other), 0)
293 }
294 }
295 other[Location] = addr[Location]
296 other[Edens] = addr[Edens]
297 }
298
299 func FillCellBySelling(data planet_data, dims []int, table []State, addr []int) {
300 if addr[Hold] > 0 {
301 // Can't sell and still have cargo
302 return
303 }
304 if addr[UnusedCargo] > 0 {
305 // Can't sell everything and still have 'unused' holds
306 return
307 }
308 my_index := EncodeIndex(dims, addr)
309 other := make([]int, NumDimensions)
310 copy(other, addr)
311 planet := data.i2p[addr[Location]]
312 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
313 commodity := data.i2c[other[Hold]]
314 if !data.Commodities[commodity].CanSell {
315 // TODO: Dump cargo
316 continue
317 }
318 relative_price, available := data.Planets[planet].RelativePrices[commodity]
319 if !available {
320 continue
321 }
322 base_price := data.Commodities[commodity].BasePrice
323 absolute_price := float64(base_price) * float64(relative_price) / 100.0
324 sell_price := int(absolute_price * 0.9)
325
326 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
327
328 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
329 sale_value := quantity * sell_price
330 UpdateCell(table, my_index, EncodeIndex(dims, other), sale_value)
331 }
332 }
333 other[UnusedCargo] = addr[UnusedCargo]
334 }
335
336 func FillCellByBuying(data planet_data, dims []int, table []State, addr []int) {
337 if addr[Hold] == 0 {
338 // Can't buy and then have nothing
339 return
340 }
341 my_index := EncodeIndex(dims, addr)
342 other := make([]int, NumDimensions)
343 copy(other, addr)
344 planet := data.i2p[addr[Location]]
345 commodity := data.i2c[addr[Hold]]
346 if !data.Commodities[commodity].CanSell {
347 return
348 }
349 relative_price, available := data.Planets[planet].RelativePrices[commodity]
350 if !available {
351 return
352 }
353 base_price := data.Commodities[commodity].BasePrice
354 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
355 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
356 total_price := quantity * absolute_price
357 other[Hold] = 0
358 other[UnusedCargo] = 0
359 UpdateCell(table, my_index, EncodeIndex(dims, other), -total_price)
360 other[UnusedCargo] = addr[UnusedCargo]
361 other[Hold] = addr[Hold]
362 }
363
364 func FillCellByMisc(data planet_data, dims []int, table []State, addr []int) {
365 my_index := EncodeIndex(dims, addr)
366 other := make([]int, NumDimensions)
367 copy(other, addr)
368 /* Buy Eden warp units */
369 /* Buy a Device of Cloaking */
370 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
371 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
372 if available {
373 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
374 other[Cloaks] = 0
375 if other[Hold] != 0 {
376 other[UnusedCargo] = addr[UnusedCargo] + 1
377 }
378 UpdateCell(table, my_index, EncodeIndex(dims, other), -absolute_price)
379 other[UnusedCargo] = addr[UnusedCargo]
380 other[Cloaks] = addr[Cloaks]
381 }
382 }
383 /* Silly: Dump a Device of Cloaking */
384 /* Buy Fighter Drones */
385 /* Buy Shield Batteries */
386 /* Visit this planet */
387 }
388
389 func FillStateTable2Iteration(data planet_data, dims []int, table []State,
390 addr []int, f func(planet_data, []int, []State, []int)) {
391 /* TODO: Justify the safety of the combination of this dimension
392 * iteration and the various phases f. */
393 for addr[Hold] = 0; addr[Hold] < dims[Hold]; addr[Hold]++ {
394 for addr[Cloaks] = 0; addr[Cloaks] < dims[Cloaks]; addr[Cloaks]++ {
395 for addr[UnusedCargo] = 0; addr[UnusedCargo] < dims[UnusedCargo]; addr[UnusedCargo]++ {
396 for addr[NeedFighters] = 0; addr[NeedFighters] < dims[NeedFighters]; addr[NeedFighters]++ {
397 for addr[NeedShields] = 0; addr[NeedShields] < dims[NeedShields]; addr[NeedShields]++ {
398 for addr[Visit] = 0; addr[Visit] < dims[Visit]; addr[Visit]++ {
399 f(data, dims, table, addr)
400 }
401 }
402 }
403 }
404 }
405 }
406 }
407
408 func FillStateTable2(data planet_data, dims []int, table []State,
409 fuel_remaining, edens_remaining int, planet string, barrier chan<- bool) {
410 addr := make([]int, len(dims))
411 addr[Edens] = edens_remaining
412 addr[Fuel] = fuel_remaining
413 addr[Location] = data.p2i[planet]
414 FillStateTable2Iteration(data, dims, table, addr, FillCellByArriving)
415 FillStateTable2Iteration(data, dims, table, addr, FillCellBySelling)
416 FillStateTable2Iteration(data, dims, table, addr, FillCellByBuying)
417 FillStateTable2Iteration(data, dims, table, addr, FillCellByMisc)
418 barrier <- true
419 }
420
421 /* Filling the state table is a set of nested for loops NumDimensions deep.
422 * We split this into two procedures: 1 and 2. #1 is the outer, slowest-
423 * changing indexes. #1 fires off many calls to #2 that run in parallel.
424 * The order of the nesting of the dimensions, the order of iteration within
425 * each dimension, and where the 1 / 2 split is placed are carefully chosen
426 * to make this arrangement safe.
427 *
428 * Outermost two layers: Go from high-energy states (lots of fuel, edens) to
429 * low-energy state. These must be processed sequentially and in this order
430 * because you travel through high-energy states to get to the low-energy
431 * states.
432 *
433 * Third layer: Planet. This is a good layer to parallelize on. There's
434 * high enough cardinality that we don't have to mess with parallelizing
435 * multiple layers for good utilization (on 2011 machines). Each thread
436 * works on one planet's states and need not synchronize with peer threads.
437 */
438 func FillStateTable1(data planet_data, dims []int, table []State) {
439 barrier := make(chan bool, len(data.Planets))
440 eden_capacity := data.Commodities["Eden Warp Units"].Limit
441 work_units := (float64(*fuel) + 1) * (float64(eden_capacity) + 1)
442 work_done := 0.0
443 for fuel_remaining := *fuel; fuel_remaining >= 0; fuel_remaining-- {
444 for edens_remaining := eden_capacity; edens_remaining >= 0; edens_remaining-- {
445 for planet := range data.Planets {
446 go FillStateTable2(data, dims, table, fuel_remaining,
447 edens_remaining, planet, barrier)
448 }
449 for _ = range data.Planets {
450 <-barrier
451 }
452 work_done++
453 print(fmt.Sprintf("\r%3.0f%%", 100*work_done/work_units))
454 }
455 }
456 print("\n")
457 }
458
459 func FindBestState(data planet_data, dims []int, table []State) int {
460 addr := make([]int, NumDimensions)
461 addr[Edens] = *end_edens
462 addr[Cloaks] = dims[Cloaks] - 1
463 addr[NeedFighters] = dims[NeedFighters] - 1
464 addr[NeedShields] = dims[NeedShields] - 1
465 addr[Visit] = dims[Visit] - 1
466 // Fuel, Hold, UnusedCargo left at 0
467 max_index := -1
468 max_value := 0
469 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
470 index := EncodeIndex(dims, addr)
471 if table[index].value > max_value {
472 max_value = table[index].value
473 max_index = index
474 }
475 }
476 return max_index
477 }
478
479 func Commas(n int) (s string) {
480 r := n % 1000
481 n /= 1000
482 for n > 0 {
483 s = fmt.Sprintf(",%03d", r) + s
484 r = n % 1000
485 n /= 1000
486 }
487 s = fmt.Sprint(r) + s
488 return
489 }
490
491 func DescribePath(data planet_data, dims []int, table []State, start int) (description []string) {
492 for index := start; index > 0 && table[index].from > 0; index = table[index].from {
493 line := fmt.Sprintf("%13v", Commas(table[index].value))
494 addr := DecodeIndex(dims, index)
495 prev := DecodeIndex(dims, table[index].from)
496 if addr[Location] != prev[Location] {
497 from := data.i2p[prev[Location]]
498 to := data.i2p[addr[Location]]
499 if addr[Fuel] != prev[Fuel] {
500 line += fmt.Sprintf(" Jump from %v to %v (%v reactor units)", from, to, prev[Fuel]-addr[Fuel])
501 } else if addr[Edens] != prev[Edens] {
502 line += fmt.Sprintf(" Eden warp from %v to %v", from, to)
503 } else {
504 panic("Traveling without fuel?")
505 }
506 }
507 if addr[Hold] != prev[Hold] {
508 if addr[Hold] == 0 {
509 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
510 line += fmt.Sprintf(" Sell %v %v", quantity, data.i2c[prev[Hold]])
511 } else if prev[Hold] == 0 {
512 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
513 line += fmt.Sprintf(" Buy %v %v", quantity, data.i2c[addr[Hold]])
514 } else {
515 panic("Switched cargo?")
516 }
517
518 }
519 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
520 // TODO: Dump cloaks, convert from cargo?
521 line += " Buy a Cloak"
522 }
523 description = append(description, line)
524 }
525 return
526 }
527
528 // (Example of a use case for generics in Go)
529 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
530 e2i := make(map[string]int, len(*m)+start_at)
531 i2e := make([]string, len(*m)+start_at)
532 i := start_at
533 for e := range *m {
534 e2i[e] = i
535 i2e[i] = e
536 i++
537 }
538 return e2i, i2e
539 }
540 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
541 e2i := make(map[string]int, len(*m)+start_at)
542 i2e := make([]string, len(*m)+start_at)
543 i := start_at
544 for e := range *m {
545 e2i[e] = i
546 i2e[i] = e
547 i++
548 }
549 return e2i, i2e
550 }
551
552 func main() {
553 flag.Parse()
554 data := ReadData()
555 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
556 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
557 dims := DimensionSizes(data)
558 table := InitializeStateTable(data, dims)
559 FillStateTable1(data, dims, table)
560 best := FindBestState(data, dims, table)
561 if best == -1 {
562 print("Cannot acheive success criteria\n")
563 } else {
564 description := DescribePath(data, dims, table, best)
565 for i := len(description) - 1; i >= 0; i-- {
566 fmt.Println(description[i])
567 }
568 }
569 }