forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9953355Tahinli6 days ago3940 commits

bdrate.py99 lines, 3.3 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Bjontegaard delta rate and delta PSNR between two rate-distortion curves.
3
4Usage: python3 -I bdrate.py [--metric y|yuv] <anchor.tsv> <test.tsv>
5
6Each TSV holds one operating point per line: `bytes<TAB>psnr_y<TAB>psnr_yuv`.
7`--metric` picks the PSNR column the curves are judged by (default yuv). Four
8points per curve is the usual Bjontegaard setup. The curves are fitted as cubic polynomials of
9log10(bytes) against PSNR (least squares with exact interpolation at four
10points), integrated over the PSNR range both cover.
11
12Prints `bd_rate_pct` (negative: the test curve needs fewer bytes for the same
13quality) and `bd_psnr_db` (positive: the test curve has more quality for the
14same bytes).
15"""
16import math
17import sys
18
19
20def load(path, metric):
21 col = {"y": 1, "yuv": 2}[metric]
22 pts = []
23 with open(path) as fh:
24 for line in fh:
25 line = line.strip()
26 if not line or line.startswith("#"):
27 continue
28 fields = line.split("\t")
29 pts.append((float(fields[0]), float(fields[col])))
30 return pts
31
32
33def solve(a, b):
34 """Solve a x = b by Gaussian elimination with partial pivoting."""
35 n = len(b)
36 m = [row[:] + [b[i]] for i, row in enumerate(a)]
37 for col in range(n):
38 piv = max(range(col, n), key=lambda r: abs(m[r][col]))
39 m[col], m[piv] = m[piv], m[col]
40 for r in range(n):
41 if r != col and m[col][col] != 0:
42 f = m[r][col] / m[col][col]
43 for c in range(col, n + 1):
44 m[r][c] -= f * m[col][c]
45 return [m[i][n] / m[i][i] for i in range(n)]
46
47
48def fit(xs, ys):
49 """Cubic a0 + a1 x + a2 x^2 + a3 x^3 through the points (least squares
50 via the normal equations; exact for four points)."""
51 rows = [[x ** k for k in range(4)] for x in xs]
52 ata = [[sum(r[i] * r[j] for r in rows) for j in range(4)] for i in range(4)]
53 aty = [sum(r[i] * y for r, y in zip(rows, ys)) for i in range(4)]
54 return solve(ata, aty)
55
56
57def integrate(coef, lo, hi):
58 def anti(x):
59 return sum(coef[k] * x ** (k + 1) / (k + 1) for k in range(4))
60 return (anti(hi) - anti(lo)) / (hi - lo)
61
62
63def main() -> int:
64 args = sys.argv[1:]
65 metric = "yuv"
66 if args[:1] == ["--metric"]:
67 metric = args[1]
68 args = args[2:]
69 anchor = load(args[0], metric)
70 test = load(args[1], metric)
71 a_psnr = [p for _, p in anchor]
72 t_psnr = [p for _, p in test]
73 lo = max(min(a_psnr), min(t_psnr))
74 hi = min(max(a_psnr), max(t_psnr))
75 if hi <= lo:
76 print("bd_rate_pct=nan bd_psnr_db=nan (PSNR ranges do not overlap)")
77 return 1
78 a_log = [math.log10(s) for s, _ in anchor]
79 t_log = [math.log10(s) for s, _ in test]
80 ca = fit(a_psnr, a_log)
81 ct = fit(t_psnr, t_log)
82 avg_a = integrate(ca, lo, hi)
83 avg_t = integrate(ct, lo, hi)
84 bd_rate = (10 ** (avg_t - avg_a) - 1) * 100
85
86 # BD-PSNR: fit PSNR against log rate and average over the rate overlap.
87 la = [math.log10(s) for s, _ in anchor]
88 lt = [math.log10(s) for s, _ in test]
89 lo_r = max(min(la), min(lt))
90 hi_r = min(max(la), max(lt))
91 pa = fit(la, a_psnr)
92 pt = fit(lt, t_psnr)
93 bd_psnr = integrate(pt, lo_r, hi_r) - integrate(pa, lo_r, hi_r)
94 print(f"bd_rate_pct={bd_rate:.2f} bd_psnr_db={bd_psnr:.3f}")
95 return 0
96
97
98if __name__ == "__main__":
99 sys.exit(main())