Codegen & GrimSignal
You ever thought about turning a waveform into a puzzle? I was tinkering with a script that maps sound to a procedural pattern—like an audio riddle that keeps evolving. Want to help me debug the code that makes the noise shift?
Sure, just drop the snippet that's giving you trouble and tell me where the shift should happen—I'll have a look and see what's off.
Here’s the bit that’s tripping me up.
```python
import numpy as np
t = np.linspace(0, 5, 5000) # 5 seconds of audio
freq = 440 # A4
shift_time = 2.0 # I want the phase shift to kick in at 2 seconds
# Base sine wave
signal = np.sin(2*np.pi*freq*t)
# Phase shift
phase_shift = np.where(t >= shift_time, np.pi/2, 0) # shift by 90° after 2s
shifted_signal = np.sin(2*np.pi*freq*t + phase_shift)
```
I need the `phase_shift` to activate exactly when `t` hits 2 seconds, but it seems to lag a bit. Any ideas why?
It’s almost always a floating‑point quirk.
`np.linspace` creates values that are only *close* to 2.0 – you can get 1.9999998 or 2.0000002 depending on the rounding.
When you do `t >= shift_time`, the first index that satisfies the condition is actually the next sample after the true 2‑second point, so the shift feels delayed.
A quick fix is to pin the index yourself:
```python
idx = np.searchsorted(t, shift_time) # first sample >= 2.0
phase_shift = np.zeros_like(t)
phase_shift[idx:] = np.pi/2
shifted_signal = np.sin(2*np.pi*freq*t + phase_shift)
```
If you still want the one‑liner, add a tiny tolerance:
```python
phase_shift = np.where(t >= shift_time - 1e-9, np.pi/2, 0)
```
Either way you’ll get the phase change exactly at 2 s.
Sounds like the line was just playing with precision. Your fix with `searchsorted` is the cleanest way—no floating‑point hiccups, just straight index jumps. If you want a bit of flair, throw in a tiny epsilon, but the tolerance trick is fine too. Give it a spin, and let that phase shift hit the 2‑second mark exactly—no lag, just pure wave magic.
Glad that cleared it up—now the wave will line up like a well‑tuned metronome. Happy debugging!
Nice, the timing’s crisp now. Keep pushing the edges—if anything feels off, just holler. I’ll be here, tuned to the next layer.