"""Beat-pattern tokenizer for v11 (reports/v11 重新設計:計畫.md, section 2; P0.5 in reports/v11 階段 0 預先登記:參考線.md). Input: the hit notes of one chart as a grid, i.e. sorted unique 1/48-beat indices (chartgen.rhythm_eval2.grid_of). The note at index g lies in beat g // 48 at position k = g % 48. A beat's pattern is the set of its note positions among the 24 candidate positions: k/48 with k a multiple of 3 or of 4, which are all the 1/3, 1/4, 1/6, 1/8, 1/12 and 1/16 positions (POSITIONS). Positions only: colours, big notes, rolls and balloons are separate streams. A pattern is stored as a 24-bit mask, bit i = POSITIONS[i]. Tokens: EMPTY (0) = no note on the 24 positions, OTHER (1) = a pattern outside the vocabulary, then the vocabulary patterns (2, 3, ...), most common first. The vocabulary holds the patterns that occur in at least `min_count` beats of the charts it is built on. Notes on any other position (k neither a multiple of 3 nor of 4: 1/5, 1/7, 1/24, 1/48 and similar) are not part of a pattern. encode() returns them in a separate list (`offgrid`), together with the masks of the OTHER beats (`other`), so that decode(tokens, ..., offgrid, other) gives back the input exactly, and decode(tokens) alone gives back every covered beat exactly. A beat is covered when its token is not OTHER and it has no off-grid note (Encoded.covered()). """ from __future__ import annotations from collections import Counter from dataclasses import dataclass, field from fractions import Fraction import numpy as np GRID = 48 POSITIONS = tuple(k for k in range(GRID) if k % 3 == 0 or k % 4 == 0) N_POS = len(POSITIONS) assert N_POS == 24 POS_BIT = np.full(GRID, -1, np.int64) POS_BIT[list(POSITIONS)] = np.arange(N_POS) _POS_ARR = np.asarray(POSITIONS, np.int64) EMPTY = 0 OTHER = 1 N_SPECIAL = 2 # ---------------------------------------------------------------- masks def positions_to_mask(positions) -> int: """Set of positions k (each in POSITIONS) -> 24-bit mask.""" m = 0 for k in positions: b = int(POS_BIT[int(k)]) if b < 0: raise ValueError(f"position {k} is not one of the 24 candidate positions") m |= 1 << b return m def mask_to_positions(mask: int) -> tuple: """24-bit mask -> sorted tuple of positions k (1/48 of a beat).""" return tuple(POSITIONS[i] for i in range(N_POS) if (int(mask) >> i) & 1) def mask_str(mask: int) -> str: """Readable pattern: the positions as fractions of a beat, e.g. '0 1/4 1/2 3/4'; '-' for the empty pattern.""" pos = mask_to_positions(mask) return " ".join(str(Fraction(k, GRID)) for k in pos) if pos else "-" def beat_masks(grid) -> tuple: """Split a grid into per-beat patterns. Returns (beats, masks, offgrid): beats = sorted indices of the beats with at least one note on the 24 positions, masks = their 24-bit masks (int64), offgrid = the notes (1/48 indices) on other positions.""" g = np.asarray(grid, np.int64) if g.size == 0: e = np.zeros(0, np.int64) return e, e.copy(), e.copy() beat = np.floor_divide(g, GRID) bit = POS_BIT[np.mod(g, GRID)] on = bit >= 0 offgrid = np.sort(g[~on]) b_on, bit_on = beat[on], bit[on] if b_on.size == 0: e = np.zeros(0, np.int64) return e, e.copy(), offgrid o = np.argsort(b_on, kind="stable") b_on, val = b_on[o], np.left_shift(np.int64(1), bit_on[o]) beats, start = np.unique(b_on, return_index=True) masks = np.bitwise_or.reduceat(val, start) return beats, masks.astype(np.int64), offgrid def masks_to_grid(beats, masks) -> np.ndarray: """Inverse of the on-grid part of beat_masks: per-beat masks -> sorted 1/48 indices.""" beats, masks = np.asarray(beats, np.int64), np.asarray(masks, np.int64) if beats.size == 0: return np.zeros(0, np.int64) bits = (masks[:, None] >> np.arange(N_POS)[None, :]) & 1 bi, pi = np.nonzero(bits) return np.sort(beats[bi] * GRID + _POS_ARR[pi]) # ---------------------------------------------------------------- vocabulary @dataclass class Vocab: """Token ids: EMPTY = 0, OTHER = 1, masks[i] has id i + 2 (masks ordered by count, then by mask value).""" masks: np.ndarray # [V] int64, 24-bit pattern masks counts: np.ndarray # [V] int64, number of beats with the pattern in the building charts min_count: int = 3 _sorted: np.ndarray = field(init=False, repr=False) _order: np.ndarray = field(init=False, repr=False) def __post_init__(self): self.masks = np.asarray(self.masks, np.int64) self.counts = np.asarray(self.counts, np.int64) if len(np.unique(self.masks)) != len(self.masks) or (self.masks <= 0).any(): raise ValueError("vocabulary masks must be distinct and non-empty") self._order = np.argsort(self.masks, kind="stable") self._sorted = self.masks[self._order] def __len__(self) -> int: """Number of tokens, EMPTY and OTHER included.""" return len(self.masks) + N_SPECIAL @property def n_patterns(self) -> int: return len(self.masks) def ids(self, masks) -> np.ndarray: """Masks -> token ids (0 -> EMPTY, unknown non-empty -> OTHER).""" m = np.asarray(masks, np.int64) out = np.full(m.shape, OTHER, np.int64) if self._sorted.size: j = np.clip(np.searchsorted(self._sorted, m), 0, len(self._sorted) - 1) hit = self._sorted[j] == m out[hit] = self._order[j[hit]] + N_SPECIAL out[m == 0] = EMPTY return out def mask(self, tokens) -> np.ndarray: """Token ids -> masks (EMPTY -> 0; OTHER -> -1, since its pattern is unknown).""" t = np.asarray(tokens, np.int64) if ((t < 0) | (t >= len(self))).any(): raise ValueError("token id out of range") table = np.r_[np.int64(0), np.int64(-1), self.masks] return table[t] def to_dict(self) -> dict: return {"min_count": int(self.min_count), "masks": self.masks.tolist(), "counts": self.counts.tolist()} @classmethod def from_dict(cls, d: dict) -> "Vocab": return cls(np.asarray(d["masks"], np.int64), np.asarray(d["counts"], np.int64), int(d["min_count"])) def count_patterns(grids) -> Counter: """Number of beats per non-empty pattern (the on-grid part of every beat that has a note on the 24 positions).""" out = Counter() for g in grids: _, masks, _ = beat_masks(g) if masks.size: u, c = np.unique(masks, return_counts=True) out.update(dict(zip(u.tolist(), c.tolist()))) return out def vocab_from_counts(counts: Counter, min_count: int = 3) -> Vocab: keep = sorted(((c, m) for m, c in counts.items() if c >= min_count and m != 0), key=lambda x: (-x[0], x[1])) return Vocab(np.array([m for _, m in keep], np.int64), np.array([c for c, _ in keep], np.int64), min_count) def build_vocab(grids, min_count: int = 3) -> Vocab: """Vocabulary of the patterns that occur in at least `min_count` beats of `grids` (iterable of 1/48 grids).""" return vocab_from_counts(count_patterns(grids), min_count) # ---------------------------------------------------------------- encode / decode @dataclass class Encoded: beat0: int # beat index of tokens[0] tokens: np.ndarray # [n_beats] int64, one token per beat from beat0 to the last beat with a note offgrid: np.ndarray # 1/48 indices of the notes off the 24 positions other: dict # beat index -> mask, for the beats whose token is OTHER def covered(self) -> np.ndarray: """[n_beats] bool: token is not OTHER and the beat has no off-grid note.""" ok = self.tokens != OTHER if self.offgrid.size: b = np.floor_divide(self.offgrid, GRID) - self.beat0 ok[b[(b >= 0) & (b < len(ok))]] = False return ok def has_note(self) -> np.ndarray: """[n_beats] bool: the beat has at least one note (on or off the 24 positions).""" out = self.tokens != EMPTY if self.offgrid.size: b = np.floor_divide(self.offgrid, GRID) - self.beat0 out[b[(b >= 0) & (b < len(out))]] = True return out def encode(grid, vocab: Vocab, beat0: int | None = None, n_beats: int | None = None) -> Encoded: """One token per beat. The span is beat0 .. beat0 + n_beats - 1 (default: first to last beat with a note); notes outside a given span are not allowed.""" g = np.asarray(grid, np.int64) if g.size and (np.diff(g) <= 0).any(): raise ValueError("grid must be sorted and unique") beats, masks, offgrid = beat_masks(g) all_beats = np.floor_divide(g, GRID) if beat0 is None: beat0 = int(all_beats.min()) if g.size else 0 if n_beats is None: n_beats = int(all_beats.max()) - beat0 + 1 if g.size else 0 if g.size and (all_beats.min() < beat0 or all_beats.max() >= beat0 + n_beats): raise ValueError("notes outside the requested beat span") tokens = np.full(n_beats, EMPTY, np.int64) ids = vocab.ids(masks) tokens[beats - beat0] = ids other = {int(b): int(m) for b, m, t in zip(beats.tolist(), masks.tolist(), ids.tolist()) if t == OTHER} return Encoded(int(beat0), tokens, offgrid, other) def decode(tokens, vocab: Vocab, beat0: int = 0, offgrid=None, other: dict | None = None) -> np.ndarray: """Tokens -> sorted 1/48 grid. OTHER beats are left empty unless their masks are given in `other`; off-grid notes are added when given.""" t = np.asarray(tokens, np.int64) m = vocab.mask(t) if other: for b, mk in other.items(): i = int(b) - beat0 if not (0 <= i < len(t)) or t[i] != OTHER: raise ValueError(f"beat {b} of `other` is not an OTHER beat") m[i] = mk keep = m > 0 g = masks_to_grid(np.nonzero(keep)[0] + beat0, m[keep]) if offgrid is not None and len(offgrid): g = np.union1d(g, np.asarray(offgrid, np.int64)) return g def decode_full(enc: Encoded, vocab: Vocab) -> np.ndarray: """Exact inverse of encode().""" return decode(enc.tokens, vocab, enc.beat0, enc.offgrid, enc.other)