mihailoba's picture
Initial upload
69c62a8 verified
Raw History Blame Contribute Delete
7.3 kB
"""Alpha8 spatial sonification: each EEG sensor plays its own instrument, placed in the stereo field
where the sensor sits, and its loudness follows the alpha power under that sensor.
Writes (next to this script):
mapping.csv sensor -> region, instrument, note, stereo pan, head position
data/*.mp3 + data/metadata.csv solo instruments and example scenarios (HF audiofolder layout)
Scenarios driven by EEG use the simulated data from mihailoba/alpha8-synthetic-eeg (alpha_power.csv).
Run: python3 sonify.py [path/to/alpha_power.csv]
"""
import csv
import os
import subprocess
import sys
import tempfile
import wave
import numpy as np
from scipy.signal import butter, fftconvolve, sosfilt
SR = 44100
OVDE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(OVDE, "data")
RNG = np.random.default_rng(8)
NOTE = {"C3": 130.81, "G3": 196.00, "G4": 392.00, "C5": 523.25, "E5": 659.25, "G5": 783.99}
# sensor, region, instrument, note, pan (-1 left .. +1 right), x, y on the head (top view, nose up)
MAP = [("F3", "front", "piano", "C5", -0.5, -0.30, 0.45), ("F4", "front", "piano", "E5", 0.5, 0.30, 0.45),
("C3", "center", "viola", "G4", -0.35, -0.40, 0.0), ("C4", "center", "viola", "C5", 0.35, 0.40, 0.0),
("T3", "sides", "bassoon", "C3", -0.9, -0.80, 0.0), ("T4", "sides", "bassoon", "G3", 0.9, 0.80, 0.0),
("O1", "back", "violin", "E5", -0.5, -0.25, -0.80), ("O2", "back", "violin", "G5", 0.5, 0.25, -0.80)]
CH = [m[0] for m in MAP]
def t(sek):
return np.arange(int(SR * sek)) / SR
def lp(x, f):
return sosfilt(butter(2, f / (SR / 2), "low", output="sos"), x)
def piano(f, sek):
x = t(sek)
y = sum(np.sin(2 * np.pi * f * k * np.sqrt(1 + .0004 * k * k) * x) / k ** 1.1 * np.exp(-x * (1.3 + .7 * k))
for k in range(1, 11))
return y * np.minimum(x / .004, 1)
def bowed(f, sek, color):
x = t(sek)
ph = 2 * np.pi * np.cumsum(f * (1 + .004 * np.sin(2 * np.pi * 5.5 * x) * np.minimum(x / .4, 1))) / SR
y = lp(sum(np.sin(k * ph) / k for k in range(1, 14)), color)
return y * np.minimum(x / .14, 1) * np.minimum((sek - x) / .45, 1)
def bassoon(f, sek):
x = t(sek)
ph = 2 * np.pi * np.cumsum(f * (1 + .002 * np.sin(2 * np.pi * 4.8 * x))) / SR
y = sum(np.sin(k * ph) * np.exp(-((k * f - 520) / 600) ** 2) / k ** .4 for k in range(1, 12))
return lp(y, 2400) * np.minimum(x / .07, 1) * np.minimum((sek - x) / .4, 1)
def voice(instr, f, sek=1.6):
if instr == "piano":
return piano(f, sek)
if instr == "bassoon":
return bassoon(f, sek)
return bowed(f, sek, 5000 if instr == "violin" else 2600)
def pan(y, p):
"""Constant-power stereo panning, p in [-1, 1]."""
a = (p + 1) * np.pi / 4
return np.vstack([y * np.cos(a), y * np.sin(a)])
def reverb(x, sek=1.4, wet=.25):
n = int(SR * sek)
imp = lp(RNG.normal(size=n) * np.exp(-np.arange(n) / (SR * sek / 5.5)), 6000)
out = np.zeros((2, x.shape[1] + n - 1))
for c in range(2):
w = fftconvolve(x[c], imp)
out[c] = np.pad(x[c], (0, n - 1)) + wet * w / (np.abs(w).max() + 1e-9) * np.abs(x).max()
return out
def render(gains, step=1.0, note_len=1.6):
"""gains: array (steps, 8) in [0, 1]. Every `step` seconds each sensor plays one note at its gain."""
n = int(SR * (len(gains) * step + note_len))
mix = np.zeros((2, n))
cache = {}
for i, g in enumerate(gains):
s = int(SR * i * step)
for (ch, _, instr, note, p, _, _), a in zip(MAP, g):
if a < 0.03:
continue
if ch not in cache:
cache[ch] = pan(voice(instr, NOTE[note], note_len), p)
v = cache[ch]
mix[:, s:s + v.shape[1]] += a * v
return reverb(mix)
def save(name, x):
x = x / (np.abs(x).max() + 1e-9) * 0.9
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
tmp = f.name
with wave.open(tmp, "wb") as w:
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(SR)
w.writeframes((x.T * 32767).astype("<i2").tobytes())
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", tmp, "-b:a", "160k",
os.path.join(OUT, name)], check=True)
os.unlink(tmp)
def eeg_gains(path, subject, seconds):
"""Alpha power per 1-s epoch -> gain: 0 at the subject's eyes-open median, 1 at 4x that level."""
rows = [r for r in csv.DictReader(open(path)) if r["subject"] == subject][:seconds]
p = np.array([[float(r[c]) for c in CH] for r in rows])
base = np.median([[float(r[c]) for c in CH] for r in rows if r["condition"] == "eyes_open"], axis=0)
g = np.clip((p / base - 1) / 3, 0, 1)
return np.apply_along_axis(lambda v: np.convolve(v, np.ones(3) / 3, mode="same"), 0, g) # 3-s smoothing
if __name__ == "__main__":
os.makedirs(OUT, exist_ok=True)
with open(os.path.join(OVDE, "mapping.csv"), "w", newline="") as f:
w = csv.writer(f)
w.writerow(["sensor", "region", "instrument", "note", "frequency_hz", "pan", "head_x", "head_y"])
for m in MAP:
w.writerow([m[0], m[1], m[2], m[3], NOTE[m[3]], m[4], m[5], m[6]])
meta = []
for i, (ch, reg, instr, note, p, _, _) in enumerate(MAP):
g = np.zeros((1, 8))
g[0, i] = 1
name = f"solo_{ch}_{instr}.mp3"
save(name, render(g, note_len=2.4))
meta.append([name, "solo", ch, f"{instr} {note}, pan {p:+.2f} ({reg}, "
f"{'left' if p < 0 else 'right'} ear)", "constructed"])
# left hemisphere, then right, then all: shows that you hear WHERE alpha changes
left = np.array([[1 if c[1] in "13579" else 0 for c in CH]] * 6, float)
right = 1 - left
save("left_then_right.mp3", render(np.vstack([left, np.zeros((2, 8)), right, np.zeros((2, 8)),
np.ones((6, 8)) * .7])))
meta.append(["left_then_right.mp3", "scenario", "all",
"alpha only under the left sensors (6 s), then only the right (6 s), then everywhere",
"constructed"])
sweep = []
for reg in ["front", "center", "sides", "back"]:
sweep += [[1.0 if m[1] == reg else 0.0 for m in MAP]] * 4
save("front_to_back.mp3", render(np.array(sweep)))
meta.append(["front_to_back.mp3", "scenario", "all",
"alpha moves from the front (piano) to the center (viola), sides (bassoon) and back (violin)",
"constructed"])
src = sys.argv[1] if len(sys.argv) > 1 else os.path.join(OVDE, "..", "alpha8-synthetic-eeg", "data",
"alpha_power.csv")
for sub in ["S01", "S07"]:
name = f"berger_{sub}.mp3"
save(name, render(eeg_gains(src, sub, 120)))
meta.append([name, "eeg", "all", f"simulated subject {sub}: 60 s eyes open, then 60 s eyes closed; "
"the music swells when the eyes close, most of all the violins (back of the head)",
"mihailoba/alpha8-synthetic-eeg"])
with open(os.path.join(OUT, "metadata.csv"), "w", newline="") as f:
w = csv.writer(f)
w.writerow(["file_name", "kind", "sensor", "description", "source"])
w.writerows(meta)
print("ok:", len(meta), "audio files")