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