"""Decisive triplet plans from planner v3's per-bar output (v7, item 1). Planner v3 ranks triplet bars well, but its triplet output is an expected value (P(triplet bar) x share), so true triplet bars get small values that the generator, trained on human plans, mostly ignores. Here the ranking makes the decision: a played bar whose triplet output exceeds the threshold gets the triplet share, 1/8 share and gap histogram of an average human triplet bar of the same tier (training charts); other bars get triplet share 0. Play, density, big-note share and rolls are kept from v3. python -m chartgen.plan_decide --rows rows.pkl --plans plans_base.pkl --threshold 0.2 --out plans_trip.pkl --roll-objects (v9.1): rolls and balloons as objects. In decided plans (song_planner --predict) roll starts and sustained measures are separate yes/no decisions, so a sustained measure that follows no start can appear on its own; the rest mask then lets the generator start a new roll there (too many rolls). Here sustain is kept only in the run that follows a roll start (the start measure and the following sustained measures, until a measure is not sustained or another roll starts). Nothing else changes. python -m chartgen.plan_decide --roll-objects --plans plans_val_t0.5.pkl --out plans_val_t0.5_obj.pkl """ import argparse import pickle import numpy as np from .dataset import BAR_F, GAP0, SUSTAIN, plan_active from .gapstats import N_GAP_BINS TRIP, EIGHTH = 4, 5 # plan columns: play, density, big, roll start, triplet, 1/8, gap histogram (10), sustain def roll_objects(pl: np.ndarray) -> np.ndarray: """Keep sustain only in measures reached from a roll start through consecutive sustained measures.""" pl = pl.copy() keep = np.zeros(len(pl), bool) k = 0 while k < len(pl): if pl[k, 3] > 0.5: keep[k] = True j = k + 1 while j < len(pl) and pl[j, SUSTAIN] > 0.1 and pl[j, 3] <= 0.5: keep[j] = True j += 1 k = j else: k += 1 pl[~keep, SUSTAIN] = 0.0 return pl def main(argv=None): p = argparse.ArgumentParser() p.add_argument("--roll-objects", action="store_true", help="only make rolls objects (see module doc); no triplet change") p.add_argument("--rows") p.add_argument("--plans", required=True) p.add_argument("--threshold", type=float, default=0.2) p.add_argument("--rate", type=float, default=0.0, help="instead of --threshold: flag this share of played bars (highest triplet output first)") p.add_argument("--keep-others", action="store_true", help="leave unflagged bars at v3's value instead of 0") p.add_argument("--out", required=True) a = p.parse_args(argv) if a.roll_objects: plans = pickle.load(open(a.plans, "rb")) out = {k: (b0, roll_objects(pl).astype(np.float32)) for k, (b0, pl) in plans.items()} before = sum(int((pl[:, SUSTAIN] > 0.1).sum()) for _, pl in plans.values()) after = sum(int((pl[:, SUSTAIN] > 0.1).sum()) for _, pl in out.values()) starts = sum(int((pl[:, 3] > 0.5).sum()) for _, pl in plans.values()) orphan = sum(int(((pl[:, SUSTAIN] > 0.1) & (pl[:, 3] <= 0.5) & ~np.r_[False, (pl[:-1, 3] > 0.5) | (pl[:-1, SUSTAIN] > 0.1)]).sum()) for _, pl in plans.values()) pickle.dump(out, open(a.out, "wb")) print(f"charts {len(out)}: roll starts {starts}; sustained measures {before} -> {after}; orphan runs started without a roll {orphan}") return rows = pickle.load(open(a.rows, "rb")) proto = {} for t in range(5): P = np.concatenate([x[1] for x in rows["train"] if x[2] == t]) y = (P[:, 0] > 0.5) & (P[:, TRIP] > 0.3) proto[t] = P[y].mean(0) tier = {(x[3][0], x[3][1]): x[2] for part in ("train", "val") for x in rows[part]} plans = pickle.load(open(a.plans, "rb")) if a.rate: v = np.concatenate([pl[pl[:, 0] > 0.5, TRIP] for _, pl in plans.values()]) a.threshold = float(np.quantile(v, 1 - a.rate)) print("threshold for rate", a.rate, "=", round(a.threshold, 4)) out, n_play, n_sel = {}, 0, 0 for k, (b0, pl) in plans.items(): pl = pl.copy() play = pl[:, 0] > 0.5 sel = play & (pl[:, TRIP] > a.threshold) if not a.keep_others: pl[play & ~sel, TRIP] = 0.0 pr = proto[tier[k]] pl[sel, TRIP] = pr[TRIP] pl[sel, EIGHTH] = pr[EIGHTH] pl[sel, GAP0:GAP0 + N_GAP_BINS] = pr[GAP0:GAP0 + N_GAP_BINS] out[k] = (b0, pl.astype(np.float32)) n_play += play.sum(); n_sel += sel.sum() pickle.dump(out, open(a.out, "wb")) print(f"charts {len(out)} played bars {n_play} triplet bars {n_sel} ({n_sel / max(n_play, 1):.4f})") for t in range(5): print(t, "triplet prototype", np.round(proto[t][TRIP:], 3)) if __name__ == "__main__": main() def prototypes(rows) -> dict: """Per tier: mean plan of training measures with triplets (share > 0.3) and with 1/8-or-finer notes (> 0.25).""" out = {} for t in range(5): P = np.concatenate([x[1] for x in rows["train"] if x[2] == t]) hit = P[:, 0] > 0.5 out[t] = {"triplet": P[hit & (P[:, TRIP] > 0.3)].mean(0), "eighth": P[hit & (P[:, EIGHTH] > 0.25)].mean(0)} return out def count_then_place(o: np.ndarray, settings: np.ndarray, tier: int, protos: dict, th_sus: float, floor: float = 0.9, max_sustain: int = 4, sure_rest: float = 0.0, rest_band: tuple | None = None, rest_weight: float = 3.0, guide: np.ndarray | None = None, rng=None) -> tuple[np.ndarray, dict]: """v10a decoding: chart settings (amounts) decide HOW MANY, the planner's per-measure scores decide WHERE. o: raw planner output [n, BAR_F] (logits for play / shares / roll / sustain, density value, gap logits); settings: raw values of latent_stats.chart_settings[:6] (inside-rest share, roll starts per active measure, triplet and 1/8 measure shares of hit measures, big-note share, mean log density). guide: the decided plan of the next harder tier of the same mapset, on the same measures (v10c). Human mapsets keep rolls at the same places across tiers and an easier tier keeps the harder tier's rests (adjacent-tier rest / roll F1 about 0.8): its roll starts are placed first, and its rests stay rests unless the music is sure the measure is played (calibrated P(rest) <= lo). The amounts still come from the settings. rng (v10d): places are SAMPLED instead of taken from the top of the ranking. k places are drawn without replacement with weights from the calibrated probabilities (Gumbel-top-k on the logits), and a rest the music is sure about (P >= hi) is a rest with that probability, not always. A draw then varies like another team of mappers instead of repeating the most likely layout (distribution evaluation: draw-to-draw rest agreement far above two human teams). Returns the decided plan and a log of requested vs placed counts.""" sig = lambda v: 1 / (1 + np.exp(-v)) # noqa: E731 n = len(o) p_play, p_roll, p_sus = sig(o[:, 0]), sig(o[:, 3]), sig(o[:, SUSTAIN]) trip, eighth, big = sig(o[:, TRIP]), sig(o[:, EIGHTH]), sig(o[:, 2]) dens = np.maximum(o[:, 1], 0.05) g = np.exp(o[:, GAP0:GAP0 + N_GAP_BINS] - o[:, GAP0:GAP0 + N_GAP_BINS].max(1, keepdims=True)) gap = g / g.sum(1, keepdims=True) r_rest, r_roll, r_trip, r_eighth, r_big, r_dens = [float(x) for x in settings[:6]] act0 = p_play > 0.5 if not act0.any(): act0[np.argmax(p_play)] = True idx = np.where(act0)[0] inside = np.zeros(n, bool) inside[idx.min(): idx.max() + 1] = True log = {} # rolls / balloons as objects: k starts by score inside the chart, each followed by its sustained run start = np.zeros(n, bool); sus = np.zeros(n, bool) k_roll = int(round(r_roll * inside.sum())) g_start = (guide[:, 3] > 0.5) if guide is not None else np.zeros(n, bool) g_rest = (~plan_active(guide) & inside) if guide is not None else np.zeros(n, bool) # roll starts stay ranked even when sampling: sampled starts varied far more between draws than two human teams' # rolls do (plan level, modern validation: roll-start F1 between draws 0.12, human cross-team cap about 0.4) for j in np.argsort(-(p_roll + g_start)): if start.sum() >= k_roll: break if not inside[j] or start[max(j - 1, 0): j + 2].any() or sus[j]: continue start[j] = True m = j + 1 while m < n and m - j <= max_sustain and inside[m] and p_sus[m] >= th_sus and not start[m]: sus[m] = True m += 1 log["roll"] = (k_roll, int(start.sum())) if rest_band is not None: # The planner was trained with rest measures weighted rest_weight times, which multiplies its rest odds by that # weight; undo it. Then the music decides the measures it is sure about (calibrated P(rest) >= hi: rest; # <= lo: not a rest) and the drawn amount only decides the uncertain ones between. q = 1 - p_play q = q / (q + rest_weight * (1 - q)) lo, hi = rest_band cand = inside & ~start & ~sus hi_ok = (q >= hi) if rng is None else (q >= hi) & (rng.random(n) < q) sure = cand & (hi_ok | (g_rest & (q > lo))) mid = np.where(cand & ~sure & (q > lo) & (q < hi))[0] k_rest = int(round(r_rest * inside.sum())) rest = sure.copy() extra = max(k_rest - int(sure.sum()), 0) rest[mid[np.argsort(-_keys(q[mid], rng))][:extra]] = True log["rest"] = (k_rest, int(rest.sum())) play = (inside & ~rest & ~sus) | (~inside & act0) | (start & (p_play > 0.5)) return _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log, rng) # rests: the k inside measures (not taken by a roll) with the lowest P(play), never one with P(play) >= floor. # Measures the planner is sure about (P(play) < sure_rest) are rests whatever k is: the music decides those # (independent human mapsets agree on the big breaks); the drawn amount decides the uncertain ones. k_rest = int(round(r_rest * inside.sum())) k_rest = max(k_rest, int((inside & ~start & ~sus & (p_play < sure_rest)).sum())) elig = np.where(inside & ~start & ~sus & (p_play < floor))[0] rest = np.zeros(n, bool) rest[elig[np.argsort(p_play[elig] - g_rest[elig])][:k_rest]] = True log["rest"] = (k_rest, int(rest.sum())) play = (inside & ~rest & ~sus) | (~inside & act0) | (start & (p_play > 0.5)) return _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log, rng) def _keys(p: np.ndarray, rng=None) -> np.ndarray: """Sort keys: the probability itself (deterministic ranking), or with rng the logit plus Gumbel noise, so that the top k are a draw without replacement with weights p / (1 - p) (Gumbel-top-k).""" if rng is None: return np.asarray(p, np.float64) p = np.clip(np.asarray(p, np.float64), 1e-6, 1 - 1e-6) return np.log(p / (1 - p)) + rng.gumbel(size=p.shape) def _finish(n, play, rest, start, sus, dens, big, gap, trip, eighth, p_sus, r_trip, r_eighth, r_big, r_dens, tier, protos, log, rng=None): plan = np.zeros((n, BAR_F), np.float32) plan[:, 0] = play plan[:, 1] = dens plan[:, 2] = big plan[:, GAP0:GAP0 + N_GAP_BINS] = gap hit = np.where(play)[0] # triplet and 1/8 measures: top-k by the planner's output among hit measures, filled with the tier's prototype for col, rate, key in ((TRIP, r_trip, "triplet"), (EIGHTH, r_eighth, "eighth")): k = int(round(rate * len(hit))) sel = hit[np.argsort(-_keys((trip if col == TRIP else eighth)[hit], rng))][:k] plan[:, col] = 0.0 pr = protos[tier][key] plan[sel, col] = pr[col] plan[sel, GAP0:GAP0 + N_GAP_BINS] = pr[GAP0:GAP0 + N_GAP_BINS] if col == TRIP: plan[sel, EIGHTH] = np.maximum(plan[sel, EIGHTH], 0.0) log[key] = (k, len(sel)) # big-note share and density: shift so the chart means match the requested values if len(hit): plan[hit, 2] = np.clip(plan[hit, 2] + (r_big - plan[hit, 2].mean()), 0, 1) plan[hit, 1] = np.maximum(plan[hit, 1] + (r_dens - plan[hit, 1].mean()), 0.05) plan[:, 3] = start plan[:, SUSTAIN] = np.where(start | sus, np.maximum(p_sus, 0.5), 0.0) hit_cols = [1, 2, TRIP, EIGHTH] + list(range(GAP0, GAP0 + N_GAP_BINS)) plan[np.ix_(~play, hit_cols)] = 0.0 return plan, log