Datasets:
Download scripts/slice_n4_run.py from parti-wave/N4_slice: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/parti-wave/N4_slice/resolve/main/scripts/slice_n4_run.py
- Command line
-
hf download hf://datasets/parti-wave/N4_slice/scripts/slice_n4_run.py
-
curl -L -o slice_n4_run.py https://huggingface.co/datasets/parti-wave/N4_slice/resolve/main/scripts/slice_n4_run.py
10.4 kB
| #!/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() | |