#!/usr/bin/env python3
"""Write one I/Q file holding several pre-distortion settings in sequence.

The calibration needs to compare the leakage and image produced by
different correction coefficients. Doing that as separate transmissions
assumes the hardware's own impairment is identical in each one -- and
tx_test re-tunes on every run, which may re-run the chip's own transmit
DC calibration. So the probes go inside a single waveform, separated by
silence, exactly like gen_amp_steps.py: the analysis finds each segment
from the envelope, every probe is measured under one tuning, and a
dropped sample cannot pair a measurement with the wrong coefficients.

Segments carry the correction x + k*conj(x) + d; the gaps are true zero,
with no DC term, so the boundaries stay sharp.

  gen_probe_sweep.py <rate_hz> <offset_hz> <out.bin> <seg_s> <gap_s>
                     <amp> kr,ki,dr,di [kr,ki,dr,di ...] [--lead S]

--lead sets the leading silence separately from the inter-segment gaps
(it defaults to one gap). It matters when something *outside* the
waveform is being stepped in time with the segments, as tx_test's -S/-D
step its LO-leakage trim: that switch is triggered by samples pushed to
the driver, which run ahead of what is radiating by the buffer depth B,
so a code written at segment i's period boundary takes effect while file
position (i*period - B) is on the air. For it to land in the gap before
segment i rather than inside segment i-1, the waveform needs

    gap >= lead + B

which an equal lead and gap cannot satisfy. A short lead buys the margin.
"""
import sys

import numpy as np

argv = list(sys.argv)
lead_s = None
if "--lead" in argv:
    i = argv.index("--lead")
    lead_s = float(argv[i + 1])
    del argv[i:i + 2]

rate = float(argv[1])
offset = float(argv[2])
out_path = argv[3]
seg_s = float(argv[4])
gap_s = float(argv[5])
amp = float(argv[6])
probes = [[float(v) for v in a.split(",")] for a in argv[7:]]
if any(len(p) != 4 for p in probes):
    sys.exit("each probe needs four comma-separated values: kr,ki,dr,di")
if lead_s is None:
    lead_s = gap_s

n_seg = int(seg_s * rate)
n_gap = int(gap_s * rate)
n_lead = int(lead_s * rate)
n_edge = max(1, int(0.002 * rate))
ramp = 0.5 - 0.5 * np.cos(np.pi * np.arange(n_edge) / n_edge)

# One continuous phase ramp across the whole file, so the tone never
# steps in phase at a segment boundary.
total = n_lead + len(probes) * (n_seg + n_gap)
ph = 2.0 * np.pi * offset * np.arange(total, dtype=np.float64) / rate
carrier = np.exp(1j * ph)

y = np.zeros(total, dtype=np.complex128)
pos = n_lead
for kr, ki, dr, di in probes:
    env = np.ones(n_seg)
    env[:n_edge] = ramp
    env[n_seg - n_edge:] = ramp[::-1]
    x = amp * env * carrier[pos:pos + n_seg]
    y[pos:pos + n_seg] = x + complex(kr, ki) * np.conj(x) + complex(dr, di)
    pos += n_seg + n_gap

peak = np.max(np.abs(y))
if peak > 1.0:
    sys.exit("peak %.3f exceeds full scale -- lower amp or the probe step"
             % peak)

iq = np.empty(total * 2, dtype=np.int16)
iq[0::2] = np.clip(np.real(y) * 32767.0, -32768, 32767).astype(np.int16)
iq[1::2] = np.clip(np.imag(y) * 32767.0, -32768, 32767).astype(np.int16)
iq.tofile(out_path)

print("wrote %s: %.2f s, %d probes of %.2f s, lead %.2f s, gap %.2f s, "
      "peak %.3f, %.1f MB"
      % (out_path, total / rate, len(probes), seg_s, lead_s, gap_s, peak,
         iq.nbytes / 1e6))
print("period %.0f samples -- tx_test -D for a trim stepped in step"
      % (n_seg + n_gap))
print("probes: " + "  ".join("k=%+.4f%+.4fj d=%+.4f%+.4fj" % tuple(p)
                             for p in probes))
