-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
390 lines (362 loc) · 11.2 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
)
type Exporter interface {
Export(scenario Scenario, chromosome Chromosome) any
}
// ScenarioExporter exports the scenario and the chromosome, useful for debugging on profit.phinau.de
type ScenarioExporter struct{}
// SolutionExporter exports the chromosome as specified by the problem statement
type SolutionExporter struct{}
type SerializedScenario struct {
Height int `json:"height"`
Width int `json:"width"`
Objects []SerializedScenarioObject `json:"objects"`
Products []SerializedScenarioObject `json:"products"`
Turns int `json:"turns"`
Time int `json:"time"`
}
type SerializedScenarioObject struct {
ObjectType string `json:"type"`
Subtype int `json:"subtype"`
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Resources []int `json:"resources"`
Points int `json:"points"`
}
type SolutionExport []SolutionExportObject
type SolutionExportObject struct {
ObjectType string `json:"type"`
X int `json:"x"`
Y int `json:"y"`
Subtype int `json:"subtype"`
}
func (c Chromosome) Export(scenario Scenario, exporter Exporter, filePath string) error {
b, err := json.MarshalIndent(exporter.Export(scenario, c), "", " ")
if err != nil {
return err
}
if filePath == "-" {
_, err = os.Stdout.Write(b)
return err
}
return os.WriteFile(filePath, b, 0644)
}
func (_ SolutionExporter) Export(s Scenario, c Chromosome) any {
export := SolutionExport{}
for _, factory := range c.factories {
export = append(export, SolutionExportObject{
ObjectType: "factory",
Subtype: factory.product,
X: factory.position.x,
Y: factory.position.y,
})
}
for _, mine := range c.mines {
export = append(export, SolutionExportObject{
ObjectType: "mine",
Subtype: int(mine.direction),
X: mine.position.x,
Y: mine.position.y,
})
}
for _, path := range c.paths {
for _, conveyor := range path.conveyors {
export = append(export, SolutionExportObject{
ObjectType: "conveyor",
Subtype: conveyor.Subtype(),
X: conveyor.position.x,
Y: conveyor.position.y,
})
}
}
for _, combiner := range c.combiners {
export = append(export, SolutionExportObject{
ObjectType: "combiner",
X: combiner.position.x,
Y: combiner.position.y,
Subtype: int(combiner.direction),
})
}
return export
}
func (_ ScenarioExporter) Export(s Scenario, c Chromosome) any {
export := SerializedScenario{
Height: s.height,
Width: s.width,
Objects: []SerializedScenarioObject{},
Products: []SerializedScenarioObject{},
Turns: s.turns,
Time: 100,
}
for _, deposit := range s.deposits {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "deposit",
Subtype: deposit.subtype,
X: deposit.position.x,
Y: deposit.position.y,
Width: deposit.width,
Height: deposit.height,
})
}
for _, obstacle := range s.obstacles {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "obstacle",
X: obstacle.position.x,
Y: obstacle.position.y,
Width: obstacle.width,
Height: obstacle.height,
})
}
for _, factory := range c.factories {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "factory",
Subtype: factory.product,
X: factory.position.x,
Y: factory.position.y,
})
}
for _, mine := range c.mines {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "mine",
Subtype: int(mine.direction),
X: mine.position.x,
Y: mine.position.y,
})
}
for _, path := range c.paths {
for _, conveyor := range path.conveyors {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "conveyor",
Subtype: conveyor.Subtype(),
X: conveyor.position.x,
Y: conveyor.position.y,
})
}
}
for _, combiner := range c.combiners {
export.Objects = append(export.Objects, SerializedScenarioObject{
ObjectType: "combiner",
X: combiner.position.x,
Y: combiner.position.y,
Subtype: int(combiner.direction),
})
}
for _, product := range s.products {
export.Products = append(export.Products, SerializedScenarioObject{
ObjectType: "product",
Subtype: product.subtype,
Points: product.points,
Resources: product.resources,
})
}
return export
}
func ImportScenario(path string) (Scenario, Chromosome, error) {
var jsonFile *os.File
var err error
if path == "-" {
jsonFile = os.Stdin
} else {
jsonFile, err = os.Open(path)
if err != nil {
return Scenario{}, Chromosome{}, err
}
defer jsonFile.Close()
}
byteValue, err := io.ReadAll(jsonFile)
if err != nil {
return Scenario{}, Chromosome{}, err
}
var s SerializedScenario
err = json.Unmarshal(byteValue, &s)
if err != nil {
return Scenario{}, Chromosome{}, err
}
scenario := Scenario{
width: s.Width,
height: s.Height,
turns: s.Turns,
time: s.Time,
}
if scenario.time <= 0 {
return Scenario{}, Chromosome{}, errors.New("time imported from json has to be greater than 0")
}
chromosome := Chromosome{}
for _, object := range s.Objects {
switch object.ObjectType {
case "deposit":
if object.Subtype >= NumResourceTypes || object.Subtype < 0 {
return Scenario{}, Chromosome{}, fmt.Errorf("invalid subtype %d for deposit", object.Subtype)
}
scenario.deposits = append(scenario.deposits, Deposit{
position: Position{object.X, object.Y},
width: object.Width,
height: object.Height,
subtype: object.Subtype,
})
case "obstacle":
scenario.obstacles = append(scenario.obstacles, Obstacle{
position: Position{object.X, object.Y},
height: object.Height,
width: object.Width,
})
case "factory":
if object.Subtype >= NumProducts || object.Subtype < 0 {
return Scenario{}, Chromosome{}, fmt.Errorf("invalid factory subtype %d", object.Subtype)
}
chromosome.factories = append(chromosome.factories, Factory{
position: Position{object.X, object.Y},
product: object.Subtype,
})
case "mine":
if object.Subtype >= NumDirections || object.Subtype < 0 {
return Scenario{}, Chromosome{}, fmt.Errorf("invalid mine subtype: %d", object.Subtype)
}
direction := DirectionFromSubtype(object.Subtype)
chromosome.mines = append(chromosome.mines, Mine{
position: Position{object.X, object.Y},
direction: direction,
})
case "conveyor":
if object.Subtype >= NumConveyorSubtypes || object.Subtype < 0 {
_ = fmt.Errorf("importing a conveyor failed, invalid subtype")
return Scenario{}, Chromosome{}, fmt.Errorf("invalid conveyor subtype: %d", object.Subtype)
}
direction := DirectionFromSubtype(object.Subtype)
length := ConveyorLengthFromSubtype(object.Subtype)
// TODO: Think about building proper paths
chromosome.paths = append(chromosome.paths, Path{
conveyors: []Conveyor{{
position: Position{object.X, object.Y},
direction: direction,
length: length,
}},
})
case "combiner":
if object.Subtype >= NumDirections || object.Subtype < 0 {
_ = fmt.Errorf("importing a combiner failed, invalid subtype")
return Scenario{}, Chromosome{}, fmt.Errorf("invalid combiner subtype: %d", object.Subtype)
}
direction := DirectionFromSubtype(object.Subtype)
chromosome.combiners = append(chromosome.combiners, Combiner{
position: Position{object.X, object.Y},
direction: direction,
})
default:
return Scenario{}, Chromosome{}, fmt.Errorf("unknown ObjectType: %s", object.ObjectType)
}
}
for _, product := range s.Products {
if product.ObjectType != "product" {
return Scenario{}, Chromosome{}, fmt.Errorf("expected ObjectType to be 'product', not %s", product.ObjectType)
}
scenario.products = append(scenario.products, Product{
subtype: product.Subtype,
points: product.Points,
resources: product.Resources,
})
}
chromosome.determineDistancesFromMinesToFactories(scenario)
return scenario, chromosome, nil
}
// we perform a BFS from all factories to the mines
func (c *Chromosome) determineDistancesFromMinesToFactories(scenario Scenario) {
combinerMatrix := make([][]*Combiner, scenario.width)
for i := range combinerMatrix {
combinerMatrix[i] = make([]*Combiner, scenario.height)
}
mineMatrix := make([][]*Mine, scenario.width)
for i := range mineMatrix {
mineMatrix[i] = make([]*Mine, scenario.height)
}
conveyorMatrix := make([][]*Conveyor, scenario.width)
for i := range conveyorMatrix {
conveyorMatrix[i] = make([]*Conveyor, scenario.height)
}
for i := range c.mines {
mine := &c.mines[i]
mine.RectanglesEach(func(rectangle Rectangle) {
rectangle.ForEach(func(position Position) {
mineMatrix[position.x][position.y] = mine
})
})
}
for i := range c.combiners {
combiner := &c.combiners[i]
combiner.RectanglesEach(func(rectangle Rectangle) {
rectangle.ForEach(func(position Position) {
combinerMatrix[position.x][position.y] = combiner
})
})
}
for i := range c.paths {
for j := range c.paths[i].conveyors {
conveyor := &c.paths[i].conveyors[j]
conveyor.Rectangle().ForEach(func(position Position) {
conveyorMatrix[position.x][position.y] = conveyor
})
}
}
for i := range c.factories {
distance := 0
factory := &c.factories[i]
positions := factory.NextToIngressPositions()
visitedPosition := make([][]bool, scenario.width)
for j := range visitedPosition {
visitedPosition[j] = make([]bool, scenario.height)
}
for {
distance++
nextPositions := make([]Position, 0)
for _, p := range positions {
if p.x < 0 || p.x >= scenario.width || p.y < 0 || p.y >= scenario.height {
continue
}
if visitedPosition[p.x][p.y] {
continue
}
visitedPosition[p.x][p.y] = true
if conveyorMatrix[p.x][p.y] != nil && conveyorMatrix[p.x][p.y].Egress() == p {
conveyorMatrix[p.x][p.y].distance = distance
nextPositions = append(nextPositions, conveyorMatrix[p.x][p.y].NextToIngressPositions()...)
}
if combinerMatrix[p.x][p.y] != nil && combinerMatrix[p.x][p.y].Egress() == p {
combinerMatrix[p.x][p.y].distance = distance
nextPositions = append(nextPositions, combinerMatrix[p.x][p.y].NextToIngressPositions()...)
}
if mineMatrix[p.x][p.y] != nil && mineMatrix[p.x][p.y].Egress() == p {
mineMatrix[p.x][p.y].distance = distance
mineMatrix[p.x][p.y].connectedFactory = factory
nextPositions = append(nextPositions, mineMatrix[p.x][p.y].NextToIngressPositions()...)
}
}
positions = nextPositions
if len(positions) == 0 {
break
}
}
}
}
func exportChromosomes(scenario Scenario, i int, chromosomes []Chromosome, dir string) error {
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
for j := 0; j < NumLoggedChromosomesPerIteration; j++ {
if j < len(chromosomes) {
err2 := chromosomes[j].Export(scenario, ScenarioExporter{}, fmt.Sprintf("%s/iteration_%d_ch_%d.json", dir, i, j))
if err2 != nil {
return err2
}
}
}
return nil
}