"""Tasks from lane-labelled save regions: a WIN x WIN window of a human factory, cleared, with a source wherever a labelled belt enters it and a sink wherever one leaves. The human's own build (with those markers) is the reference; only windows it actually produces something in are kept.""" import glob, gzip, json, pickle, random, sys import numpy as np, torch import factorion_rs from compare import frame from corpus.convert import designs, rasterise, _MASKED, _TERRAIN from factorion import Channel, Footprint, refresh_power, str2ent, str2item SIZE, WIN, OFF = 32, 20, 6 BELTISH = {str2ent(n).value for n in ("transport_belt", "underground_belt")} SPLITTER = str2ent("splitter").value MACH = {str2ent(n).value for n in ("assembling_machine_1", "stone_furnace", "steel_furnace", "electric_furnace")} SRC, SNK = str2ent("source").value, str2ent("sink").value DELTA = {1: (0, -1), 2: (1, 0), 3: (0, 1), 4: (-1, 0)} C = [Channel.ENTITIES.value, Channel.DIRECTION.value, Channel.ITEMS.value, Channel.MISC.value] def records(paths): for p in paths: with gzip.open(p, "rt") as f: try: for line in f: yield json.loads(line) except (EOFError, json.JSONDecodeError, OSError): pass # the pipeline is still appending to this file def tasks_from(rec, rng, tries=30): if not rec.get("lanes"): return bp = next(designs(rec["string"])) bp["unbuildable"] = rec.get("unbuildable") or [] r = rasterise(bp) if r is None: return mx, my = 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(",")) W, H = r.ent.shape if W < WIN + 3 or H < WIN + 3: return seen = set() for _ in range(tries): x0, y0 = rng.randrange(1, W - WIN - 1), rng.randrange(1, H - WIN - 1) if (x0 // 8, y0 // 8) in seen: continue seen.add((x0 // 8, y0 // 8)) win = (slice(x0, x0 + WIN), slice(y0, y0 + WIN)) inst = r.inst[win] inner = np.bincount(inst[inst > 0], minlength=len(r.tiles)) whole = (inst > 0) & (inner == r.tiles)[np.maximum(inst, 0)] if not np.isin(r.ent[win][whole], list(MACH)).any(): continue if ((inst > 0) & ~whole & (r.ent[win] == SPLITTER)).any(): continue # a splitter cut in half markers = {} inside = lambda x, y: x0 <= x < x0 + WIN and y0 <= y < y0 + WIN # noqa: E731 for x in range(x0, x0 + WIN): for y in range(y0, y0 + WIN): if x not in (x0, x0 + WIN - 1) and y not in (y0, y0 + WIN - 1): continue if r.ent[x, y] not in BELTISH or r.inst[x, y] <= 0 or int(r.dir[x, y]) not in DELTA: continue d = int(r.dir[x, y]); dx, dy = DELTA[d] its = lab.get((x, y), set()) if len(its) != 1 or str2item(next(iter(its))) is None: continue item = str2item(next(iter(its))).value u, v = (x - dx, y - dy), (x + dx, y + dy) if not inside(*u) and 0 <= u[0] < W and 0 <= u[1] < H and r.ent[u] in BELTISH | {SPLITTER}: markers[u] = (SRC, d, item) if not inside(*v) and 0 <= v[0] < W and 0 <= v[1] < H and r.ent[v] in BELTISH | {SPLITTER}: markers[v] = (SNK, d, item) kinds = {m[0] for m in markers.values()} if kinds != {SRC, SNK}: continue worlds = [] for context in (False, True): w = np.zeros((len(Channel), SIZE, SIZE), np.int64) w[Channel.FOOTPRINT.value] = Footprint.UNBUILDABLE.value gx0, gy0 = x0 - OFF, y0 - OFF # raster coord of grid (0, 0) for gx in range(SIZE): for gy in range(SIZE): x, y = gx + gx0, gy + gy0 if not (0 <= x < W and 0 <= y < H): continue if inside(x, y): if r.inst[x, y] in (_MASKED, _TERRAIN) or (r.inst[x, y] > 0 and not whole[x - x0, y - y0]): continue w[Channel.FOOTPRINT.value, gx, gy] = 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, gx, gy] = a[x, y] elif context and r.inst[x, y] > 0 and max(abs(2 * x - 2 * x0 - WIN + 1), abs(2 * y - 2 * y0 - WIN + 1)) > WIN + 1: for c, a in zip(C, (r.ent, r.dir, r.item, r.misc)): w[c, gx, gy] = a[x, y] for (x, y), (ent, d, item) in markers.items(): gx, gy = x - gx0, y - gy0 w[C[0], gx, gy], w[C[1], gx, gy], w[C[2], gx, gy], w[C[3], gx, gy] = ent, d, item, 0 refresh_power(torch.from_numpy(w)) worlds.append(w) # A sink still fed with every machine gone is a belt passing through: not a task. bare = worlds[0].copy() bare[:, np.isin(bare[C[0]], list(MACH))] = 0 bare[Channel.FOOTPRINT.value] = worlds[0][Channel.FOOTPRINT.value] through = {(x, y) for x, y, _, rate in factorion_rs.py_sink_deliveries(np.ascontiguousarray(bare.transpose(1, 2, 0))) if rate > 0} for w in worlds: for x, y in through: w[:4, x, y] = 0 ref = factorion_rs.simulate_throughput(np.ascontiguousarray(worlds[0].transpose(1, 2, 0)))[0] if ref <= 0 or not (worlds[0][C[0]] == SNK).any(): continue yield {"id": f"{rec['id']}@{x0},{y0}", "world": worlds[0], "context": worlds[1], "max_throughput": ref, "n_src": sum(m[0] == SRC for m in markers.values()), "n_snk": int((worlds[0][C[0]] == SNK).sum()), "n_machines": len(set(inst[whole & np.isin(r.ent[win], list(MACH))].tolist()))} if __name__ == "__main__": out, want = sys.argv[1], int(sys.argv[2]) rng = random.Random(0) tasks, n_rec = [], 0 for rec in records(sorted(glob.glob(sys.argv[3]))): n_rec += 1 for t in tasks_from(rec, rng): tasks.append(t) break # one task per region, for variety if len(tasks) >= want: break pickle.dump(tasks, open(out, "wb")) print(f"{len(tasks)} tasks from {n_rec} regions")