csdigit 0.5__tar.gz → 0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. {csdigit-0.5 → csdigit-0.6}/.gitignore +11 -0
  2. {csdigit-0.5 → csdigit-0.6}/CHANGELOG.md +5 -0
  3. {csdigit-0.5/src/csdigit.egg-info → csdigit-0.6}/PKG-INFO +1 -1
  4. csdigit-0.6/examples/gaussian_blur_1d.v +86 -0
  5. csdigit-0.6/examples/gaussian_blur_1d_tb.v +62 -0
  6. csdigit-0.6/examples/gaussian_blur_csd.py +510 -0
  7. csdigit-0.6/examples/temperature_c_to_f.py +346 -0
  8. csdigit-0.6/examples/temperature_c_to_f.v +30 -0
  9. csdigit-0.6/examples/temperature_c_to_f_tb.v +28 -0
  10. csdigit-0.6/paper/Makefile +43 -0
  11. csdigit-0.6/paper/beamer-preamble.tex +28 -0
  12. csdigit-0.6/paper/csd-tutorial-talk.md +359 -0
  13. csdigit-0.6/paper/csd-tutorial-talk.pdf +0 -0
  14. csdigit-0.6/paper/csd-tutorial.md +446 -0
  15. csdigit-0.6/paper/csd-tutorial.pdf +0 -0
  16. csdigit-0.6/paper/references.bib +156 -0
  17. {csdigit-0.5 → csdigit-0.6/src/csdigit.egg-info}/PKG-INFO +1 -1
  18. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/SOURCES.txt +13 -0
  19. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/scm_file_list.json +13 -0
  20. csdigit-0.6/src/csdigit.egg-info/scm_version.json +8 -0
  21. csdigit-0.5/src/csdigit.egg-info/scm_version.json +0 -8
  22. {csdigit-0.5 → csdigit-0.6}/.coveragerc +0 -0
  23. {csdigit-0.5 → csdigit-0.6}/.github/workflows/ci.yml +0 -0
  24. {csdigit-0.5 → csdigit-0.6}/.github/workflows/codecov.yml +0 -0
  25. {csdigit-0.5 → csdigit-0.6}/.github/workflows/jekyll-gh-pages.yml +0 -0
  26. {csdigit-0.5 → csdigit-0.6}/.github/workflows/multi-platforms.yml +0 -0
  27. {csdigit-0.5 → csdigit-0.6}/.github/workflows/python-app.yml +0 -0
  28. {csdigit-0.5 → csdigit-0.6}/.github/workflows/python-package.yml +0 -0
  29. {csdigit-0.5 → csdigit-0.6}/.github/workflows/python-publish.yml +0 -0
  30. {csdigit-0.5 → csdigit-0.6}/.isort.cfg +0 -0
  31. {csdigit-0.5 → csdigit-0.6}/.pre-commit-config.yaml +0 -0
  32. {csdigit-0.5 → csdigit-0.6}/.readthedocs.yml +0 -0
  33. {csdigit-0.5 → csdigit-0.6}/.vscode/settings.json +0 -0
  34. {csdigit-0.5 → csdigit-0.6}/AGENTS.md +0 -0
  35. {csdigit-0.5 → csdigit-0.6}/AUTHORS.md +0 -0
  36. {csdigit-0.5 → csdigit-0.6}/CONTRIBUTING.md +0 -0
  37. {csdigit-0.5 → csdigit-0.6}/GEMINI.md +0 -0
  38. {csdigit-0.5 → csdigit-0.6}/LICENSE.txt +0 -0
  39. {csdigit-0.5 → csdigit-0.6}/README.md +0 -0
  40. {csdigit-0.5 → csdigit-0.6}/_config.yml +0 -0
  41. {csdigit-0.5 → csdigit-0.6}/benches/bench_csd.py +0 -0
  42. {csdigit-0.5 → csdigit-0.6}/benches/test_bench.py +0 -0
  43. {csdigit-0.5 → csdigit-0.6}/benches/verify_output.py +0 -0
  44. {csdigit-0.5 → csdigit-0.6}/compare-py-cpp-rs.md +0 -0
  45. {csdigit-0.5 → csdigit-0.6}/docs/Makefile +0 -0
  46. {csdigit-0.5 → csdigit-0.6}/docs/_static/.gitignore +0 -0
  47. {csdigit-0.5 → csdigit-0.6}/docs/authors.md +0 -0
  48. {csdigit-0.5 → csdigit-0.6}/docs/changelog.md +0 -0
  49. {csdigit-0.5 → csdigit-0.6}/docs/conf.py +0 -0
  50. {csdigit-0.5 → csdigit-0.6}/docs/contributing.md +0 -0
  51. {csdigit-0.5 → csdigit-0.6}/docs/examples/plot_csd_conversion.py +0 -0
  52. {csdigit-0.5 → csdigit-0.6}/docs/examples/plot_csd_distribution.py +0 -0
  53. {csdigit-0.5 → csdigit-0.6}/docs/figures_demo.md +0 -0
  54. {csdigit-0.5 → csdigit-0.6}/docs/index.md +0 -0
  55. {csdigit-0.5 → csdigit-0.6}/docs/license.md +0 -0
  56. {csdigit-0.5 → csdigit-0.6}/docs/readme.md +0 -0
  57. {csdigit-0.5 → csdigit-0.6}/docs/requirements.txt +0 -0
  58. {csdigit-0.5 → csdigit-0.6}/environment.yml +0 -0
  59. {csdigit-0.5 → csdigit-0.6}/experiments/notes.md +0 -0
  60. {csdigit-0.5 → csdigit-0.6}/experiments/random_gen.py +0 -0
  61. {csdigit-0.5 → csdigit-0.6}/mypy.ini +0 -0
  62. {csdigit-0.5 → csdigit-0.6}/pyproject.toml +0 -0
  63. {csdigit-0.5 → csdigit-0.6}/requirements/README.md +0 -0
  64. {csdigit-0.5 → csdigit-0.6}/requirements/default.txt +0 -0
  65. {csdigit-0.5 → csdigit-0.6}/requirements/doc.txt +0 -0
  66. {csdigit-0.5 → csdigit-0.6}/requirements/extras.txt +0 -0
  67. {csdigit-0.5 → csdigit-0.6}/requirements/test.txt +0 -0
  68. {csdigit-0.5 → csdigit-0.6}/requirements.txt +0 -0
  69. {csdigit-0.5 → csdigit-0.6}/setup.cfg +0 -0
  70. {csdigit-0.5 → csdigit-0.6}/setup.py +0 -0
  71. {csdigit-0.5 → csdigit-0.6}/src/csdigit/__init__.py +0 -0
  72. {csdigit-0.5 → csdigit-0.6}/src/csdigit/cli.py +0 -0
  73. {csdigit-0.5 → csdigit-0.6}/src/csdigit/csd.py +0 -0
  74. {csdigit-0.5 → csdigit-0.6}/src/csdigit/csd_multiplier.py +0 -0
  75. {csdigit-0.5 → csdigit-0.6}/src/csdigit/lcsre.py +0 -0
  76. {csdigit-0.5 → csdigit-0.6}/src/csdigit/py.typed +0 -0
  77. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/dependency_links.txt +0 -0
  78. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/not-zip-safe +0 -0
  79. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/requires.txt +0 -0
  80. {csdigit-0.5 → csdigit-0.6}/src/csdigit.egg-info/top_level.txt +0 -0
  81. {csdigit-0.5 → csdigit-0.6}/src/pycsd/README +0 -0
  82. {csdigit-0.5 → csdigit-0.6}/src/pycsd/__init__.py +0 -0
  83. {csdigit-0.5 → csdigit-0.6}/src/pycsd/csd/__init__.py +0 -0
  84. {csdigit-0.5 → csdigit-0.6}/src/pycsd/csd/csd.py +0 -0
  85. {csdigit-0.5 → csdigit-0.6}/src/pycsd/csd_orig.py +0 -0
  86. {csdigit-0.5 → csdigit-0.6}/src/pycsd/dev/csd_numbers.py +0 -0
  87. {csdigit-0.5 → csdigit-0.6}/src/pycsd/from_csd +0 -0
  88. {csdigit-0.5 → csdigit-0.6}/src/pycsd/run_tests.py +0 -0
  89. {csdigit-0.5 → csdigit-0.6}/src/pycsd/test/__init__.py +0 -0
  90. {csdigit-0.5 → csdigit-0.6}/src/pycsd/test/decimal_tests.py +0 -0
  91. {csdigit-0.5 → csdigit-0.6}/src/pycsd/test/test_csd_decimals.py +0 -0
  92. {csdigit-0.5 → csdigit-0.6}/src/pycsd/test/test_csd_integers.py +0 -0
  93. {csdigit-0.5 → csdigit-0.6}/src/pycsd/test/test_to_and_fro_10bits.py +0 -0
  94. {csdigit-0.5 → csdigit-0.6}/src/pycsd/to_csd +0 -0
  95. {csdigit-0.5 → csdigit-0.6}/tests/conftest.py +0 -0
  96. {csdigit-0.5 → csdigit-0.6}/tests/test_cli.py +0 -0
  97. {csdigit-0.5 → csdigit-0.6}/tests/test_csd.py +0 -0
  98. {csdigit-0.5 → csdigit-0.6}/tests/test_csd_multiplier.py +0 -0
  99. {csdigit-0.5 → csdigit-0.6}/tests/test_lcsre.py +0 -0
  100. {csdigit-0.5 → csdigit-0.6}/tox.ini +0 -0
@@ -180,3 +180,14 @@ MANIFEST
180
180
  # Cache dirs
181
181
  .ruff_cache/
182
182
  .benchmarks/
183
+
184
+ # Paper build artifacts
185
+ paper/*.aux
186
+ paper/*.log
187
+ paper/*.nav
188
+ paper/*.out
189
+ paper/*.snm
190
+ paper/*.toc
191
+ paper/*.vrb
192
+ paper/csd-tutorial-talk.tex
193
+ paper/*.txt
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## Version 0.6 (2026-11-20)
4
+
5
+ ### Documentation
6
+ - **CSD tutorial paper, talk and demos**: Added the canonical-signed-digit tutorial paper, its accompanying presentation, and the demonstration scripts. (#2562cd1)
7
+
3
8
  ## Version 0.5 (2026-10-09)
4
9
 
5
10
  ### Bug Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: csdigit
3
- Version: 0.5
3
+ Version: 0.6
4
4
  Summary: Canonical Signed Digit Conversion in Python
5
5
  Home-page: https://github.com/luk036/csdigit
6
6
  Author: Wai-Shing Luk
@@ -0,0 +1,86 @@
1
+
2
+ module csd_mult_72 (
3
+ input signed [10:0] x, // Input value
4
+ output signed [16:0] result // Result of multiplication
5
+ );
6
+
7
+ // Create shifted versions of input
8
+ wire signed [16:0] x_shift6 = x <<< 6;
9
+ wire signed [16:0] x_shift3 = x <<< 3;
10
+
11
+ // CSD implementation
12
+ assign result = x_shift6 + x_shift3;
13
+ endmodule
14
+
15
+
16
+ module csd_mult_134 (
17
+ input signed [10:0] x, // Input value
18
+ output signed [17:0] result // Result of multiplication
19
+ );
20
+
21
+ // Create shifted versions of input
22
+ wire signed [17:0] x_shift7 = x <<< 7;
23
+ wire signed [17:0] x_shift3 = x <<< 3;
24
+ wire signed [17:0] x_shift1 = x <<< 1;
25
+
26
+ // CSD implementation
27
+ assign result = x_shift7 + x_shift3 - x_shift1;
28
+ endmodule
29
+
30
+
31
+ module csd_mult_194 (
32
+ input signed [10:0] x, // Input value
33
+ output signed [18:0] result // Result of multiplication
34
+ );
35
+
36
+ // Create shifted versions of input
37
+ wire signed [18:0] x_shift8 = x <<< 8;
38
+ wire signed [18:0] x_shift6 = x <<< 6;
39
+ wire signed [18:0] x_shift1 = x <<< 1;
40
+
41
+ // CSD implementation
42
+ assign result = x_shift8 - x_shift6 + x_shift1;
43
+ endmodule
44
+
45
+
46
+ module csd_mult_224 (
47
+ input signed [10:0] x, // Input value
48
+ output signed [18:0] result // Result of multiplication
49
+ );
50
+
51
+ // Create shifted versions of input
52
+ wire signed [18:0] x_shift8 = x <<< 8;
53
+ wire signed [18:0] x_shift5 = x <<< 5;
54
+
55
+ // CSD implementation
56
+ assign result = x_shift8 - x_shift5;
57
+ endmodule
58
+
59
+ module gaussian_blur_1d (
60
+ input [7:0] x0, x1, x2, x3, x4, x5, x6,
61
+ output [7:0] y
62
+ );
63
+ wire signed [10:0] s3 = x0 + x6;
64
+ wire signed [10:0] s2 = x1 + x5;
65
+ wire signed [10:0] s1 = x2 + x4;
66
+ wire signed [10:0] s0 = x3;
67
+
68
+ wire signed [16:0] p3_raw;
69
+ wire signed [17:0] p2_raw;
70
+ wire signed [18:0] p1_raw;
71
+ wire signed [18:0] p0_raw;
72
+
73
+ csd_mult_72 m3 (.x(s3), .result(p3_raw));
74
+ csd_mult_134 m2 (.x(s2), .result(p2_raw));
75
+ csd_mult_194 m1 (.x(s1), .result(p1_raw));
76
+ csd_mult_224 m0 (.x(s0), .result(p0_raw));
77
+
78
+ wire signed [18:0] p3 = p3_raw;
79
+ wire signed [18:0] p2 = p2_raw;
80
+ wire signed [18:0] p1 = p1_raw;
81
+ wire signed [18:0] p0 = p0_raw;
82
+ wire signed [18:0] total = p3 + p2 + p1 + p0;
83
+ wire signed [18:0] rounded = (total + 19'sd512) >>> 10;
84
+
85
+ assign y = rounded[7:0];
86
+ endmodule
@@ -0,0 +1,62 @@
1
+
2
+ module tb;
3
+ reg [7:0] x0, x1, x2, x3, x4, x5, x6;
4
+ wire [7:0] y;
5
+
6
+ gaussian_blur_1d dut (
7
+ .x0(x0), .x1(x1), .x2(x2), .x3(x3),
8
+ .x4(x4), .x5(x5), .x6(x6), .y(y)
9
+ );
10
+
11
+ task check;
12
+ input [7:0] v0, v1, v2, v3, v4, v5, v6;
13
+ input [7:0] expected;
14
+ begin
15
+ x0 = v0; x1 = v1; x2 = v2; x3 = v3;
16
+ x4 = v4; x5 = v5; x6 = v6;
17
+ #1;
18
+ if (y !== expected) begin
19
+ $display("MISMATCH x=%0d,%0d,%0d,%0d,%0d,%0d,%0d y=%0d expected=%0d",
20
+ v0, v1, v2, v3, v4, v5, v6, y, expected);
21
+ $fatal(1, "Gaussian blur RTL mismatch");
22
+ end
23
+ end
24
+ endtask
25
+
26
+ initial begin
27
+ check(8'd0, 8'd0, 8'd0, 8'd0, 8'd0, 8'd0, 8'd0, 8'd0);
28
+ check(8'd255, 8'd255, 8'd255, 8'd255, 8'd255, 8'd255, 8'd255, 8'd255);
29
+ check(8'd128, 8'd128, 8'd128, 8'd128, 8'd128, 8'd128, 8'd128, 8'd128);
30
+ check(8'd0, 8'd255, 8'd0, 8'd255, 8'd0, 8'd255, 8'd0, 8'd123);
31
+ check(8'd255, 8'd0, 8'd255, 8'd0, 8'd255, 8'd0, 8'd255, 8'd132);
32
+ check(8'd0, 8'd0, 8'd0, 8'd255, 8'd0, 8'd0, 8'd0, 8'd56);
33
+ check(8'd0, 8'd0, 8'd255, 8'd0, 8'd255, 8'd0, 8'd0, 8'd97);
34
+ check(8'd255, 8'd0, 8'd0, 8'd0, 8'd0, 8'd0, 8'd255, 8'd36);
35
+ check(8'd57, 8'd12, 8'd140, 8'd125, 8'd114, 8'd71, 8'd52, 8'd94);
36
+ check(8'd44, 8'd216, 8'd16, 8'd15, 8'd47, 8'd111, 8'd119, 8'd69);
37
+ check(8'd13, 8'd101, 8'd214, 8'd112, 8'd229, 8'd142, 8'd3, 8'd141);
38
+ check(8'd81, 8'd216, 8'd174, 8'd142, 8'd79, 8'd110, 8'd172, 8'd139);
39
+ check(8'd52, 8'd47, 8'd194, 8'd49, 8'd183, 8'd176, 8'd135, 8'd124);
40
+ check(8'd22, 8'd235, 8'd63, 8'd193, 8'd40, 8'd150, 8'd185, 8'd127);
41
+ check(8'd98, 8'd35, 8'd23, 8'd116, 8'd148, 8'd40, 8'd119, 8'd83);
42
+ check(8'd51, 8'd194, 8'd142, 8'd232, 8'd186, 8'd83, 8'd189, 8'd166);
43
+ check(8'd181, 8'd107, 8'd136, 8'd36, 8'd87, 8'd125, 8'd83, 8'd99);
44
+ check(8'd236, 8'd194, 8'd138, 8'd112, 8'd166, 8'd28, 8'd117, 8'd136);
45
+ check(8'd16, 8'd161, 8'd205, 8'd137, 8'd33, 8'd108, 8'd161, 8'd123);
46
+ check(8'd108, 8'd255, 8'd202, 8'd234, 8'd73, 8'd135, 8'd71, 8'd167);
47
+ check(8'd126, 8'd134, 8'd219, 8'd204, 8'd185, 8'd112, 8'd70, 8'd167);
48
+ check(8'd252, 8'd46, 8'd24, 8'd56, 8'd78, 8'd81, 8'd216, 8'd81);
49
+ check(8'd32, 8'd197, 8'd195, 8'd239, 8'd128, 8'd5, 8'd58, 8'd146);
50
+ check(8'd136, 8'd174, 8'd57, 8'd150, 8'd222, 8'd80, 8'd232, 8'd145);
51
+ check(8'd1, 8'd134, 8'd91, 8'd54, 8'd152, 8'd101, 8'd78, 8'd94);
52
+ check(8'd191, 8'd82, 8'd0, 8'd165, 8'd250, 8'd9, 8'd57, 8'd113);
53
+ check(8'd185, 8'd157, 8'd122, 8'd29, 8'd123, 8'd40, 8'd43, 8'd95);
54
+ check(8'd248, 8'd35, 8'd64, 8'd65, 8'd243, 8'd84, 8'd135, 8'd115);
55
+ check(8'd216, 8'd108, 8'd102, 8'd159, 8'd204, 8'd191, 8'd224, 8'd163);
56
+ check(8'd231, 8'd61, 8'd126, 8'd115, 8'd32, 8'd173, 8'd10, 8'd103);
57
+ check(8'd117, 8'd112, 8'd3, 8'd36, 8'd30, 8'd117, 8'd34, 8'd55);
58
+ check(8'd16, 8'd169, 8'd36, 8'd121, 8'd142, 8'd248, 8'd109, 8'd124);
59
+ $display("PASS: all 32 vectors match the CSD kernel");
60
+ $finish;
61
+ end
62
+ endmodule
@@ -0,0 +1,510 @@
1
+ """CSD multiplier demo: a separable 7-tap Gaussian blur filter.
2
+
3
+ The blur kernel is a 7-tap Gaussian with ``sigma = 2`` and an integer scale of
4
+ ``1024``. The exact kernel is ``[72, 134, 195, 222, 195, 134, 72]``; its
5
+ coefficients sum to 1024. A separable 2D blur applies this 1D kernel
6
+ horizontally and vertically, so the 1D adder cost is paid twice.
7
+
8
+ For an 8-bit image, the worst-case pre-round output error of a CSD
9
+ approximation is
10
+
11
+ 255 * max(P, N) / 1024,
12
+
13
+ where ``P`` and ``N`` are the sums of the positive and negative coefficient
14
+ errors over the full kernel. Using the L1 sum instead would be conservative
15
+ when the coefficient errors have mixed signs. The demo searches, within a
16
+ +/-32 coefficient window around the exact kernel, for the minimum total NNZ
17
+ under two error targets:
18
+
19
+ * ``0.5`` LSB: 18 NNZ, worst-case error 0.498 LSB;
20
+ * ``1.0`` LSB: 16 NNZ, worst-case error 0.996 LSB.
21
+
22
+ The exact kernel needs 21 NNZ. The 18-NNZ design is emitted as a symmetric
23
+ 1D FIR: three pair pre-adds, four CSD coefficient multipliers, three product
24
+ adds, and one rounding add, for 13 adders per pass (26 for the separable 2D
25
+ filter, excluding line buffers). The direct non-symmetric form would need 18
26
+ adders per pass.
27
+
28
+ Run with::
29
+
30
+ python examples/gaussian_blur_csd.py
31
+
32
+ It writes ``gaussian_blur_1d.v`` and ``gaussian_blur_1d_tb.v`` next to this
33
+ file and simulates them with Icarus Verilog when available.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import random
39
+ import shutil
40
+ import subprocess
41
+ import sys
42
+ import tempfile
43
+ from pathlib import Path
44
+ from typing import NamedTuple
45
+
46
+ from csdigit.csd import to_csd_i
47
+ from csdigit.csd_multiplier import generate_csd_multiplier
48
+
49
+ SIGMA = 2.0
50
+ SCALE = 1024
51
+ TAPS = 7
52
+ INPUT_WIDTH = 11
53
+ EXACT_INDEPENDENT = (222, 195, 134, 72)
54
+ SEARCH_WINDOW = 32
55
+
56
+
57
+ class Approximation(NamedTuple):
58
+ """One symmetric CSD kernel approximation.
59
+
60
+ The independent coefficients are ``(center, +-1, +-2, +-3)``; the full
61
+ kernel is ``(a3, a2, a1, a0, a1, a2, a3)``.
62
+ """
63
+
64
+ target_lsb: float
65
+ independent: tuple[int, int, int, int]
66
+ weights: tuple[int, int, int, int]
67
+ positive_error: int
68
+ negative_error: int
69
+
70
+ @property
71
+ def full_kernel(self) -> tuple[int, int, int, int, int, int, int]:
72
+ """Return the seven coefficients in image order.
73
+
74
+ :return: full kernel from left to right
75
+ :rtype: tuple[int, int, int, int, int, int, int]
76
+ """
77
+ a0, a1, a2, a3 = self.independent
78
+ return (a3, a2, a1, a0, a1, a2, a3)
79
+
80
+ @property
81
+ def total_nnz(self) -> int:
82
+ """Return the NNZ of the full seven-tap kernel.
83
+
84
+ :return: sum of the seven CSD weights
85
+ :rtype: int
86
+ """
87
+ a0, a1, a2, a3 = self.weights
88
+ return a0 + 2 * (a1 + a2 + a3)
89
+
90
+ @property
91
+ def worst_error_lsb(self) -> float:
92
+ """Return the worst-case pre-round error in output LSBs.
93
+
94
+ :return: ``255 * max(positive_error, negative_error) / SCALE``
95
+ :rtype: float
96
+ """
97
+ return 255.0 * max(self.positive_error, self.negative_error) / SCALE
98
+
99
+ @property
100
+ def coefficient_adders(self) -> int:
101
+ """Return the adders inside the four coefficient multipliers.
102
+
103
+ :return: sum of ``weight - 1`` over the independent coefficients
104
+ :rtype: int
105
+ """
106
+ return sum(weight - 1 for weight in self.weights)
107
+
108
+ @property
109
+ def one_dimensional_adders(self) -> int:
110
+ """Return the adders in the symmetric 1D pass.
111
+
112
+ The count is three pair pre-adds, the coefficient adders, three
113
+ product-accumulation adders, and one rounding adder.
114
+
115
+ :return: arithmetic cells in one 1D pass
116
+ :rtype: int
117
+ """
118
+ return 3 + self.coefficient_adders + 3 + 1
119
+
120
+ @property
121
+ def two_dimensional_adders(self) -> int:
122
+ """Return the arithmetic cells in the separable 2D filter.
123
+
124
+ :return: two times the 1D adder count, excluding line buffers
125
+ :rtype: int
126
+ """
127
+ return 2 * self.one_dimensional_adders
128
+
129
+
130
+ def count_nnz(csd: str) -> int:
131
+ """Count non-zero digits in a CSD string.
132
+
133
+ :param csd: CSD string containing only ``+``, ``-`` and ``0``
134
+ :type csd: str
135
+ :return: number of ``+`` and ``-`` digits
136
+ :rtype: int
137
+
138
+ Examples:
139
+ >>> count_nnz("+00-0+0-")
140
+ 4
141
+ """
142
+ return csd.count("+") + csd.count("-")
143
+
144
+
145
+ def full_kernel(
146
+ independent: tuple[int, int, int, int]
147
+ ) -> tuple[int, int, int, int, int, int, int]:
148
+ """Expand a symmetric independent kernel to seven taps.
149
+
150
+ :param independent: ``(center, +-1, +-2, +-3)`` coefficients
151
+ :type independent: tuple[int, int, int, int]
152
+ :return: seven coefficients in image order
153
+ :rtype: tuple[int, int, int, int, int, int, int]
154
+ """
155
+ a0, a1, a2, a3 = independent
156
+ return (a3, a2, a1, a0, a1, a2, a3)
157
+
158
+
159
+ def worst_error_lsb(independent: tuple[int, int, int, int]) -> tuple[int, int, float]:
160
+ """Compute the exact worst-case convolution error.
161
+
162
+ For independent 8-bit pixels, the maximum of ``sum(delta_i * x_i)`` is
163
+ ``255 * max(P, N)``, where ``P`` and ``N`` are the positive and negative
164
+ error sums. This is tighter than the L1 bound when errors have mixed
165
+ signs.
166
+
167
+ :param independent: ``(center, +-1, +-2, +-3)`` coefficients
168
+ :type independent: tuple[int, int, int, int]
169
+ :return: positive error sum, negative error sum, and worst error in LSBs
170
+ :rtype: tuple[int, int, float]
171
+
172
+ Examples:
173
+ >>> worst_error_lsb((224, 194, 134, 72))
174
+ (2, 2, 0.498046875)
175
+ """
176
+ delta = tuple(a - c for a, c in zip(independent, EXACT_INDEPENDENT))
177
+ d0, d1, d2, d3 = delta
178
+ positive = sum(d for d in (d3, d2, d1, d0, d1, d2, d3) if d > 0)
179
+ negative = sum(-d for d in (d3, d2, d1, d0, d1, d2, d3) if d < 0)
180
+ return positive, negative, 255.0 * max(positive, negative) / SCALE
181
+
182
+
183
+ def exact_approximation() -> Approximation:
184
+ """Return the exact, sum-normalized integer Gaussian kernel.
185
+
186
+ :return: exact kernel with zero approximation error
187
+ :rtype: Approximation
188
+ """
189
+ weights = tuple(count_nnz(to_csd_i(a)) for a in EXACT_INDEPENDENT)
190
+ return Approximation(0.0, EXACT_INDEPENDENT, weights, 0, 0)
191
+
192
+
193
+ def search(target_lsb: float) -> Approximation | None:
194
+ """Find the minimum-NNZ kernel under a worst-case error target.
195
+
196
+ The search is exhaustive within ``+/-SEARCH_WINDOW`` of the exact kernel.
197
+
198
+ :param target_lsb: maximum pre-round error in output LSBs
199
+ :type target_lsb: float
200
+ :return: best approximation, or ``None`` if the search fails
201
+ :rtype: Approximation | None
202
+ """
203
+ best: Approximation | None = None
204
+ for a0 in range(
205
+ EXACT_INDEPENDENT[0] - SEARCH_WINDOW, EXACT_INDEPENDENT[0] + SEARCH_WINDOW + 1
206
+ ):
207
+ for a1 in range(
208
+ EXACT_INDEPENDENT[1] - SEARCH_WINDOW,
209
+ EXACT_INDEPENDENT[1] + SEARCH_WINDOW + 1,
210
+ ):
211
+ for a2 in range(
212
+ EXACT_INDEPENDENT[2] - SEARCH_WINDOW,
213
+ EXACT_INDEPENDENT[2] + SEARCH_WINDOW + 1,
214
+ ):
215
+ remainder = SCALE - a0 - 2 * a1 - 2 * a2
216
+ if remainder % 2:
217
+ continue
218
+ a3 = remainder // 2
219
+ if a3 <= 0 or abs(a3 - EXACT_INDEPENDENT[3]) > SEARCH_WINDOW:
220
+ continue
221
+ independent = (a0, a1, a2, a3)
222
+ positive, negative, error = worst_error_lsb(independent)
223
+ if error >= target_lsb:
224
+ continue
225
+ weights = tuple(count_nnz(to_csd_i(a)) for a in independent)
226
+ candidate = Approximation(
227
+ target_lsb, independent, weights, positive, negative
228
+ )
229
+ if best is None or (
230
+ candidate.total_nnz,
231
+ candidate.worst_error_lsb,
232
+ independent,
233
+ ) < (
234
+ best.total_nnz,
235
+ best.worst_error_lsb,
236
+ best.independent,
237
+ ):
238
+ best = candidate
239
+ return best
240
+
241
+
242
+ def multiplier_module(coefficient: int) -> str:
243
+ """Generate and rename one CSD multiplier module.
244
+
245
+ :param coefficient: positive integer coefficient
246
+ :type coefficient: int
247
+ :return: Verilog module named ``csd_mult_<coefficient>``
248
+ :rtype: str
249
+ """
250
+ csd = to_csd_i(coefficient)
251
+ module = generate_csd_multiplier(csd, INPUT_WIDTH, len(csd) - 1)
252
+ return module.replace("module csd_multiplier", f"module csd_mult_{coefficient}", 1)
253
+
254
+
255
+ def build_verilog(approx: Approximation) -> str:
256
+ """Build the symmetric 1D Gaussian filter and its multiplier modules.
257
+
258
+ :param approx: chosen kernel approximation
259
+ :type approx: Approximation
260
+ :return: Verilog source for four multipliers and the filter top
261
+ :rtype: str
262
+ """
263
+ a0, a1, a2, a3 = approx.independent
264
+ widths = {}
265
+ for coefficient in (a0, a1, a2, a3):
266
+ csd = to_csd_i(coefficient)
267
+ widths[coefficient] = INPUT_WIDTH + len(csd) - 1
268
+
269
+ multipliers = "\n".join(multiplier_module(a) for a in (a3, a2, a1, a0))
270
+ top = f"""
271
+ module gaussian_blur_1d (
272
+ input [7:0] x0, x1, x2, x3, x4, x5, x6,
273
+ output [7:0] y
274
+ );
275
+ wire signed [10:0] s3 = x0 + x6;
276
+ wire signed [10:0] s2 = x1 + x5;
277
+ wire signed [10:0] s1 = x2 + x4;
278
+ wire signed [10:0] s0 = x3;
279
+
280
+ wire signed [{widths[a3] - 1}:0] p3_raw;
281
+ wire signed [{widths[a2] - 1}:0] p2_raw;
282
+ wire signed [{widths[a1] - 1}:0] p1_raw;
283
+ wire signed [{widths[a0] - 1}:0] p0_raw;
284
+
285
+ csd_mult_{a3} m3 (.x(s3), .result(p3_raw));
286
+ csd_mult_{a2} m2 (.x(s2), .result(p2_raw));
287
+ csd_mult_{a1} m1 (.x(s1), .result(p1_raw));
288
+ csd_mult_{a0} m0 (.x(s0), .result(p0_raw));
289
+
290
+ wire signed [18:0] p3 = p3_raw;
291
+ wire signed [18:0] p2 = p2_raw;
292
+ wire signed [18:0] p1 = p1_raw;
293
+ wire signed [18:0] p0 = p0_raw;
294
+ wire signed [18:0] total = p3 + p2 + p1 + p0;
295
+ wire signed [18:0] rounded = (total + 19'sd512) >>> 10;
296
+
297
+ assign y = rounded[7:0];
298
+ endmodule
299
+ """
300
+ return multipliers + top
301
+
302
+
303
+ def expected_value(
304
+ kernel: tuple[int, int, int, int, int, int, int], pixels: tuple[int, ...]
305
+ ) -> int:
306
+ """Evaluate the integer convolution and round to the nearest output.
307
+
308
+ :param kernel: seven integer coefficients
309
+ :type kernel: tuple[int, int, int, int, int, int, int]
310
+ :param pixels: seven 8-bit input pixels
311
+ :type pixels: tuple[int, ...]
312
+ :return: 8-bit blurred output
313
+ :rtype: int
314
+ """
315
+ return (sum(k * p for k, p in zip(kernel, pixels)) + SCALE // 2) >> 10
316
+
317
+
318
+ def test_vectors() -> list[tuple[int, ...]]:
319
+ """Return edge cases and deterministic random 8-bit vectors.
320
+
321
+ :return: seven-pixel input vectors
322
+ :rtype: list[tuple[int, ...]]
323
+ """
324
+ vectors = [
325
+ (0, 0, 0, 0, 0, 0, 0),
326
+ (255, 255, 255, 255, 255, 255, 255),
327
+ (128, 128, 128, 128, 128, 128, 128),
328
+ (0, 255, 0, 255, 0, 255, 0),
329
+ (255, 0, 255, 0, 255, 0, 255),
330
+ (0, 0, 0, 255, 0, 0, 0),
331
+ (0, 0, 255, 0, 255, 0, 0),
332
+ (255, 0, 0, 0, 0, 0, 255),
333
+ ]
334
+ rng = random.Random(42)
335
+ vectors.extend(tuple(rng.randrange(256) for _ in range(7)) for _ in range(24))
336
+ return vectors
337
+
338
+
339
+ def build_testbench(approx: Approximation) -> str:
340
+ """Build a self-checking testbench for the 1D filter.
341
+
342
+ The expected values use the approximate CSD kernel, so the testbench
343
+ verifies the RTL implementation rather than the kernel approximation.
344
+
345
+ :param approx: chosen kernel approximation
346
+ :type approx: Approximation
347
+ :return: Verilog testbench source
348
+ :rtype: str
349
+ """
350
+ kernel = approx.full_kernel
351
+ checks = []
352
+ for pixels in test_vectors():
353
+ checks.append(
354
+ " check(8'd{p0}, 8'd{p1}, 8'd{p2}, 8'd{p3}, "
355
+ "8'd{p4}, 8'd{p5}, 8'd{p6}, 8'd{expected});".format(
356
+ p0=pixels[0],
357
+ p1=pixels[1],
358
+ p2=pixels[2],
359
+ p3=pixels[3],
360
+ p4=pixels[4],
361
+ p5=pixels[5],
362
+ p6=pixels[6],
363
+ expected=expected_value(kernel, pixels),
364
+ )
365
+ )
366
+ return f"""
367
+ module tb;
368
+ reg [7:0] x0, x1, x2, x3, x4, x5, x6;
369
+ wire [7:0] y;
370
+
371
+ gaussian_blur_1d dut (
372
+ .x0(x0), .x1(x1), .x2(x2), .x3(x3),
373
+ .x4(x4), .x5(x5), .x6(x6), .y(y)
374
+ );
375
+
376
+ task check;
377
+ input [7:0] v0, v1, v2, v3, v4, v5, v6;
378
+ input [7:0] expected;
379
+ begin
380
+ x0 = v0; x1 = v1; x2 = v2; x3 = v3;
381
+ x4 = v4; x5 = v5; x6 = v6;
382
+ #1;
383
+ if (y !== expected) begin
384
+ $display("MISMATCH x=%0d,%0d,%0d,%0d,%0d,%0d,%0d y=%0d expected=%0d",
385
+ v0, v1, v2, v3, v4, v5, v6, y, expected);
386
+ $fatal(1, "Gaussian blur RTL mismatch");
387
+ end
388
+ end
389
+ endtask
390
+
391
+ initial begin
392
+ {chr(10).join(checks)}
393
+ $display("PASS: all {len(checks)} vectors match the CSD kernel");
394
+ $finish;
395
+ end
396
+ endmodule
397
+ """
398
+
399
+
400
+ def simulate(dut: Path, testbench: Path) -> bool:
401
+ """Compile and run the testbench when Icarus Verilog is installed.
402
+
403
+ :param dut: path to the generated design
404
+ :type dut: Path
405
+ :param testbench: path to the generated testbench
406
+ :type testbench: Path
407
+ :return: ``True`` if the simulation passed or could not be run
408
+ :rtype: bool
409
+ """
410
+ iverilog = shutil.which("iverilog")
411
+ vvp = shutil.which("vvp")
412
+ if iverilog is None or vvp is None:
413
+ print("iverilog/vvp not found - generated Verilog was not simulated.")
414
+ return True
415
+ with tempfile.TemporaryDirectory() as tmp:
416
+ binary = Path(tmp) / "sim.out"
417
+ subprocess.run(
418
+ [
419
+ iverilog,
420
+ "-g2012",
421
+ "-s",
422
+ "tb",
423
+ "-o",
424
+ str(binary),
425
+ str(dut),
426
+ str(testbench),
427
+ ],
428
+ check=True,
429
+ )
430
+ return subprocess.run([vvp, str(binary)], check=False).returncode == 0
431
+
432
+
433
+ def print_analysis() -> None:
434
+ """Print the kernel, NNZ, and adder analysis for the demo."""
435
+ exact = exact_approximation()
436
+ one_lsb = search(1.0)
437
+ half_lsb = search(0.5)
438
+ assert one_lsb is not None and half_lsb is not None
439
+
440
+ print("7-tap Gaussian blur: sigma=2.0, scale=1024, 8-bit pixels")
441
+ print(f"search window: +/-{SEARCH_WINDOW} coefficients around the exact kernel")
442
+ print(
443
+ f"exact kernel: {full_kernel(EXACT_INDEPENDENT)} (sum={sum(full_kernel(EXACT_INDEPENDENT))})"
444
+ )
445
+ print(
446
+ f"exact full CSD weights: {tuple(count_nnz(to_csd_i(a)) for a in full_kernel(EXACT_INDEPENDENT))}"
447
+ )
448
+ print()
449
+ print(
450
+ "target coefficients (center first) weights NNZ pre-round err adders 1D/2D direct 1D/2D"
451
+ )
452
+ print(
453
+ "---------+------------------------------+--------------+----+------------+-----------+-------------"
454
+ )
455
+ for label, approx in (
456
+ ("exact", exact),
457
+ ("<=1 LSB", one_lsb),
458
+ ("<0.5 LSB", half_lsb),
459
+ ):
460
+ coeffs = approx.independent
461
+ weights = approx.weights
462
+ print(
463
+ f"{label:<8} | {str(coeffs):<28} | {str(weights):<12} | "
464
+ f"{approx.total_nnz:>2} | {approx.worst_error_lsb:>10.6f} | "
465
+ f"{approx.one_dimensional_adders:>3}/{approx.two_dimensional_adders:<3} "
466
+ f"| {approx.total_nnz:>3}/{2 * approx.total_nnz:<3}"
467
+ )
468
+ print()
469
+ print(
470
+ "The direct column is the non-symmetric form: coefficient adders + 6 product adds + 1 round."
471
+ )
472
+ print("The 2D counts exclude line-buffer registers.")
473
+ exact_kernel = full_kernel(EXACT_INDEPENDENT)
474
+ observed = max(
475
+ abs(expected_value(half_lsb.full_kernel, p) - expected_value(exact_kernel, p))
476
+ for p in test_vectors()
477
+ )
478
+ print(
479
+ f"observed rounded difference vs exact Gaussian on test vectors: {observed} LSB"
480
+ )
481
+ print(
482
+ "The 0.498 LSB bound is pre-round; near a boundary the rounded result can differ by 1."
483
+ )
484
+ print()
485
+ print(
486
+ f"chosen RTL: target <0.5 LSB, coefficients {half_lsb.independent}, "
487
+ f"NNZ={half_lsb.total_nnz}, error={half_lsb.worst_error_lsb:.6f} LSB"
488
+ )
489
+
490
+
491
+ def main() -> int:
492
+ """Run the Gaussian-blur demo.
493
+
494
+ :return: process exit code
495
+ :rtype: int
496
+ """
497
+ print_analysis()
498
+ half_lsb = search(0.5)
499
+ assert half_lsb is not None
500
+ dut = Path(__file__).resolve().with_name("gaussian_blur_1d.v")
501
+ testbench = Path(__file__).resolve().with_name("gaussian_blur_1d_tb.v")
502
+ dut.write_text(build_verilog(half_lsb), encoding="utf-8")
503
+ testbench.write_text(build_testbench(half_lsb), encoding="utf-8")
504
+ print(f"wrote {dut.name} and {testbench.name}")
505
+ print(flush=True)
506
+ return 0 if simulate(dut, testbench) else 1
507
+
508
+
509
+ if __name__ == "__main__":
510
+ sys.exit(main())