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