File size: 10,352 Bytes
e715519
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python3
"""
slice_n4_run.py
---------------
Slice the canonical RGC N4 logistic CSV into 253 roughly equal pieces
with small tail overlaps on every interior slice.

Design goals
------------
* Stream the source file — never load the full multi-GB CSV into RAM.
* Keep every slice self-contained (identical header row).
* Prefer cuts that fall on frame boundaries (multiples of 49 data rows)
  so a 49-core lattice snapshot is never split mid-frame.
* Add a configurable overlap (default 1.5 MB ≈ a few thousand frames)
  at the *start* of every slice except the first, and at the *end* of
  every slice except the last.  This gives contiguous analysis windows
  a small shared context for ACF / period-3 / order-parameter continuity.
* Produce deterministic, numbered output files:
      n4_slice_000.csv … n4_slice_252.csv

Usage
-----
  python slice_n4_run.py /path/to/logistic_20260606_145947.csv \\
                         [--outdir ./n4_slices] \\
                         [--n-slices 253] \\
                         [--overlap-mb 1.5] \\
                         [--cores 49]

The script only needs read access to the source and write access to
the output directory.  It prints a progress summary and a final
manifest (slice index, byte range, row estimate, file size).
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path
from typing import List, Tuple


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def human(n: float) -> str:
    """Pretty-print a byte count."""
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if abs(n) < 1024.0:
            return f"{n:6.1f} {unit}"
        n /= 1024.0
    return f"{n:.1f} PB"


def find_frame_aligned_offset(
    fh,
    target_byte: int,
    cores: int,
    header_len: int,
    search_window: int = 512 * 1024,
) -> int:
    """
    Return a byte offset >= target_byte that sits on a clean frame boundary
    (i.e. after a complete set of `cores` data rows).

    Strategy: jump near the target, read a modest window, count newlines,
    and advance until (data_rows_seen % cores) == 0.
    """
    file_size = fh.seek(0, os.SEEK_END)
    if target_byte >= file_size:
        return file_size

    # Start a little before the target so we have context
    start = max(header_len, target_byte - search_window // 4)
    fh.seek(start)
    buf = fh.read(search_window)
    if not buf:
        return file_size

    # If we started mid-line, discard the partial first line
    if start > header_len and buf[0:1] != b"\n":
        nl = buf.find(b"\n")
        if nl < 0:
            return min(file_size, start + len(buf))
        buf = buf[nl + 1 :]
        start += nl + 1

    # Walk line-by-line until we are past target_byte *and* on a frame edge
    pos = start
    data_rows = 0
    for line in buf.splitlines(keepends=True):
        pos += len(line)
        data_rows += 1
        if pos >= target_byte and (data_rows % cores) == 0:
            return min(pos, file_size)

    # Fallback: just return the end of the window (still better than mid-line)
    return min(pos, file_size)


def compute_slice_plan(
    file_size: int,
    header_len: int,
    n_slices: int,
    overlap_bytes: int,
    cores: int,
    fh,
) -> List[Tuple[int, int, int, int]]:
    """
    Return a list of (slice_idx, start_byte, end_byte, pure_end_byte).

    start_byte  – inclusive, may include leading overlap
    end_byte    – exclusive, may include trailing overlap
    pure_end_byte – the nominal boundary *without* trailing overlap
                    (used so the next slice knows where its leading
                    overlap should begin)
    """
    body_size = file_size - header_len
    if body_size <= 0:
        raise ValueError("File contains only a header (or is empty).")

    nominal_chunk = body_size / n_slices
    plan = []

    # First pass: pure (non-overlapping) boundaries, frame-aligned
    pure_bounds = [header_len]
    for i in range(1, n_slices):
        target = header_len + int(i * nominal_chunk)
        aligned = find_frame_aligned_offset(fh, target, cores, header_len)
        pure_bounds.append(aligned)
    pure_bounds.append(file_size)

    # Second pass: expand each interior slice by overlap_bytes on both sides
    for i in range(n_slices):
        pure_start = pure_bounds[i]
        pure_end = pure_bounds[i + 1]

        if i == 0:
            start = pure_start          # no leading overlap on first slice
        else:
            # Walk backward from pure_start by ~overlap_bytes, stay frame-aligned
            target = max(header_len, pure_start - overlap_bytes)
            start = find_frame_aligned_offset(fh, target, cores, header_len)
            # Guarantee we do not go past the previous pure boundary in a
            # way that would create negative-length regions
            start = min(start, pure_start)

        if i == n_slices - 1:
            end = pure_end              # no trailing overlap on last slice
        else:
            target = min(file_size, pure_end + overlap_bytes)
            end = find_frame_aligned_offset(fh, target, cores, header_len)

        plan.append((i, start, end, pure_end))

    return plan


# ---------------------------------------------------------------------------
# Main slicing routine
# ---------------------------------------------------------------------------

def slice_file(
    src: Path,
    outdir: Path,
    n_slices: int = 253,
    overlap_mb: float = 1.5,
    cores: int = 49,
    bufsize: int = 8 * 1024 * 1024,
) -> None:
    if not src.is_file():
        sys.exit(f"ERROR: source file not found: {src}")

    outdir.mkdir(parents=True, exist_ok=True)
    overlap_bytes = int(overlap_mb * 1024 * 1024)
    file_size = src.stat().st_size

    print(f"Source      : {src}")
    print(f"Size        : {human(file_size)}")
    print(f"Slices      : {n_slices}")
    print(f"Overlap     : {overlap_mb} MB  ({human(overlap_bytes)})")
    print(f"Cores/frame : {cores}")
    print(f"Output dir  : {outdir}")
    print()

    with open(src, "rb") as fh:
        # Read header (first line)
        header = fh.readline()
        if not header:
            sys.exit("ERROR: empty file")
        header_len = len(header)
        print(f"Header ({header_len} bytes): {header.decode('utf-8', errors='replace').rstrip()}")
        print()

        plan = compute_slice_plan(
            file_size, header_len, n_slices, overlap_bytes, cores, fh
        )

        manifest = []
        for idx, start, end, pure_end in plan:
            out_path = outdir / f"n4_slice_{idx:03d}.csv"
            length = end - start
            # Leading / trailing overlap sizes for the log
            lead = max(0, pure_end - start) if idx > 0 else 0
            # Actually lead = pure_start - start; we approximate via plan
            pure_start = plan[idx][1] if idx == 0 else plan[idx - 1][3]
            # Recompute cleanly
            pure_start_i = header_len if idx == 0 else plan[idx - 1][3]
            lead_ov = max(0, pure_start_i - start) if idx > 0 else 0
            trail_ov = max(0, end - pure_end) if idx < n_slices - 1 else 0

            with open(out_path, "wb") as out:
                out.write(header)          # every slice is self-describing
                fh.seek(start)
                remaining = length
                while remaining > 0:
                    chunk = fh.read(min(bufsize, remaining))
                    if not chunk:
                        break
                    out.write(chunk)
                    remaining -= len(chunk)

            final_size = out_path.stat().st_size
            manifest.append(
                {
                    "idx": idx,
                    "file": out_path.name,
                    "start": start,
                    "end": end,
                    "bytes": final_size,
                    "lead_ov": lead_ov,
                    "trail_ov": trail_ov,
                }
            )
            print(
                f"  [{idx:03d}] {out_path.name}  "
                f"{human(final_size)}  "
                f"bytes {start:,}–{end:,}  "
                f"lead_ov={human(lead_ov)}  trail_ov={human(trail_ov)}"
            )

    # Write a small manifest CSV for later bookkeeping
    man_path = outdir / "slice_manifest.csv"
    with open(man_path, "w", encoding="utf-8") as m:
        m.write("slice_idx,filename,start_byte,end_byte,file_bytes,lead_overlap_bytes,trail_overlap_bytes\n")
        for row in manifest:
            m.write(
                f"{row['idx']},{row['file']},{row['start']},{row['end']},"
                f"{row['bytes']},{row['lead_ov']},{row['trail_ov']}\n"
            )
    print()
    print(f"Manifest written to {man_path}")
    print(f"Done — {n_slices} slices.")


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def main() -> None:
    p = argparse.ArgumentParser(
        description="Slice canonical RGC N4 logistic CSV into overlapping pieces."
    )
    p.add_argument(
        "source",
        type=Path,
        help="Path to the full logistic_*.csv (canonical N4 run)",
    )
    p.add_argument(
        "--outdir",
        type=Path,
        default=Path("./n4_slices"),
        help="Directory for the slice files (default: ./n4_slices)",
    )
    p.add_argument(
        "--n-slices",
        type=int,
        default=253,
        help="Number of slices (default: 253)",
    )
    p.add_argument(
        "--overlap-mb",
        type=float,
        default=1.5,
        help="Overlap size in MiB at each interior boundary (default: 1.5)",
    )
    p.add_argument(
        "--cores",
        type=int,
        default=49,
        help="Cores per lattice frame (default: 49)",
    )
    args = p.parse_args()

    if args.n_slices < 1:
        sys.exit("--n-slices must be >= 1")
    if args.overlap_mb < 0:
        sys.exit("--overlap-mb must be >= 0")

    slice_file(
        src=args.source,
        outdir=args.outdir,
        n_slices=args.n_slices,
        overlap_mb=args.overlap_mb,
        cores=args.cores,
    )


if __name__ == "__main__":
    main()