File size: 17,805 Bytes
0a3edb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Turn 32x32 views of lane-labelled save regions into working factories: a 30x30
interior from the human base, plus a 1-tile ring where flows across the edge
become sources and sinks of the item the save says they carried."""
import collections, glob, random, sys
import numpy as np, torch
import factorion_rs
import corpus.convert as cv
from build_tasks import records, C
from compare import frame as bp_frame
from factorion import Channel, Footprint, items, refresh_power, str2ent, str2item

INT, SIZE = 30, 32
E = lambda n: str2ent(n).value  # noqa: E731
BELT, UG, SPLIT = E("transport_belt"), E("underground_belt"), E("splitter")
BELTISH = {BELT, UG}
INS = {E("inserter"): 1, E("long_handed_inserter"): 2}
MACH = {E(n) for n in ("assembling_machine_1", "stone_furnace", "steel_furnace", "electric_furnace")}
SRC, SNK = E("source"), E("sink")
CHESTS = {E(n) for n in ("wooden_chest", "iron_chest", "steel_chest")}


def neighbours(x, y, reach):
    return [(x + dx, y + dy) for dx in range(-reach, reach + 1) for dy in range(-reach, reach + 1) if (dx == 0) != (dy == 0)]
DELTA = {1: (0, -1), 2: (1, 0), 3: (0, 1), 4: (-1, 0)}


def labelled(rec):
    bp = next(cv.designs(rec["string"]))
    bp["unbuildable"] = rec.get("unbuildable") or []
    r = cv.rasterise(bp)
    if r is None:
        return None, None
    mx, my = bp_frame(bp)
    lab = {}
    for x, y, _, its in rec["lanes"]:
        lab.setdefault((x - mx, y - my), set()).update(i.replace("-", "_") for i in its.split(","))
    scale = 1 if (bp.get("version", 0) >> 48) >= 2 else 2
    r.drills = []  # (front tile inside the drill, facing) of every electric mining drill
    for e in bp["entities"]:
        d = cv._DIR16.get(e.get("direction", 0) * scale)
        reach = {"electric-mining-drill": 1, "big-mining-drill": 2}.get(e["name"])
        if reach and d in DELTA:
            cx, cy = int(e["position"]["x"] // 1) - mx, int(e["position"]["y"] // 1) - my
            dx, dy = DELTA[d]
            r.drills.append(((cx + dx * reach, cy + dy * reach), d))
    return r, lab


def item_of(its):
    """One item id from a lane label, or None (unlabelled, mixed or unmodelled)."""
    ids = {getattr(str2item(i), "value", None) for i in its}
    return next(iter(ids)) if len(ids) == 1 and None not in ids else None


def window(r, lab, x0, y0, opts):
    """(world, info) for the interior [x0, x0+INT) x [y0, y0+INT) of `r`."""
    W, H = r.ent.shape
    inside = lambda x, y: x0 <= x < x0 + INT and y0 <= y < y0 + INT  # noqa: E731
    ring = lambda x, y: x0 - 1 <= x <= x0 + INT and y0 - 1 <= y <= y0 + INT and not inside(x, y)  # noqa: E731
    inraster = lambda x, y: 0 <= x < W and 0 <= y < H  # noqa: E731
    # Where flow can leave the modelled factory: the ring, and (with `masked_ports`) a
    # masked entity or one the edge cuts, inside the window.
    def portable(x, y):
        if ring(x, y):
            return True
        return bool(opts.get("masked_ports")) and inside(x, y) and (r.inst[x, y] == cv._MASKED or (r.inst[x, y] > 0 and not whole[x - x0, y - y0]))
    sl = (slice(x0, x0 + INT), slice(y0, y0 + INT))
    inst = r.inst[sl]
    inner = np.bincount(inst[inst > 0], minlength=len(r.tiles))
    whole = (inst > 0) & (inner == r.tiles)[np.maximum(inst, 0)]
    w = np.zeros((len(Channel), SIZE, SIZE), np.int64)
    w[Channel.FOOTPRINT.value] = Footprint.UNBUILDABLE.value
    g = lambda x, y: (x - x0 + 1, y - y0 + 1)  # noqa: E731  raster -> grid
    for i in range(INT):
        for j in range(INT):
            x, y = x0 + i, y0 + j
            if r.inst[x, y] in (cv._MASKED, cv._TERRAIN) or (r.inst[x, y] > 0 and not whole[i, j]):
                continue
            w[Channel.FOOTPRINT.value, i + 1, j + 1] = Footprint.BUILDABLE.value
            if r.inst[x, y] > 0:
                for c, a in zip(C, (r.ent, r.dir, r.item, r.misc)):
                    w[c, i + 1, j + 1] = a[x, y]
    ports, unresolved, why = {}, {}, collections.Counter()
    why.markers = {}  # tile -> (kind, how)

    def feeders(x, y):
        """Whether a modelled belt in the window feeds (x, y) from its aft or a side."""
        for d2, (dx, dy) in DELTA.items():
            u = (x - dx, y - dy)
            if inside(*u) and whole[u[0] - x0, u[1] - y0] and r.ent[u] in BELTISH | {SPLIT} and int(r.dir[u]) == d2:
                return True
        return False

    def along(tile, steps=40):
        """The label of `tile`, else of the nearest labelled tile along its belt, either way."""
        if lab.get(tile) or not opts.get("walk"):
            return lab.get(tile, set())
        for sign in (1, -1):
            x, y = tile
            for _ in range(steps):
                if not inraster(x, y) or r.ent[x, y] not in BELTISH | {SPLIT} or int(r.dir[x, y]) not in DELTA:
                    break
                dx, dy = DELTA[int(r.dir[x, y])]
                x, y = x + sign * dx, y + sign * dy
                if lab.get((x, y)):
                    return lab[(x, y)]
        return set()

    def port(tile, kind, d, its, how):
        item = item_of(its)
        if item is None:
            why[f"{how}: no single labelled item"] += 1
            if not opts.get("choose"):
                return
            cands = {getattr(str2item(i), "value", None) for i in its} - {None}
            unresolved.setdefault(tile, (kind, d, cands))
            why.markers.setdefault(tile, ("source" if kind == SRC else "sink", how + " (item chosen)"))
            return
        ports.setdefault(tile, (kind, d, item))
        why.markers.setdefault(tile, ("source" if kind == SRC else "sink", how + " (labelled)"))
        why[how] += 1

    for i in range(INT):
        for j in range(INT):
            x, y = x0 + i, y0 + j
            if not whole[i, j]:
                continue
            ent, d = int(r.ent[x, y]), int(r.dir[x, y])
            if d not in DELTA:
                continue
            dx, dy = DELTA[d]
            if ent in BELTISH or (opts.get("splitters") and ent == SPLIT):
                u, v = (x - dx, y - dy), (x + dx, y + dy)
                if ring(*u) and inraster(*u) and r.ent[u] in BELTISH | {SPLIT} and int(r.dir[u]) == d:
                    port(u, SRC, d, along(u) or along((x, y)), "belt in")
                elif portable(*u) and not ring(*u) and not feeders(x, y):
                    port(u, SRC, d, along((x, y)), "belt fed by a masked entity")
                if ring(*v) and inraster(*v) and r.ent[v] in BELTISH | {SPLIT}:
                    port(v, SNK, d, along((x, y)), "belt out")
                elif portable(*v) and not ring(*v):
                    port(v, SNK, d, along((x, y)), "belt into a masked entity")
            if opts.get("inserters") and ent in INS:
                k = INS[ent]
                p, q = (x - dx * k, y - dy * k), (x + dx * k, y + dy * k)
                touch = opts.get("touch")
                if portable(*p) and inraster(*p) and r.inst[p] != 0:
                    port(p, SRC, d, lab.get(p, set()) or (along(q) if touch else set()), "inserter picks across")
                if portable(*q) and inraster(*q) and r.inst[q] != 0:
                    port(q, SNK, d, lab.get(q, set()) or (along(p) if touch else set()), "inserter drops across")
    if opts.get("drills"):
        for (fx, fy), d in getattr(r, "drills", []):
            dx, dy = DELTA[d]
            out = (fx + dx, fy + dy)
            if (inside(fx, fy) or ring(fx, fy)) and inside(*out) and whole[out[0] - x0, out[1] - y0] and r.ent[out] in BELTISH:
                port((fx, fy), SRC, d, along(out), "mining drill")
    if opts.get("tunnels") or opts.get("dead_starts") or opts.get("dead_ends"):
        from factorion import Misc
        for i in range(INT):
            for j in range(INT):
                x, y = x0 + i, y0 + j
                if not whole[i, j] or int(r.dir[x, y]) not in DELTA:
                    continue
                d = int(r.dir[x, y]); dx, dy = DELTA[d]
                if opts.get("tunnels") and r.ent[x, y] == UG:
                    down = r.misc[x, y] == Misc.UNDERGROUND_DOWN.value
                    step = 1 if down else -1  # an entrance looks ahead for its exit, an exit behind
                    for k in range(1, 10):
                        px, py = x + step * dx * k, y + step * dy * k
                        if not inraster(px, py):
                            break
                        if r.ent[px, py] == UG and int(r.dir[px, py]) == d and r.misc[px, py] != r.misc[x, y]:
                            if not inside(px, py):
                                # Replace the window's tunnel end with the marker: its partner is outside.
                                port((x, y), SNK if down else SRC, d, along((x, y)), "tunnel across the edge")
                            break
                if opts.get("dead_ends") and r.ent[x, y] == BELT:
                    v = (x + dx, y + dy)
                    if inraster(*v) and r.inst[v] == 0:
                        port((x, y), SNK, d, along((x, y)), "belt that dead-ends")
                if opts.get("dead_starts") and r.ent[x, y] in (BELT, SPLIT) and not feeders(x, y) and along((x, y)):
                    u = (x - dx, y - dy)
                    if inraster(*u) and r.inst[u] == 0:
                        port((x, y), SRC, d, along((x, y)), "labelled belt fed by nothing")
    if opts.get("chest_sinks"):
        # A chest inserters fill and nothing empties is a store for later: a sink of what goes in.
        for i in range(INT):
            for j in range(INT):
                x, y = x0 + i, y0 + j
                if not whole[i, j] or r.ent[x, y] not in CHESTS:
                    continue
                fill, empty, cands = 0, 0, set()
                for (ix, iy), k in ((p, INS[int(r.ent[p])]) for p in neighbours(x, y, 2) if inside(*p) and r.ent[p] in INS and int(r.dir[p]) in DELTA):
                    dx, dy = DELTA[int(r.dir[ix, iy])]
                    if (ix + dx * k, iy + dy * k) == (x, y):
                        fill += 1
                        src = (ix - dx * k, iy - dy * k)
                        cands |= lab.get(src, set())
                    elif (ix - dx * k, iy - dy * k) == (x, y):
                        empty += 1
                if fill and not empty:
                    unresolved[(x, y)] = (SNK, 1, {getattr(str2item(n), "value", None) for n in cands} - {None})
                    why["chest becomes a sink"] += 1
    if opts.get("sideloads"):
        for x in range(x0 - 1, x0 + INT + 1):
            for y in range(y0 - 1, y0 + INT + 1):
                if not ring(x, y) or not inraster(x, y) or r.ent[x, y] not in BELTISH | {SPLIT} or int(r.dir[x, y]) not in DELTA:
                    continue
                e = int(r.dir[x, y]); dx, dy = DELTA[e]
                p = (x + dx, y + dy)
                if inside(*p) and whole[p[0] - x0, p[1] - y0] and r.ent[p] in BELTISH and int(r.dir[p]) not in (e, {1: 3, 3: 1, 2: 4, 4: 2}[e]):
                    port((x, y), SRC, e, along((x, y)), "sideload in")
    for (x, y), (kind, d, item) in ports.items():
        gx, gy = g(x, y)
        w[C[0], gx, gy], w[C[1], gx, gy], w[C[2], gx, gy], w[C[3], gx, gy] = kind, d, item, 0
    refresh_power(torch.from_numpy(w))
    if unresolved:
        ins, outs = io_items(w)
        view_items = {getattr(str2item(n), "value", None) for (x, y), its in lab.items() if ring(x, y) or inside(x, y) for n in its} - {None}
        counts = collections.Counter(getattr(str2item(n), "value", None) for its in lab.values() for n in its)
        counts.pop(None, None)
        region_item = counts.most_common(1)[0][0] if counts else str2item("iron_plate").value
        for (x, y), (kind, d, cands) in sorted(unresolved.items(), key=lambda kv: kv[1][0] != SRC):
            if (x, y) in ports:
                continue
            gx, gy = g(x, y)
            options = cands or (ins if kind == SRC else outs | ins)
            if kind == SNK and not cands and opts.get("random_isolated"):
                options = options | (set(w[C[2]][w[C[0]] == SRC].tolist()) - {0})
            if not options and opts.get("random_isolated") and kind == SRC and isolated(w, gx, gy, d):
                options = {opts["rng"].choice(BELT_ITEMS)}
                why["random item on an isolated belt"] += 1
            if not options and opts.get("view_labels"):
                options = view_items
            if not options and opts.get("fallback_item"):
                options = {region_item}
            best, best_v = None, -1.0
            for item in sorted(options):
                w[C[0], gx, gy], w[C[1], gx, gy], w[C[2], gx, gy] = kind, d, item
                v = crafted_delivery(w) + 1e-3 * thput(w)
                if v > best_v:
                    best, best_v = item, v
            if best is None:
                w[C[0], gx, gy] = w[C[1], gx, gy] = w[C[2], gx, gy] = 0
            else:
                w[C[2], gx, gy] = best
                why["item chosen"] += 1
    if opts.get("poles"):
        powered = factorion_rs.py_place_poles(np.ascontiguousarray(w.transpose(1, 2, 0)))
        if powered is not None:
            w = np.ascontiguousarray(powered.transpose(2, 0, 1))
            refresh_power(torch.from_numpy(w))
        else:
            why["no room for poles"] += 1
    return w, why


RECIPES = factorion_rs.py_recipes()
FURNACE_IN = {getattr(str2item(n), "value", None) for n in ("iron_ore", "copper_ore", "stone", "iron_plate", "coal")} - {None}
FURNACES = {E(n) for n in ("stone_furnace", "steel_furnace", "electric_furnace")}
NAME = {getattr(str2item(n), "value", None): n for n in RECIPES}
NAME_ANY = {k: v.name for k, v in items.items()}


def io_items(w):
    """(ingredients, products) of the window's machines, as item ids."""
    ins, outs = set(), set()
    ent, itm = w[C[0]], w[C[2]]
    for v in set(itm[ent == E("assembling_machine_1")].tolist()) - {0}:
        r = RECIPES.get(NAME.get(v, ""))
        if r:
            ins |= {str2item(i).value for i in r["consumes"] if str2item(i)}
            outs |= {str2item(i).value for i in r["produces"] if str2item(i)}
    if np.isin(ent, list(FURNACES)).any():
        ins |= FURNACE_IN
        outs |= {getattr(str2item(n), "value", None) for n in ("iron_plate", "copper_plate", "steel_plate", "stone_brick")} - {None}
    return ins, outs


def crafted_delivery(w):
    """items/s of machine products the sinks receive."""
    _, outs = io_items(w)
    names = {NAME_ANY.get(v) for v in outs}
    return sum(rate for _, _, item, rate in factorion_rs.py_sink_deliveries(np.ascontiguousarray(w.transpose(1, 2, 0))) if item in names)


BELT_ITEMS = sorted(i for i, it in items.items() if it.name not in ("empty", "source", "sink", "bulk_inserter") and i != E("source") and i != E("sink"))


def isolated(w, gx, gy, d):
    """Whether the belt a source at (gx, gy) facing `d` feeds is untouched: no inserter
    picks from or drops onto it and no other belt merges into it, so its item can't matter."""
    ent, dirs = w[C[0]], w[C[1]]
    chain, (x, y) = [], (gx + DELTA[d][0], gy + DELTA[d][1])
    while 0 <= x < SIZE and 0 <= y < SIZE and ent[x, y] in BELTISH and (x, y) not in chain:
        chain.append((x, y))
        dx, dy = DELTA.get(int(dirs[x, y]), (0, 0))
        x, y = x + dx, y + dy
    if not chain:
        return False
    on = set(chain)
    for (ix, iy) in np.argwhere(np.isin(ent, list(INS))):
        k = INS[int(ent[ix, iy])]
        dx, dy = DELTA.get(int(dirs[ix, iy]), (0, 0))
        if (ix - dx * k, iy - dy * k) in on or (ix + dx * k, iy + dy * k) in on:
            return False
    for i, (x, y) in enumerate(chain):
        for d2, (dx, dy) in DELTA.items():
            u = (x - dx, y - dy)
            fed = 0 <= u[0] < SIZE and 0 <= u[1] < SIZE and ent[u] in BELTISH | {SPLIT, SRC} and int(dirs[u]) == d2
            if fed and u != (gx, gy) and (i == 0 or u != chain[i - 1]):
                return False
    return True


def thput(w):
    return factorion_rs.simulate_throughput(np.ascontiguousarray(w.transpose(1, 2, 0)))[0]


def works(w):
    """(delivers anything, some sink receives an item a machine in it crafted)."""
    return thput(w) > 0, crafted_delivery(w) > 0


def cut_machines(r, x0, y0):
    """Machines (and masked machines' tiles) the interior's edge cuts through."""
    inst = r.inst[x0:x0 + INT, y0:y0 + INT]
    inner = np.bincount(inst[inst > 0], minlength=len(r.tiles))
    cut = (inner > 0) & (inner < r.tiles)
    ids = np.nonzero(cut)[0]
    return int(np.isin(r.ent[x0:x0 + INT, y0:y0 + INT][np.isin(inst, ids)], list(MACH)).sum())


def sample(paths, n, seed=0, nudge=False):
    """`n` (r, lab, x0, y0) views, each around a random flow tile of a random labelled region."""
    rng, out = random.Random(seed), []
    flow = [E(n) for n in ("transport_belt", "underground_belt", "splitter", "inserter", "long_handed_inserter", "assembling_machine_1")]
    for rec in records(paths):
        if not rec.get("lanes") or rng.random() > 0.5:
            continue
        r, lab = labelled(rec)
        if r is None:
            continue
        W, H = r.ent.shape
        if W < INT + 2 or H < INT + 2:
            continue
        fx, fy = np.nonzero((r.inst > 0) & np.isin(r.ent, flow))
        if not len(fx):
            continue
        k = rng.randrange(len(fx))
        x0 = min(max(1, fx[k] - rng.randrange(INT)), W - INT - 1)
        y0 = min(max(1, fy[k] - rng.randrange(INT)), H - INT - 1)
        if nudge:
            x0, y0 = min(((x, y) for x in range(max(1, x0 - 3), min(W - INT - 1, x0 + 3) + 1) for y in range(max(1, y0 - 3), min(H - INT - 1, y0 + 3) + 1)),
                         key=lambda p: (cut_machines(r, *p), abs(p[0] - x0) + abs(p[1] - y0)))
        out.append((r, lab, x0, y0))
        if len(out) >= n:
            break
    return out