File size: 12,509 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""v11 stage 2: data for the position map R (reports/v11 階段 2 預先登記:位置圖 R.md, sections 1-2).

One *group* is one song record (beatmapset + audio) and one timing (charts of a mapset share their red lines in all but
10 of 5,268 multi-chart mapsets; charts with other red lines form their own group). A group holds

  beat table   every global beat b of the timing that has a candidate position inside the audio: its start time (ms),
               beat length (ms), section, beat-in-measure, and a 24-bit mask of valid positions (time inside the audio
               and before the next red line minus 1 ms; positions of a beat cut by a red line after it are invalid)
  per tier     a list of charts, each as two 24-bit masks per beat: target (hit notes, types 0-3, on the 24 positions;
               chart['beat'] * 48 rounded, which equals the time-derived grid exactly) and loss (valid, not strictly
               inside a roll / balloon body, and the beat has no hit note off the 24 positions)

Roles (by song key = song_key or str(beatmapset_id)): test songs are never loaded; val; train songs are split into the
tuning set (sha1('tune:' + key) % 10 == 0) and halves A / B (sha1('fold:' + key) % 2). Era band of a group = the latest
chart year in it: <= 2013, 2014-2016, 2017-2021, 2022+.

    python -m chartgen.v11.rmap_data --selftest
"""

from __future__ import annotations

import argparse
import hashlib
import math
from dataclasses import dataclass, field

import numpy as np

from chartgen.dataset import measure_at, measure_span, roll_end_beats
from chartgen.train import song_split
from chartgen.v11.patterns import GRID, N_POS, POS_BIT, POSITIONS

POS = np.asarray(POSITIONS, np.int64)          # [24] positions in 1/48 beat
N_TIERS = 5
ERA_EDGES = (2014, 2017, 2022)
N_ERA = len(ERA_EDGES) + 1
MAX_BIB = 15                                   # beat-in-measure index is clipped here
ALL24 = np.uint32((1 << N_POS) - 1)
# position classes (dataset.subdiv_class order): 0 beat, 1 1/2, 2 1/3, 3 1/4, 4 1/6, 5 1/8, 6 1/12, 7 1/16
POS_CLASS = np.array([[1, 2, 3, 4, 6, 8, 12, 16].index(GRID // math.gcd(int(k), GRID)) if k else 0 for k in POS])
FAMILIES = {"beat": (0,), "1/2": (1,), "1/4": (3,), "triplet": (2, 4, 6), "eighth": (5, 7)}
FAMILY_OF_CLASS = {c: f for f, cs in FAMILIES.items() for c in cs}


def song_key(song: dict) -> str:
    return song.get("song_key") or str(song["beatmapset_id"])


def _h(salt: str, key: str) -> int:
    return int(hashlib.sha1(f"{salt}:{key}".encode()).hexdigest(), 16)


def role(key: str) -> str | None:
    """'val', 'tune', 'A', 'B', or None for test songs."""
    sp = song_split(key)
    if sp == "test":
        return None
    if sp == "val":
        return "val"
    if _h("tune", key) % 10 == 0:
        return "tune"
    return "A" if _h("fold", key) % 2 == 0 else "B"


def era_band(year) -> int:
    return int(np.searchsorted(ERA_EDGES, int(year or 0), side="right"))


def bits_to_bool(m: np.ndarray) -> np.ndarray:
    """[n] uint32 masks -> [n, 24] bool."""
    return ((np.asarray(m, np.uint32)[:, None] >> np.arange(N_POS, dtype=np.uint32)[None]) & 1).astype(bool)


def bool_to_bits(b: np.ndarray) -> np.ndarray:
    return (np.asarray(b, np.uint32) << np.arange(N_POS, dtype=np.uint32)[None]).sum(1).astype(np.uint32)


# ------------------------------------------------------------------------------------------------ beat table

@dataclass
class BeatTable:
    beat: np.ndarray        # [n] int64 global beat numbers (sorted, unique)
    t0: np.ndarray          # [n] float64 ms of the beat start
    bl: np.ndarray          # [n] float32 beat length (ms)
    sec: np.ndarray         # [n] int16 section index
    bib: np.ndarray         # [n] uint8 beat index inside its measure (clipped at MAX_BIB)
    valid: np.ndarray       # [n] uint32 24-bit mask of valid positions

    def __len__(self):
        return len(self.beat)

    def pos_ms(self) -> np.ndarray:
        """[n, 24] ms of every candidate position."""
        return self.t0[:, None] + self.bl[:, None].astype(np.float64) * POS[None] / GRID


def beat_table(sections, n_frames: int) -> BeatTable:
    s = np.asarray(sections, np.float64)
    end = n_frames * 10.0
    B, T0, BL, SEC, NXT = [], [], [], [], []
    for j in range(len(s)):
        t0, bl, sb = s[j, 0], s[j, 1], s[j, 3]
        if not bl > 0:
            continue
        nxt_t = s[j + 1, 0] if j + 1 < len(s) else math.inf
        lo = math.floor(sb + (0.0 - t0) / bl) if j == 0 else int(round(sb))
        lo = max(lo, int(round(sb))) if t0 < 0 and j == 0 else lo
        hi = int(round(s[j + 1, 3])) if j + 1 < len(s) else math.ceil(sb + (end - t0) / bl)
        if hi <= lo:
            continue
        b = np.arange(lo, hi, dtype=np.int64)
        tb = t0 + (b - sb) * bl
        keep = (tb < min(end, nxt_t)) & (tb + bl > 0)
        B.append(b[keep]); T0.append(tb[keep]); BL.append(np.full(keep.sum(), bl)); SEC.append(np.full(keep.sum(), j))
        NXT.append(np.full(keep.sum(), nxt_t))
    if not B:
        z = np.zeros(0)
        return BeatTable(z.astype(np.int64), z, z.astype(np.float32), z.astype(np.int16), z.astype(np.uint8),
                         z.astype(np.uint32))
    b, t0, bl, sec, nxt = (np.concatenate(x) for x in (B, T0, BL, SEC, NXT))
    o = np.argsort(b, kind="stable")
    b, t0, bl, sec, nxt = b[o], t0[o], bl[o], sec[o], nxt[o]
    keep = np.r_[True, np.diff(b) > 0]          # duplicate beat numbers cannot occur by construction; be safe
    b, t0, bl, sec, nxt = b[keep], t0[keep], bl[keep], sec[keep], nxt[keep]
    pt = t0[:, None] + bl[:, None] * POS[None] / GRID
    ok = (pt >= 0) & (pt < end) & (pt < nxt[:, None] - 1.0)
    m = measure_at(s, b.astype(np.float64))
    start, _ = measure_span(s, m)
    bib = np.clip(np.round(b - start), 0, MAX_BIB).astype(np.uint8)
    return BeatTable(b, t0, bl.astype(np.float32), sec.astype(np.int16), bib, bool_to_bits(ok))


# ------------------------------------------------------------------------------------------------ chart targets

def chart_masks(chart: dict, table: BeatTable) -> tuple[np.ndarray, np.ndarray]:
    """(target, loss) 24-bit masks per beat of the table for one chart on the table's timing."""
    n = len(table)
    tgt = np.zeros(n, np.uint32)
    loss = table.valid.copy()
    if n == 0:
        return tgt, loss
    beat = np.asarray(chart["beat"], np.float64)
    typ = np.asarray(chart["type"])
    hit = typ <= 3
    g = np.round(beat[hit] * GRID).astype(np.int64)
    bb, kk = np.floor_divide(g, GRID), np.mod(g, GRID)
    row = np.searchsorted(table.beat, bb)
    ok = (row < n) & (table.beat[np.minimum(row, n - 1)] == bb)
    bit = POS_BIT[kk]
    on = ok & (bit >= 0)
    np.bitwise_or.at(tgt, row[on], (np.uint32(1) << bit[on].astype(np.uint32)).astype(np.uint32))
    off = ok & (bit < 0)
    loss[row[off]] = 0
    roll = typ >= 4
    if roll.any():
        sb = beat[roll]
        eb = roll_end_beats(np.asarray(chart["sections"], np.float64), sb,
                            np.asarray(chart["length_beats"], np.float64)[roll])
        for a, e in zip(sb, eb):
            if e - a <= 1e-6:
                continue
            r0 = np.searchsorted(table.beat, math.floor(a))
            r1 = np.searchsorted(table.beat, math.ceil(e), side="right")
            if r1 <= r0:
                continue
            pv = table.beat[r0:r1, None] + POS[None] / GRID
            inside = (pv > a + 1e-6) & (pv < e - 1e-6)
            loss[r0:r1] &= ~bool_to_bits(inside)
    tgt &= table.valid
    return tgt, loss


# ------------------------------------------------------------------------------------------------ groups

@dataclass
class Group:
    set_id: int
    key: str
    role: str
    era: int
    table: BeatTable
    sections: np.ndarray
    charts: dict = field(default_factory=dict)      # tier -> list of (beatmap_id, year, target, loss)
    song_index: int = -1                              # index of the song record in the loaded list

    @property
    def uid(self) -> str:
        """Stable id of the group: set id and a hash of its red lines."""
        h = hashlib.sha1(np.round(np.asarray(self.sections, np.float64)[:, :4], 3).tobytes()).hexdigest()[:8]
        return f"s{self.set_id}_{h}"

    def n_examples(self) -> int:
        return max((len(v) for v in self.charts.values()), default=0)

    def example(self, i: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """(target [n, 5] uint32, loss [n, 5] uint32, tier present [5] bool): chart i % k of every tier."""
        n = len(self.table)
        tgt = np.zeros((n, N_TIERS), np.uint32)
        los = np.zeros((n, N_TIERS), np.uint32)
        has = np.zeros(N_TIERS, bool)
        for t, lst in self.charts.items():
            _, _, a, b = lst[i % len(lst)]
            tgt[:, t], los[:, t], has[t] = a, b, True
        return tgt, los, has


def song_groups(song: dict, song_index: int = -1, tiers=range(N_TIERS)) -> list[Group]:
    key = song_key(song)
    r = role(key)
    if r is None:
        return []
    n_frames = len(song["mel"])
    by_timing: dict[bytes, list] = {}
    for c in song["charts"]:
        if int(c["tier"]) not in tiers or len(c["time"]) == 0:
            continue
        s = np.asarray(c["sections"], np.float64)
        by_timing.setdefault(np.round(s[:, :4], 3).tobytes(), []).append(c)
    out = []
    for cs in by_timing.values():
        s = np.asarray(cs[0]["sections"], np.float64)
        table = beat_table(s, n_frames)
        if len(table) < 8:
            continue
        g = Group(int(song["beatmapset_id"]), key, r, era_band(max(int(c.get("year") or 0) for c in cs)), table, s,
                  song_index=song_index)
        for c in sorted(cs, key=lambda c: int(c["beatmap_id"])):
            tgt, los = chart_masks(c, table)
            g.charts.setdefault(int(c["tier"]), []).append((int(c["beatmap_id"]), int(c.get("year") or 0), tgt, los))
        out.append(g)
    return out


# ------------------------------------------------------------------------------------------------ self-test

def selftest(shard: str | None = None):
    from chartgen.dataset import load_songs
    from chartgen.rhythm_eval2 import grid_of
    path = shard or "data/pilot/features/taiko-00000.pkl"
    songs = load_songs([path], mmap=True)
    n_g = n_ch = 0
    n_hit = n_cov = n_valid_miss = 0
    roles = {}
    for i, s in enumerate(songs):
        for g in song_groups(s, i):
            roles[g.role] = roles.get(g.role, 0) + 1
            n_g += 1
            for t, lst in g.charts.items():
                for bid, _, tgt, los in lst:
                    n_ch += 1
                    c = next(c for c in s["charts"] if int(c["beatmap_id"]) == bid)
                    grid = grid_of(c, c["sections"])
                    ok = np.isin(np.mod(grid, GRID), POS)
                    n_hit += len(grid)
                    rec = []
                    tb = bits_to_bool(tgt)
                    rows, cols = np.nonzero(tb)
                    rec = np.sort(g.table.beat[rows] * GRID + POS[cols])
                    # every on-grid hit inside a valid position is a target, and nothing else
                    want = np.sort(grid[ok])
                    inside = np.isin(want, rec)
                    n_cov += inside.sum()
                    n_valid_miss += (~inside).sum()
                    assert np.isin(rec, want).all(), (bid, "target not in chart")
                    assert (tgt & ~g.table.valid).sum() == 0
    print(f"songs {len(songs)}, groups {n_g} {roles}, charts {n_ch}; hit notes {n_hit}, as targets {n_cov}, "
          f"not targets (off-grid or outside valid positions) {n_hit - n_cov}")
    # cut-beat test: a red line at 2.5 beats of a 500 ms section
    sec = np.array([[0.0, 500.0, 4, 0, 0], [1250.0, 400.0, 4, 3, 0]])
    tb = beat_table(sec, 600)
    v = bits_to_bool(tb.valid)
    assert list(tb.beat[:5]) == [0, 1, 2, 3, 4], tb.beat[:5]
    k_ok = POS[v[2]]
    assert k_ok.max() < 24 and k_ok.min() == 0, k_ok          # beat 2 valid only before 2.5 (1250 ms)
    assert v[3].all() and np.isclose(tb.t0[3], 1250.0)
    print("cut-beat test ok; positions valid in beat 2:", k_ok.tolist())
    print("selftest ok")


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--shard")
    a = ap.parse_args(argv)
    if a.selftest:
        selftest(a.shard)


if __name__ == "__main__":
    main()