"""Build the HDD rotation table (CSV, JSON, SVG); no drive measurements.

Constant RPM gives a period of 60 / rpm seconds. Uniform target-relative phase
after positioning gives a half-period mean wait. The reciprocal mean is a
conditional serial-model rate, not a workload-independent HDD IOPS ceiling.
The published column preserves the Wikipedia cross-check recorded on 2026-10-12.
Standalone download: pass --output-dir to a writable directory.
"""
import csv, json, math
from decimal import Decimal as D, ROUND_HALF_UP
from pathlib import Path

import argparse

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, required=True)
d = parser.parse_args().output_dir
d.mkdir(parents=True, exist_ok=True)
SLUG = "hdd-rotational-latency-calc"
PUBLISHED = {3600: "8.33", 4200: "7.14", 5400: "5.56", 7200: "4.17", 10000: "3.00", 15000: "2.00"}
q = lambda x, p: str(x.quantize(D(p), rounding=ROUND_HALF_UP))
hdr = ["rpm", "revolutions_per_second", "max_latency_ms", "avg_latency_ms", "published_avg_latency_ms", "rotation_only_iops_qd1"]
rows = []
for rpm, pub in PUBLISHED.items():
    mx = D(60000) / D(rpm)
    avg = mx / 2
    rows.append([rpm, q(D(rpm) / 60, "0.01"), q(mx, "0.01"), q(avg, "0.01"), pub, q(D(1000) / avg, "0.1")])
with open(d / f"{SLUG}.csv", "w", newline="") as fh:
    cw = csv.writer(fh, lineterminator="\n")
    cw.writerow(hdr)
    cw.writerows(rows)

columns = [
    ("rpm", "integer", "Spindle speed in revolutions per minute."),
    ("revolutions_per_second", "number", "rpm / 60, two decimals."),
    ("max_latency_ms", "number", "60000 / rpm: one-revolution period in milliseconds at constant RPM, rounded to two decimals. Legacy field name retained; this bounds a single uninterrupted wait for the next target-sector passage, not total request latency."),
    ("avg_latency_ms", "number", "Half of the unrounded revolution period under a uniform target-relative phase model after positioning, rounded to two decimals."),
    ("published_avg_latency_ms", "number", "Average rotational latency as printed in the cited Wikipedia article (table for 4,200 to 15,000 rpm, text for 3,600 rpm). The build checks it equals avg_latency_ms."),
    ("rotation_only_iops_qd1", "number", "1000 divided by the unrounded uniform-phase mean wait in ms, equivalently rpm / 30. Conditional continuously busy serial-model rate with rotation as the only delay, rounded to one decimal; not a workload-independent IOPS ceiling."),
]
# Constructed serial sequence, separate from the six spindle-speed rows.
waits_ms = [D(1), D(9)]
elapsed_ms = sum(waits_ms)
serial_example = {
    "evidenceType": "constructed arithmetic example; not drive measurements",
    "waitsMs": [int(wait) for wait in waits_ms],
    "completionCount": len(waits_ms),
    "elapsedMs": str(elapsed_ms),
    "meanWaitMs": str(elapsed_ms / len(waits_ms)),
    "aggregateOpsPerSecond": q(D(1000) * len(waits_ms) / elapsed_ms, "0.1"),
    "meanReciprocalOpsPerSecond": q(sum(D(1000) / wait for wait in waits_ms) / len(waits_ms), "0.1"),
    "assumptions": "One completed operation per positive wait, serial service, no idle gaps, no overlap and no other cost. The two waits are chosen examples, not a uniform-phase sample estimate or a measured trace.",
}
meta = {
    "schemaVersion": 1,
    "slug": SLUG,
    "title": "HDD rotational latency by spindle speed",
    "summary": "One-revolution periods and uniform-phase mean waits for six spindle speeds from 3,600 to 15,000 rpm. At 7,200 rpm the period is 8.33 ms and the model mean is 4.17 ms. The reciprocal mean gives 240 operations/s in this rotation-only serial model, not an HDD performance ceiling. Calculated values, no drive measurements.",
    "published": "2026-10-12",
    "updated": "2026-11-06",
    "evidenceType": "arithmetic from a published definition; no measurements",
    "license": "CC0-1.0 for the generated rows, which are arithmetic. The cited article keeps its own rights and no text from it is copied.",
    "licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/",
    "sourceUrl": "https://pages.cs.wisc.edu/~remzi/OSTEP/file-disks.pdf",
    "humanPage": "https://hesela.com/tech/hdd/",
    "correction": "2026-11-06: clarified the conditional phase model and removed the general IOPS-ceiling interpretation. Original six CSV rows, column identifiers and recorded published-value cross-checks are unchanged.",
    "downloadPath": f"/data/datasets/{SLUG}.csv",
    "chartPath": f"/data/datasets/{SLUG}.svg",
    "codePath": f"/scripts/build-hdd-rotational-latency.py",
    "rowCount": len(rows),
    "serialRateExample": serial_example,
    "columns": [{"name": a, "type": b, "description": c} for a, b, c in columns],
    "method": "Assume constant spindle speed and uniform target-relative phase after positioning. The period is 60000 / rpm ms and the mean remaining rotational wait is half that period. The platter continues rotating during a seek. For continuously busy serial service with only this wait, reciprocal mean service time is rpm / 30 operations/s. Compute from unrounded values, then round for display; do not invert the rounded CSV mean. The published column retains the Wikipedia cross-check recorded on 2026-10-12, not a new measurement. OSTEP chapter 37 explains the access components; Ruemmler and Wilkes (1994) describe why correlated requests require phase-aware modeling.",
    "limits": [
        "Arithmetic from a definition, not measurements of any drive. No confidence interval applies.",
        "Uniform phase after positioning is an assumption, not a consequence of RPM or queue depth. Locality, read-ahead and rotation-aware scheduling can change the service process.",
        "One revolution bounds only the single uninterrupted wait for the next target-sector passage. Seeking, transfer, queuing, retries and controller work can make request latency longer. The reciprocal model mean is not a workload-independent IOPS ceiling.",
        "Spindle speeds are the round values in the cited article. A drive can differ from its nominal speed.",
    ],
    "citations": [
        {"id": "ostep-hdd", "title": "Arpaci-Dusseau and Arpaci-Dusseau: OSTEP, chapter 37, sections 37.3-37.5 (rotation, positioning and scheduling)", "url": "https://pages.cs.wisc.edu/~remzi/OSTEP/file-disks.pdf", "accessed": "2026-11-06"},
        {"id": "disk-model", "title": "Ruemmler and Wilkes: An Introduction to Disk Drive Modeling, IEEE Computer 27(3):17-29 (March 1994), controller and rotational-position modeling sections", "url": "https://www.pdl.cmu.edu/Publications/HTML-Papers/DiskModeling/i.shtml", "accessed": "2026-11-06"},
        {"id": "wp-hddperf", "title": "Hard disk drive performance characteristics, Wikipedia: rotational latency section and table of typical figures", "url": "https://en.wikipedia.org/wiki/Hard_disk_drive_performance_characteristics", "accessed": "2026-10-12"},
    ],
}
with open(d / f"{SLUG}.json", "w") as f:
    json.dump(meta, f, indent=2)
    f.write("\n")

# Chart uses legacy CSV columns but labels their model scope explicitly.
W, H, L, R, T, B = 760, 420, 70, 30, 70, 70
ymax = 20
sy = lambda v: T + (H - T - B) * (1 - v / ymax)
n = len(rows)
bw = (W - L - R) / n
s = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" font-family="sans-serif" font-size="12">',
     '<title>Rotational latency by spindle speed</title>', f'<rect width="{W}" height="{H}" fill="#fff"/>',
     '<text x="20" y="26" font-size="15" font-weight="bold">Rotational latency by spindle speed</text>',
     '<text x="20" y="46" fill="#444">Light: one-revolution period. Dark: uniform-phase mean. Every bar is a CSV cell.</text>']
for v in range(0, ymax + 1, 5):
    s.append(f'<line x1="{L}" y1="{sy(v)}" x2="{W - R}" y2="{sy(v)}" stroke="#ddd"/>')
    s.append(f'<text x="{L - 8}" y="{sy(v) + 4}" text-anchor="end" fill="#444">{v} ms</text>')
for i, r in enumerate(rows):
    x = L + bw * i + 10
    w = bw - 20
    mx, av = float(r[2]), float(r[3])
    s.append(f'<rect x="{x:.1f}" y="{sy(mx):.1f}" width="{w:.1f}" height="{H - B - sy(mx):.1f}" fill="#a9c4e4"/>')
    s.append(f'<rect x="{x:.1f}" y="{sy(av):.1f}" width="{w:.1f}" height="{H - B - sy(av):.1f}" fill="#1f5fa8"/>')
    s.append(f'<text x="{x + w / 2:.1f}" y="{sy(mx) - 5:.1f}" text-anchor="middle" font-size="11">{r[2]}</text>')
    s.append(f'<text x="{x + w / 2:.1f}" y="{sy(av) + 14:.1f}" text-anchor="middle" font-size="11" fill="#fff">{r[3]}</text>')
    s.append(f'<text x="{x + w / 2:.1f}" y="{H - B + 18}" text-anchor="middle">{r[0]:,} rpm</text>')
s.append(f'<text x="{L}" y="{H - 14}" fill="#444">Constant RPM; uniform phase after positioning. Arithmetic only. Sources in JSON metadata.</text>')
s.append('</svg>')
(d / f"{SLUG}.svg").write_text("\n".join(s) + "\n")
print(len(rows))
