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