diff --git a/.gitignore b/.gitignore index 59a962b..c856cdb 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,4 @@ python/out/ *.zip bench/compare.png paper/out/ +data/psplib/ diff --git a/paper/README.md b/paper/README.md index bca660c..f156a4f 100644 --- a/paper/README.md +++ b/paper/README.md @@ -23,7 +23,7 @@ Outputs go to `paper/out/`, which git ignores: `ptr.pt` holds the weights, the c - 80 Poisson jobs at 0.8 per tick; - 2 resources; - a 20-tick horizon; -- a pool of 10 waiting slots; +- a waiting pool with one slot per job (80), so it is never full: no job is rejected and the model always sees every waiting job; - the DeepRM slowdown reward. Its sum over an episode is minus the total slowdown. @@ -76,6 +76,25 @@ Use `--episodes` that is a multiple of the worker count. Bigger `--batch` / `--updates` / `--d-model` use the GPU more; more `--episodes` / `--sims` use the CPU cores more. +## PSPLIB workload + +Job profiles can come from PSPLIB RCPSP instances (Kolisch & Sprecher 1997) +instead of DeepRM. Download a set (e.g. j30.sm) from the PSPLIB site and +unpack it, then: + + python paper/train.py --psplib data/psplib/j30 ... + python paper/evaluate.py paper/out/ptr.pt ... # uses the env stored in the checkpoint + +Every activity with duration > 0 becomes a job template: its duration and +constant demand on the 4 renewable resources, divided by the instance's +availability and scaled to capacity 100 (so instances can be mixed). Each +job draws a template with the episode seed; precedence relations are +ignored. Arrivals stay `poisson:n=80,rate=0.8`. PSPLIB activities are larger +than DeepRM jobs, so lower the rate if the queue grows without bound. + +From the CLI: `sim --machines psplib:path=data/psplib/j30,n=2 --res 4 ...` +(`order=sequential` takes activities in file order). + ## Evaluation and seeds Every policy runs on the same seeds: `10¹²`, `10¹² + 1`, … These never overlap with training seeds. Two things are checked, not assumed: diff --git a/paper/evaluate.py b/paper/evaluate.py index 3ad708f..5da7ca4 100644 --- a/paper/evaluate.py +++ b/paper/evaluate.py @@ -20,7 +20,7 @@ Metrics per episode (from the trace): average slowdown (wait + dur) / dur, average wait, makespan, total reward, jobs rejected (full pool, impossible) -and admitted jobs left unplaced. +admitted jobs left unplaced, and episodes cut off at --max-ticks. Writes paper/out/eval.json and prints a mean ± std table. """ @@ -65,7 +65,8 @@ def read_trace(path: Path) -> tuple[dict, dict]: "wait": float(np.mean(wait)) if wait else float("nan"), "makespan": done["makespan"] if done else None, "unplaced": sum(1 for v in work.values() if v[1] is not None) - len(places), # admitted, never placed - "rejected": sum(1 for v in work.values() if v[1] is None)} + "rejected": sum(1 for v in work.values() if v[1] is None), + "truncated": int(bool(done and done.get("truncated")))} return m, work @@ -119,6 +120,8 @@ def main(): ap.add_argument("--seed-start", type=int, default=EVAL_SEED_START) ap.add_argument("--sims", type=int, default=32, help="MCTS simulations per move (0 = skip ptr+mcts)") ap.add_argument("--policies", default=",".join(BUILTIN)) + ap.add_argument("--max-ticks", type=int, default=2000, + help="end (truncate) an episode after this many ticks; counted in the 'truncated' column") ap.add_argument("--device", default="cpu") ap.add_argument("--out", default="paper/out/eval.json") args = ap.parse_args() @@ -140,7 +143,10 @@ def main(): overlap = [s for s in seeds if s in used] if overlap: raise SystemExit(f"evaluation seeds {overlap[0]}.. were used in training ({used.start}..{used.stop - 1})") - env_kw = ck["env"] if ck else ENV_KW + env_kw = dict(ck["env"] if ck else ENV_KW) + # a policy that keeps choosing "wait" would otherwise never end the episode; + # every job has arrived long before this, so the cap does not change the workload + env_kw["max_ticks"] = env_kw.get("max_ticks") or args.max_ticks env = SchedEnv(**env_kw) policies = {name: (lambda e, o, s, p, n=name: e.policy_action(n)) for name in args.policies.split(",") if name} @@ -176,7 +182,7 @@ def main(): print(f"\n{len(seeds)} seeds from {args.seed_start}; same workload for every policy: " f"{'yes' if not checks['workload_mismatch'] else 'NO ' + str(checks['workload_mismatch'])}; " f"engine deterministic: {'yes' if not checks['nondeterministic'] else 'NO ' + str(checks['nondeterministic'])}\n") - cols = ["slowdown", "wait", "makespan", "reward", "rejected", "unplaced", "sec"] + cols = ["slowdown", "wait", "makespan", "reward", "rejected", "unplaced", "truncated", "sec"] print(f"{'policy':<14}" + "".join(f"{c:>18}" for c in cols)) summary = {} for name, rows in results.items(): diff --git a/paper/ptrmcts.py b/paper/ptrmcts.py index e343103..85d5f1c 100644 --- a/paper/ptrmcts.py +++ b/paper/ptrmcts.py @@ -49,12 +49,16 @@ from sched_env import _lib # noqa: E402 # Environment used in the paper experiments. Small enough for MCTS on a CPU. +# The waiting pool has one slot per job in the episode, so it can never be +# full: no job is rejected and the model always sees every waiting job (the +# pointer network handles any number of jobs; empty slots are masked). +N_JOBS = 80 ENV_KW = dict( machines="deeprm:n=1", - jobs="poisson:n=80,rate=0.8", + jobs=f"poisson:n={N_JOBS},rate=0.8", n_res=2, n_ticks=20, - max_jobs=10, + max_jobs=N_JOBS, reward="slowdown", ) @@ -87,6 +91,19 @@ def atomic_write(path, write) -> None: raise +def env_config(psplib: str | None = None) -> dict: + """ENV_KW, or with job profiles from PSPLIB instances (a .sm file or a + directory of them): 4 renewable resources, demand / availability x 100.""" + if not psplib: + return dict(ENV_KW) + path = os.path.abspath(psplib) + if not os.path.exists(path): + raise FileNotFoundError(path) + if "," in path or "=" in path: + raise ValueError(f"PSPLIB path must not contain ',' or '=': {path}") + return {**ENV_KW, "machines": f"psplib:path={path},n=1", "n_res": 4} + + def make_env(**overrides) -> SchedEnv: return SchedEnv(**{**ENV_KW, **overrides}) diff --git a/paper/train.py b/paper/train.py index 5fe1b11..2d6b010 100644 --- a/paper/train.py +++ b/paper/train.py @@ -31,7 +31,8 @@ import torch import torch.nn.functional as F -from ptrmcts import ENV_KW, MCTS, PointerNet, atomic_write, collate, featurize, fingerprint, make_env, train_seed_range +from ptrmcts import MCTS, PointerNet, atomic_write, collate, env_config, featurize, fingerprint, train_seed_range +from sched_env import SchedEnv def discounted(rewards: list[float], gamma: float, scale: float) -> list[float]: @@ -86,10 +87,10 @@ def train_step(net, opt, batch, device, value_coef): _W: dict = {} -def _worker_init(d_model: int, threads: int): +def _worker_init(env_kw: dict, d_model: int, threads: int): torch.set_num_threads(threads) - env = make_env() - _W["env"] = env + env = SchedEnv(**env_kw) + _W["env"], _W["env_kw"] = env, env_kw _W["net"] = PointerNet.for_env(env, d=d_model).eval() @@ -101,7 +102,7 @@ def self_play_episode(job): _W["net"].load_state_dict(state) env, net = _W["env"], _W["net"] rng = np.random.default_rng([a["seed"], seed]) - mcts = MCTS(net, ENV_KW, "cpu", sims=a["sims"], gamma=a["gamma"], reward_scale=a["reward_scale"], rng=rng) + mcts = MCTS(net, _W["env_kw"], "cpu", sims=a["sims"], gamma=a["gamma"], reward_scale=a["reward_scale"], rng=rng) def choose(obs, mask, prefix, expect, step): counts = mcts.search(seed, prefix, expect, noise=True) @@ -143,6 +144,8 @@ def main(): ap.add_argument("--gamma", type=float, default=0.98) ap.add_argument("--reward-scale", type=float, default=10.0) ap.add_argument("--d-model", type=int, default=128) + ap.add_argument("--psplib", default=None, + help="take job profiles from PSPLIB instances (.sm file or directory) instead of DeepRM") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--workers", type=int, default=1, help="parallel self-play processes (0 = all cores but one); results do not depend on it") @@ -159,7 +162,8 @@ def main(): rng = np.random.default_rng(args.seed) device = torch.device(args.device) - env = make_env() + env_kw = env_config(args.psplib) + env = SchedEnv(**env_kw) net = PointerNet.for_env(env, d=args.d_model).to(device) opt = torch.optim.Adam(net.parameters(), lr=args.lr) buffer = collections.deque(maxlen=args.buffer) @@ -194,9 +198,9 @@ def teacher(obs, mask, prefix, expect, step): # 2-3. self-play + training ------------------------------------------------ cpus = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2) workers = args.workers or max(1, cpus - 1) # affinity: only the CPUs SLURM/taskset gave us - pool = (mp.get_context("spawn").Pool(workers, _worker_init, (args.d_model, 1)) if workers > 1 else None) + pool = (mp.get_context("spawn").Pool(workers, _worker_init, (env_kw, args.d_model, 1)) if workers > 1 else None) if pool is None: - _worker_init(args.d_model, torch.get_num_threads()) + _worker_init(env_kw, args.d_model, torch.get_num_threads()) print(f"self-play: {workers} worker(s), training on {device}") for it in range(args.iters): t0 = time.time() @@ -214,7 +218,7 @@ def teacher(obs, mask, prefix, expect, step): "policy_loss": pl, "value_loss": vl, "buffer": len(buffer), "sec": round(time.time() - t0, 1)} log.append(rec) print(json.dumps(rec)) - ck = {"model": net.state_dict(), "d_model": args.d_model, "env": ENV_KW, "args": vars(args), "log": log} + ck = {"model": net.state_dict(), "d_model": args.d_model, "env": env_kw, "args": vars(args), "log": log} atomic_write(out, lambda p: torch.save(ck, p)) if pool: pool.close() diff --git a/src/adapters.zig b/src/adapters.zig index af8d816..43856ff 100644 --- a/src/adapters.zig +++ b/src/adapters.zig @@ -20,6 +20,8 @@ pub const arrivals = struct { pub const generators = struct { pub const RandomProfiles = @import("adapters/generators/random_profiles.zig").RandomProfiles; pub const DeepRM = @import("adapters/generators/deeprm.zig").DeepRM; + pub const psplib = @import("adapters/generators/psplib.zig"); + pub const Psplib = psplib.Psplib; }; pub const rewards = struct { diff --git a/src/adapters/generators/psplib.zig b/src/adapters/generators/psplib.zig new file mode 100644 index 0000000..e1c20dd --- /dev/null +++ b/src/adapters/generators/psplib.zig @@ -0,0 +1,272 @@ +//! PSPLIB workload (Kolisch & Sprecher, "PSPLIB – a project scheduling +//! problem library", EJOR 1997): job profiles taken from the activities of +//! RCPSP instances (`.sm` single-mode files; `.mm` files use mode 1). +//! +//! * every non-dummy activity (duration > 0) becomes a job template with +//! its duration and constant per-resource demand; +//! * demands are normalized by the instance's resource availability and +//! rescaled to the machine capacity `cap`, so templates from instances +//! with different availabilities mix on the same machines; +//! * resource r of the simulator is PSPLIB renewable resource r +//! (n_res must be <= the number of renewable resources, usually 4); +//! * `order = .random` draws a template uniformly per job (seeded); +//! `.sequential` takes them in file order, cycling. +//! +//! Precedence relations are ignored: jobs are independent, as everywhere in +//! the simulator. Parsing is separate from file I/O (see `parse`), so this +//! adapter does no I/O; the registry reads the files. +const std = @import("std"); +const grid = @import("../../grid.zig"); +const model = @import("../../model.zig"); +const Error = @import("../../ports.zig").usage_generator.Error; +const Elem = grid.Elem; +const Usage = grid.Usage; + +pub const max_res = 8; + +pub const Activity = struct { + dur: u16, + /// demand / availability per renewable resource, in [0, 1] + frac: [max_res]f32 = @splat(0), +}; + +pub const Order = enum { random, sequential }; + +pub const Psplib = struct { + acts: []const Activity, + /// renewable resources available in every template (min over instances) + n_renewable: usize, + n_machines: usize = 1, + cap: Elem = 100, + order: Order = .random, + next: usize = 0, + prng: std.Random.DefaultPrng = .init(0), + + pub fn reset(self: *Psplib, seed: u64) void { + self.prng = .init(seed +% 3); + self.next = 0; + } + + pub fn machineCount(self: *Psplib) usize { + return self.n_machines; + } + + pub fn machine(self: *Psplib, index: usize, cap: []Elem) Error!void { + _ = index; + if (cap.len > self.n_renewable) return error.InvalidInput; + @memset(cap, self.cap); + } + + pub fn job(self: *Psplib, meta: model.JobMeta, out: Usage) Error!u16 { + _ = meta; + if (self.acts.len == 0 or out.layout.n_res > self.n_renewable) return error.InvalidInput; + const i = switch (self.order) { + .random => self.prng.random().uintLessThan(usize, self.acts.len), + .sequential => blk: { + const k = self.next; + self.next = (k + 1) % self.acts.len; + break :blk k; + }, + }; + const a = self.acts[i]; + const dur: u16 = @intCast(@min(a.dur, out.layout.n_ticks)); + const c: f32 = @floatFromInt(self.cap); + for (0..out.layout.n_res) |res| { + const d: Elem = @intFromFloat(@round(a.frac[res] * c)); + @memset(out.resourceMut(res)[0..dur], d); + } + return dur; + } +}; + +/// Parse one PSPLIB instance (text of a `.sm` / `.mm` file) and append its +/// activities to `out`. Returns the number of renewable resources. +pub fn parse(gpa: std.mem.Allocator, text: []const u8, out: *std.ArrayList(Activity)) Error!usize { + var n_ren: ?usize = null; + var n_non: usize = 0; + var raw: std.ArrayList(struct { dur: u16, dem: [max_res]u32 }) = .empty; + defer raw.deinit(gpa); + var avail: ?[max_res]u32 = null; + + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line_cr| { + const line = std.mem.trimEnd(u8, line_cr, "\r"); + const t = std.mem.trim(u8, line, " \t"); + if (startsWith(t, "- renewable")) { + n_ren = try lastNumberBefore(t, 'R'); + } else if (startsWith(t, "- nonrenewable")) { + n_non = try lastNumberBefore(t, 'N'); + } else if (startsWith(t, "REQUESTS/DURATIONS")) { + const r = n_ren orelse return error.InvalidInput; + if (r == 0 or r > max_res) return error.InvalidInput; + _ = lines.next(); // column header + _ = lines.next(); // dashes + while (lines.next()) |row_cr| { + const row = std.mem.trim(u8, row_cr, " \t\r"); + if (row.len == 0) continue; + if (row[0] == '*') break; + var nums: [3 + 2 * max_res + 8]u32 = undefined; + const n = try ints(row, &nums); + // new activity: jobnr mode dur R.. N..; extra mode lines lack jobnr -> skipped (mode 1 only) + if (n != 3 + r + n_non) continue; + var e: @TypeOf(raw.items[0]) = .{ .dur = std.math.cast(u16, nums[2]) orelse return error.InvalidInput, .dem = @splat(0) }; + @memcpy(e.dem[0..r], nums[3 .. 3 + r]); + try raw.append(gpa, e); + } + } else if (startsWith(t, "RESOURCEAVAILABILITIES")) { + const r = n_ren orelse return error.InvalidInput; + _ = lines.next(); // "R 1 R 2 ..." + const row = lines.next() orelse return error.InvalidInput; + var nums: [2 * max_res + 8]u32 = undefined; + const n = try ints(row, &nums); + if (n < r) return error.InvalidInput; + var a: [max_res]u32 = @splat(0); + @memcpy(a[0..r], nums[0..r]); + avail = a; + } + } + const r = n_ren orelse return error.InvalidInput; + const av = avail orelse return error.InvalidInput; + if (raw.items.len == 0) return error.InvalidInput; + for (raw.items) |e| { + if (e.dur == 0) continue; // dummy source / sink + var act: Activity = .{ .dur = e.dur }; + for (0..r) |k| { + if (e.dem[k] > av[k]) return error.InvalidInput; // can never fit + act.frac[k] = if (av[k] == 0) 0 else @as(f32, @floatFromInt(e.dem[k])) / @as(f32, @floatFromInt(av[k])); + } + try out.append(gpa, act); + } + return r; +} + +fn startsWith(s: []const u8, p: []const u8) bool { + return std.mem.startsWith(u8, s, p); +} + +/// "- renewable : 4 R" -> 4 +fn lastNumberBefore(s: []const u8, unit: u8) Error!usize { + const colon = std.mem.indexOfScalar(u8, s, ':') orelse return error.InvalidInput; + var it = std.mem.tokenizeAny(u8, s[colon + 1 ..], " \t"); + const num = it.next() orelse return error.InvalidInput; + const u = it.next() orelse return error.InvalidInput; + if (u.len == 0 or u[0] != unit) return error.InvalidInput; + return std.fmt.parseInt(usize, num, 10) catch error.InvalidInput; +} + +/// Whitespace-separated unsigned ints of `row` into `buf`; returns the count. +fn ints(row: []const u8, buf: []u32) Error!usize { + var it = std.mem.tokenizeAny(u8, row, " \t\r"); + var n: usize = 0; + while (it.next()) |tok| { + if (n == buf.len) return error.InvalidInput; + buf[n] = std.fmt.parseInt(u32, tok, 10) catch return error.InvalidInput; + n += 1; + } + return n; +} + +// ----------------------------------------------------------------------------- tests + +/// Small hand-made instance in the PSPLIB .sm layout (2 real activities + dummies). +pub const example_sm = + \\************************************************************************ + \\file with basedata : example.bas + \\initial value random generator: 1 + \\************************************************************************ + \\projects : 1 + \\jobs (incl. supersource/sink ): 4 + \\horizon : 20 + \\RESOURCES + \\ - renewable : 4 R + \\ - nonrenewable : 2 N + \\ - doubly constrained : 0 D + \\************************************************************************ + \\PRECEDENCE RELATIONS: + \\jobnr. #modes #successors successors + \\ 1 1 2 2 3 + \\ 2 1 1 4 + \\ 3 1 1 4 + \\ 4 1 0 + \\************************************************************************ + \\REQUESTS/DURATIONS: + \\jobnr. mode duration R 1 R 2 R 3 R 4 N 1 N 2 + \\------------------------------------------------------------------------ + \\ 1 1 0 0 0 0 0 0 0 + \\ 2 1 3 5 0 10 2 0 0 + \\ 3 1 7 0 20 5 8 0 0 + \\ 4 1 0 0 0 0 0 0 0 + \\************************************************************************ + \\RESOURCEAVAILABILITIES: + \\ R 1 R 2 R 3 R 4 N 1 N 2 + \\ 10 20 20 16 0 0 + \\************************************************************************ + \\ +; + +test "psplib: parse an .sm instance" { + const a = std.testing.allocator; + var acts: std.ArrayList(Activity) = .empty; + defer acts.deinit(a); + try std.testing.expectEqual(@as(usize, 4), try parse(a, example_sm, &acts)); + try std.testing.expectEqual(@as(usize, 2), acts.items.len); // dummies dropped + try std.testing.expectEqual(@as(u16, 3), acts.items[0].dur); + try std.testing.expectEqualSlices(f32, &.{ 0.5, 0, 0.5, 0.125 }, acts.items[0].frac[0..4]); + try std.testing.expectEqual(@as(u16, 7), acts.items[1].dur); + try std.testing.expectEqualSlices(f32, &.{ 0, 1, 0.25, 0.5 }, acts.items[1].frac[0..4]); +} + +test "psplib: malformed input is rejected" { + const a = std.testing.allocator; + var acts: std.ArrayList(Activity) = .empty; + defer acts.deinit(a); + try std.testing.expectError(error.InvalidInput, parse(a, "not a psplib file", &acts)); + // demand above availability + const bad = try std.mem.replaceOwned(u8, a, example_sm, " 10 20 20 16", " 1 20 20 16"); + defer a.free(bad); + try std.testing.expectError(error.InvalidInput, parse(a, bad, &acts)); +} + +test "psplib: jobs follow the templates, scaled to cap; seeded and sequential" { + const a = std.testing.allocator; + var acts: std.ArrayList(Activity) = .empty; + defer acts.deinit(a); + const n_ren = try parse(a, example_sm, &acts); + + const layout = try grid.Layout.init(3, 8, grid.simd.padding); + const buf = try a.alignedAlloc(Elem, grid.simd.ALIGN, layout.block); + defer a.free(buf); + + var g = Psplib{ .acts = acts.items, .n_renewable = n_ren, .cap = 40, .order = .sequential }; + g.reset(1); + var cap: [3]Elem = undefined; + try g.machine(0, &cap); + try std.testing.expectEqualSlices(Elem, &.{ 40, 40, 40 }, &cap); + var too_many: [5]Elem = undefined; + try std.testing.expectError(error.InvalidInput, g.machine(0, &too_many)); + + for ([_]u16{ 3, 7, 3 }) |want| { + @memset(buf, 0); + const u = Usage.fromSlice(buf, layout); + const dur = try g.job(.{ .id = 0, .arrival = 0 }, u); + try std.testing.expectEqual(want, dur); + const exp: [3]Elem = if (want == 3) .{ 20, 0, 20 } else .{ 0, 40, 10 }; + for (0..3) |r| { + try std.testing.expectEqual(exp[r], u.resource(r)[0]); + try std.testing.expectEqual(exp[r], u.resource(r)[dur - 1]); + try std.testing.expectEqual(@as(Elem, 0), u.resource(r)[dur]); + } + } + + // random order: same seed -> same sequence + g.order = .random; + var seqs: [2][16]u16 = undefined; + for (&seqs) |*s| { + g.reset(7); + for (s) |*d| { + @memset(buf, 0); + d.* = try g.job(.{ .id = 0, .arrival = 0 }, Usage.fromSlice(buf, layout)); + } + } + try std.testing.expectEqualSlices(u16, &seqs[0], &seqs[1]); +} diff --git a/src/app/capi.zig b/src/app/capi.zig index 49cab92..960ed3c 100644 --- a/src/app/capi.zig +++ b/src/app/capi.zig @@ -122,7 +122,8 @@ fn create(c: *const SimConfig) !*Sim { }; if (c.max_jobs == 0) return cli.fail("sim_create: max_jobs must be > 0", .{}); - sim.gen = try registry.generator(a, try cli.Spec.parse(a, "machines", std.mem.span(c.machines))); + sim.threaded = std.Io.Threaded.init_single_threaded; + sim.gen = try registry.generator(a, sim.threaded.io(), try cli.Spec.parse(a, "machines", std.mem.span(c.machines))); errdefer sim.gen.deinit(); sim.arr = try registry.arrivals(a, try cli.Spec.parse(a, "jobs", std.mem.span(c.jobs))); errdefer sim.arr.deinit(); @@ -132,7 +133,6 @@ fn create(c: *const SimConfig) !*Sim { sim.started = false; sim.trace = .{}; sim.tracing = false; - sim.threaded = std.Io.Threaded.init_single_threaded; try sim.eng.addObserver(.init(sim)); return sim; } diff --git a/src/app/main.zig b/src/app/main.zig index 6d8dfc8..926f224 100644 --- a/src/app/main.zig +++ b/src/app/main.zig @@ -87,7 +87,7 @@ fn run(init: std.process.Init) !void { if (!registry.hasPolicy(policy_spec.name)) return cli.fail("--policy: unknown policy '{s}' (see --list)", .{policy_spec.name}); // ---------------- build adapters ---------------- - const gen = try registry.generator(arena, try cli.Spec.parse(arena, "--machines", machines_spec)); + const gen = try registry.generator(arena, io, try cli.Spec.parse(arena, "--machines", machines_spec)); defer gen.deinit(); const arr = try registry.arrivals(arena, try cli.Spec.parse(arena, "--jobs", jobs_spec)); defer arr.deinit(); diff --git a/src/app/registry.zig b/src/app/registry.zig index d50e839..f1df637 100644 --- a/src/app/registry.zig +++ b/src/app/registry.zig @@ -13,7 +13,7 @@ const Spec = cli.Spec; // ---------------------------------------------------------------- generators -pub fn generator(arena: std.mem.Allocator, s: Spec) !ports.UsageGenerator { +pub fn generator(arena: std.mem.Allocator, io: std.Io, s: Spec) !ports.UsageGenerator { if (std.mem.eql(u8, s.name, "random")) { try s.only(&.{ "n", "caps", "dur", "demand", "varying" }); const g = try arena.create(A.generators.RandomProfiles); @@ -44,9 +44,90 @@ pub fn generator(arena: std.mem.Allocator, s: Spec) !ports.UsageGenerator { }; return .init(g); } + if (std.mem.eql(u8, s.name, "psplib")) { + try s.only(&.{ "path", "n", "cap", "order" }); + const path = s.raw("path") orelse return cli.fail("--machines psplib: path=<.sm file or directory> is required", .{}); + const g = try arena.create(A.generators.Psplib); + const order_s = s.raw("order") orelse "random"; + const order = std.meta.stringToEnum(A.generators.psplib.Order, order_s) orelse + return cli.fail("--machines psplib: order must be random or sequential, got '{s}'", .{order_s}); + var acts: std.ArrayList(A.generators.psplib.Activity) = .empty; + const n_ren = try loadPsplib(arena, io, path, &acts); + g.* = .{ + .acts = acts.items, + .n_renewable = n_ren, + .n_machines = try s.int(usize, "n", 1), + .cap = try s.int(Elem, "cap", 100), + .order = order, + }; + return .init(g); + } return cli.fail("--machines: unknown generator '{s}' (see --list)", .{s.name}); } +/// Read a PSPLIB instance file, or every .sm/.mm file of a directory (in +/// name order, so the template list does not depend on the file system). +/// Returns the smallest renewable-resource count over the instances. +fn loadPsplib(arena: std.mem.Allocator, io: std.Io, path: []const u8, acts: *std.ArrayList(A.generators.psplib.Activity)) !usize { + const cwd = std.Io.Dir.cwd(); + const limit: std.Io.Limit = .limited(64 << 20); + var names: std.ArrayList([]const u8) = .empty; + var dir = cwd.openDir(io, path, .{ .iterate = true }) catch |e| switch (e) { + error.NotDir => null, + else => return cli.fail("--machines psplib: cannot open '{s}': {t}", .{ path, e }), + }; + if (dir) |*d| { + defer d.close(io); + var it = d.iterate(); + while (it.next(io) catch |e| return cli.fail("--machines psplib: cannot list '{s}': {t}", .{ path, e })) |ent| { + if (ent.kind != .file) continue; + if (!std.mem.endsWith(u8, ent.name, ".sm") and !std.mem.endsWith(u8, ent.name, ".mm")) continue; + try names.append(arena, try std.fs.path.join(arena, &.{ path, ent.name })); + } + std.mem.sort([]const u8, names.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + return std.mem.lessThan(u8, a, b); + } + }.lt); + if (names.items.len == 0) return cli.fail("--machines psplib: no .sm/.mm files in '{s}'", .{path}); + } else try names.append(arena, path); + + var n_ren: usize = std.math.maxInt(usize); + for (names.items) |name| { + const text = cwd.readFileAlloc(io, name, arena, limit) catch |e| + return cli.fail("--machines psplib: cannot read '{s}': {t}", .{ name, e }); + const r = A.generators.psplib.parse(arena, text, acts) catch + return cli.fail("--machines psplib: '{s}' is not a valid PSPLIB instance", .{name}); + n_ren = @min(n_ren, r); + } + return n_ren; +} + +test "psplib spec loads a file and a directory" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "set"); + try tmp.dir.writeFile(io, .{ .sub_path = "set/a.sm", .data = A.generators.psplib.example_sm }); + try tmp.dir.writeFile(io, .{ .sub_path = "set/b.sm", .data = A.generators.psplib.example_sm }); + try tmp.dir.writeFile(io, .{ .sub_path = "set/notes.txt", .data = "ignored" }); + const base = try tmp.dir.realPathFileAlloc(io, "set", arena); + + var acts: std.ArrayList(A.generators.psplib.Activity) = .empty; + try std.testing.expectEqual(@as(usize, 4), try loadPsplib(arena, io, base, &acts)); + try std.testing.expectEqual(@as(usize, 4), acts.items.len); // 2 files x 2 activities + acts.clearRetainingCapacity(); + _ = try loadPsplib(arena, io, try std.fs.path.join(arena, &.{ base, "a.sm" }), &acts); + try std.testing.expectEqual(@as(usize, 2), acts.items.len); + + const spec = try std.fmt.allocPrint(arena, "psplib:path={s},n=2,cap=40,order=sequential", .{base}); + const g = try generator(arena, io, try cli.Spec.parse(arena, "--machines", spec)); + try std.testing.expectEqual(@as(usize, 2), g.machineCount()); +} + // ---------------------------------------------------------------- arrivals pub fn arrivals(arena: std.mem.Allocator, s: Spec) !ports.ArrivalSource { @@ -246,6 +327,9 @@ pub const list_text = \\ machines cycle through caps; uniform random duration and demand \\ deeprm n=1 cap=100 short=3 long=10-15 short_prob=0.8 \\ DeepRM workload: 80% short jobs, one dominant resource per job + \\ psplib path=<.sm file or dir> n=1 cap=100 order=random + \\ PSPLIB (RCPSP) activities as jobs: duration + demand / availability x cap; + \\ order=random (seeded) or sequential; n_res <= renewable resources (4) \\ \\Job arrivals (--jobs): \\ poisson n=500 rate=1.0 exponential gaps, mean 1/rate ticks