"""Bit-exact Python model of dds.sv: phase accumulator plus quarter-wave sine LUT. Run standalone to (re)generate the LUT file used by dds.sv: python dds_model.py # writes dds_sine_quarter.hex next to this file """ from __future__ import annotations import math from pathlib import Path ACC_BITS = 32 # phase accumulator width N PHASE_BITS = 10 # phase bits kept after truncation P (2 quadrant bits + 8 LUT address bits) AMP = 32767 # peak amplitude of the 16-bit signed output HEX_FILE = Path(__file__).resolve().parent / "dds_sine_quarter.hex" def quarter_lut(addr_bits: int = PHASE_BITS - 2, amp: int = AMP) -> list[int]: """First quarter of a sine wave, sampled half a step off zero. Entry k holds round(amp * sin(2*pi*(k + 0.5) / 2**(addr_bits + 2))). The half-step offset makes the quarter exactly symmetric, so mirroring the address with a bitwise NOT gives the second quarter. """ full = 1 << (addr_bits + 2) return [round(amp * math.sin(2.0 * math.pi * (k + 0.5) / full)) for k in range(1 << addr_bits)] def phase_to_sample(phase: int, lut: list[int], phase_bits: int = PHASE_BITS) -> int: """Map a truncated phase (phase_bits wide) to a signed sample, as dds.sv does.""" addr_bits = phase_bits - 2 quadrant = phase >> addr_bits addr = phase & ((1 << addr_bits) - 1) if quadrant & 1: # second and fourth quarter: mirror the address addr = (~addr) & ((1 << addr_bits) - 1) value = lut[addr] return -value if quadrant & 2 else value # third and fourth quarter: negate def dds_samples(tuning_word: int, n: int, acc_bits: int = ACC_BITS, phase_bits: int = PHASE_BITS, phase0: int = 0) -> list[int]: """n output samples. Sample i uses the accumulator value phase0 + i * tuning_word.""" lut = quarter_lut(phase_bits - 2) mask = (1 << acc_bits) - 1 out = [] acc = phase0 & mask for _ in range(n): out.append(phase_to_sample(acc >> (acc_bits - phase_bits), lut, phase_bits)) acc = (acc + tuning_word) & mask return out def tuning_word(f_out: float, f_clk: float, acc_bits: int = ACC_BITS) -> int: """Nearest tuning word M for f_out = M * f_clk / 2**acc_bits.""" return round(f_out * (1 << acc_bits) / f_clk) def output_frequency(m: int, f_clk: float, acc_bits: int = ACC_BITS) -> float: return m * f_clk / (1 << acc_bits) def write_hex(path: Path = HEX_FILE) -> None: words = [f"{v & 0xFFFF:04X}" for v in quarter_lut()] path.write_text("\n".join(words) + "\n") if __name__ == "__main__": write_hex() print(f"wrote {HEX_FILE.name}: {len(quarter_lut())} words")