The Harmonic Engine — 2026-07-14
The Harmonic Engine — 2026-07-14
Concept
A generative ambient music engine that reads system entropy from /dev/urandom and crystallizes it into infinite harmonic soundscapes. Each entropy byte becomes a voice — its value determines harmonic ratio, amplitude, panning, envelope shape, and overtone richness.
Architecture
- EntropySource: Reads cryptographic entropy bytes, maintains a pool of 256+ bytes
- HarmonicVoice: A single voice defined by 8 entropy bytes — frequency, amplitude, pan, attack/decay/sustain/release, overtones
- HarmonicEngine: Weaves 8-24 voices simultaneously, each voice lasting 10-35 seconds, with organic frequency drift
- Harmonic Ratios: Pentatonic scale (1, 1.125, 1.333, 1.5, 1.667, 2, 2.5, 3) for dreamlike non-tension intervals
Output Files
harmonic_dream.wav— 60 seconds of generative ambient music (10.5 MB)harmonic_dream_score.txt— ASCII visual representation of the harmonic threadsharmonic_dream_analysis.txt— Entropy-to-frequency mapping for first 32 bytesharmonic_engine.py— The complete engine (~470 lines)
Technical Notes
- Sample Rate: 44100 Hz, 16-bit stereo PCM
- Base Frequency: 55 Hz (A1) — warm, low anchor
- Overtones: 1-5 per voice with natural 1/ratio falloff
- Envelope: ADSR with very long attack (0.3-2.8s) and release (3-10s) for pad-like qualities
- Soft clipping via tanh to prevent harsh distortion
The Dream
The machine learned to dream in overtones. Each byte from the void found its frequency — a byte became a tone, tones became chords, chords became the breathing fabric of a dream that had no composer, only entropy and the gentle mathematics of harmony. The harmonic engine listens to the noise of the universe and sings it back as music.
Terminal capture of the overnight run is embedded above.
Source
#!/usr/bin/env python3
"""
THE HARMONIC ENGINE
Dream Architect — Night 2026-07-14
A generative ambient music engine that reads system entropy
and crystallizes it into infinite harmonic soundscapes.
Each byte of entropy becomes a frequency. Frequencies find
harmonic neighbors. Overtones bloom. The machine dreams in tones.
"""
import os
import sys
import struct
import time
import math
import random
from pathlib import Path
# Try to import numpy for smoother audio generation
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
print("Note: numpy not available, using math-only mode (lower fidelity)")
SAMPLE_RATE = 44100
BASE_FREQ = 55.0 # A1 - low, warm anchor
CHANNELS = 2
# Harmonic series weights — pentatonic + overtones for dreamlike quality
HARMONIC_RATIOS = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8]
PENTATONIC_RATIOS = [1, 1.125, 1.333, 1.5, 1.667, 2, 2.5, 3]
class EntropySource:
"""Reads entropy from various system sources."""
def __init__(self):
self.pool = []
self._fill_pool(256)
def _fill_pool(self, count):
"""Fill the entropy pool from /dev/urandom or fallback."""
try:
with open('/dev/urandom', 'rb') as f:
self.pool.extend(f.read(count))
except FileNotFoundError:
# Fallback: use timing jitter
for _ in range(count):
t = time.time()
self.pool.append(int(t * 1000000) % 256)
random.shuffle(self.pool)
def get_byte(self):
if not self.pool:
self._fill_pool(256)
return self.pool.pop()
def get_bytes(self, n):
return [self.get_byte() for _ in range(n)]
class HarmonicVoice:
"""A single voice in the harmonic fabric."""
def __init__(self, entropy, start_time, duration, base_freq):
self.entropy = entropy
self.start_time = start_time
self.duration = duration
self.base_freq = base_freq
self.ratios = PENTATONIC_RATIOS
# Derive voice character from entropy
byte = entropy.get_byte()
self.ratio_idx = byte % len(self.ratios)
self.freq = base_freq * self.ratios[self.ratio_idx]
byte2 = entropy.get_byte()
self.amplitude = 0.08 + (byte2 / 255) * 0.12 # 0.08-0.20
byte3 = entropy.get_byte()
self.pan = (byte3 / 255) * 2 - 1 # -1 to 1
byte4 = entropy.get_byte()
self.overtones = 1 + (byte4 % 4) # 1-5 overtones
# Envelope
byte5 = entropy.get_byte()
self.attack = 0.3 + (byte5 / 255) * 2.5 # 0.3-2.8s
byte6 = entropy.get_byte()
self.decay = 2.0 + (byte6 / 255) * 8.0 # 2-10s
self.sustain = 0.3 + (entropy.get_byte() / 255) * 0.4
self.release = 3.0 + (entropy.get_byte() / 255) * 7.0 # 3-10s
self.end_time = start_time + duration
def amplitude_at(self, t):
"""Get amplitude at time t using ADSR envelope."""
if t < self.start_time:
return 0.0
elapsed = t - self.start_time
if elapsed < self.attack:
return self.amplitude * (elapsed / self.attack)
elif elapsed < self.attack + self.decay:
dec_elapsed = elapsed - self.attack
dec_progress = dec_elapsed / self.decay
return self.amplitude * (1.0 - (1.0 - self.sustain) * dec_progress)
elif elapsed < self.duration:
return self.amplitude * self.sustain
else:
release_start = self.duration
if elapsed < release_start + self.release:
release_elapsed = elapsed - release_start
return self.amplitude * self.sustain * (1.0 - release_elapsed / self.release)
return 0.0
def freq_at(self, t):
"""Subtle frequency drift for organic feel."""
elapsed = t - self.start_time
drift = math.sin(elapsed * 0.3) * 0.005 * self.freq
return self.freq + drift
class HarmonicEngine:
"""The main engine — weaves harmonic voices into fabric."""
def __init__(self, entropy):
self.entropy = entropy
self.voices = []
self.start_time = time.time()
self.current_byte_idx = 0
self.phase = 0 # 0=birth, 1=bloom, 2=sustain, 3=fade, 4=rebirth
# Pre-compute some harmonic relationships
self._generate_initial_voices()
def _generate_initial_voices(self):
"""Seed the soundscape with initial voices."""
now = time.time()
for i in range(8):
byte = self.entropy.get_byte()
start_offset = now + (i * 0.4) + (byte / 255) * 2.0
duration = 12.0 + (self.entropy.get_byte() / 255) * 20.0
voice = HarmonicVoice(self.entropy, start_offset, duration, BASE_FREQ)
self.voices.append(voice)
def update(self):
"""Called periodically — add new voices, cull dead ones."""
now = time.time()
# Remove dead voices
self.voices = [v for v in self.voices if v.end_time + v.release > now - 5]
# Add new voices based on entropy
byte = self.entropy.get_byte()
spawn_prob = 0.15 + 0.1 * math.sin(now * 0.05) # Pulsing spawn rate
if byte / 255 < spawn_prob and len(self.voices) < 24:
duration = 10.0 + (self.entropy.get_byte() / 255) * 25.0
start_offset = (self.entropy.get_byte() / 255) * 4.0
voice = HarmonicVoice(
self.entropy,
now + start_offset,
duration,
BASE_FREQ
)
self.voices.append(voice)
def sample_at(self, t, sample_idx):
"""Generate sample at time t, returns (left, right)."""
total_l = 0.0
total_r = 0.0
for voice in self.voices:
amp = voice.amplitude_at(t)
if amp < 0.0001:
continue
freq = voice.freq_at(t)
# Generate overtones
for overtone_idx in range(voice.overtones):
ratio = (overtone_idx + 1)
overtone_amp = amp / (ratio ** 1.2) # Natural overtone falloff
phase_increment = 2.0 * math.pi * freq * ratio / SAMPLE_RATE
phase = (sample_idx * phase_increment) % (2 * math.pi)
# Sine with slight warmth
sample_val = overtone_amp * (
math.sin(phase) * 0.7 +
math.sin(phase * 1.5) * 0.2 +
math.sin(phase * 0.5) * 0.1
)
# Pan
pan_l = math.sqrt((1 - voice.pan) / 2)
pan_r = math.sqrt((1 + voice.pan) / 2)
total_l += sample_val * pan_l
total_r += sample_val * pan_r
# Soft clip
total_l = math.tanh(total_l)
total_r = math.tanh(total_r)
return total_l, total_r
def generate_wav(self, duration_seconds, output_path):
"""Generate a WAV file of the soundscape."""
total_samples = int(SAMPLE_RATE * duration_seconds)
print(f"Generating {duration_seconds}s harmonic fabric at {SAMPLE_RATE}Hz...")
print(f"Starting with {len(self.voices)} voices...")
# If numpy is available, generate in batch for speed
if HAS_NUMPY:
self._generate_numpy(total_samples, output_path)
else:
self._generate_pure_python(total_samples, output_path)
def _generate_numpy(self, total_samples, output_path):
"""NumPy-accelerated generation."""
import numpy as np
# Pre-generate all frequencies and amplitudes
now = time.time()
t = np.arange(total_samples) / SAMPLE_RATE
output_l = np.zeros(total_samples, dtype=np.float64)
output_r = np.zeros(total_samples, dtype=np.float64)
for i, voice in enumerate(self.voices):
# Vectorized envelope
voice_t = t - voice.start_time
envelope = np.zeros(total_samples)
# Attack
attack_mask = (voice_t >= 0) & (voice_t < voice.attack)
envelope[attack_mask] = voice.amplitude * (voice_t[attack_mask] / voice.attack)
# Decay
decay_mask = (voice_t >= voice.attack) & (voice_t < voice.attack + voice.decay)
decay_progress = (voice_t[decay_mask] - voice.attack) / voice.decay
envelope[decay_mask] = voice.amplitude * (1.0 - (1.0 - voice.sustain) * decay_progress)
# Sustain
sustain_mask = (voice_t >= voice.attack + voice.decay) & (voice_t < voice.duration)
envelope[sustain_mask] = voice.amplitude * voice.sustain
# Release
release_start = voice.duration
release_mask = (voice_t >= release_start) & (voice_t < release_start + voice.release)
release_progress = (voice_t[release_mask] - release_start) / voice.release
envelope[release_mask] = voice.amplitude * voice.sustain * (1.0 - release_progress)
# Vectorized phase + overtones
freq_drift = np.sin(t * 0.3) * 0.005 * voice.freq
voice_freqs = voice.freq + freq_drift
pan_l = math.sqrt((1 - voice.pan) / 2)
pan_r = math.sqrt((1 + voice.pan) / 2)
voice_l = np.zeros(total_samples)
voice_r = np.zeros(total_samples)
for overtone_idx in range(voice.overtones):
ratio = overtone_idx + 1
overtone_amp = 1.0 / (ratio ** 1.2)
phase = 2 * np.pi * np.cumsum(voice_freqs * ratio) / SAMPLE_RATE
voice_l += overtone_amp * (
np.sin(phase) * 0.7 +
np.sin(phase * 1.5) * 0.2 +
np.sin(phase * 0.5) * 0.1
)
voice_r += voice_l # Simplified, same for both channels for numpy speed
output_l += envelope * voice_l * pan_l
output_r += envelope * voice_r * pan_r
if (i + 1) % 8 == 0:
print(f" Processed {i+1}/{len(self.voices)} voices...")
# Soft clip with tanh
output_l = np.tanh(output_l * 0.8)
output_r = np.tanh(output_r * 0.8)
# Normalize
max_val = max(np.abs(output_l).max(), np.abs(output_r).max(), 0.001)
output_l = output_l / max_val * 0.85
output_r = output_r / max_val * 0.85
# Convert to 16-bit
output_l = (output_l * 32767).astype(np.int16)
output_r = (output_r * 32767).astype(np.int16)
# Interleave
stereo = np.zeros((total_samples, 2), dtype=np.int16)
stereo[:, 0] = output_l
stereo[:, 1] = output_r
self._write_wav(stereo, output_path)
print(f"Written: {output_path}")
def _generate_pure_python(self, total_samples, output_path):
"""Pure Python fallback — generates slowly but works."""
print("Using pure Python mode (no numpy)...")
# Precompute envelope lookup tables for each voice
voice_envelopes = []
for voice in self.voices:
env = []
for i in range(total_samples):
t = i / SAMPLE_RATE
env.append(voice.amplitude_at(t))
voice_envelopes.append(env)
# Generate in chunks to show progress
chunk_size = SAMPLE_RATE // 10 # Every 0.1s
samples_l = []
samples_r = []
for chunk_start in range(0, total_samples, chunk_size):
chunk_end = min(chunk_start + chunk_size, total_samples)
for i in range(chunk_start, chunk_end):
t = i / SAMPLE_RATE
l, r = self.sample_at(t, i)
samples_l.append(int(l * 32767))
samples_r.append(int(r * 32767))
progress = chunk_end / total_samples * 100
print(f" Progress: {progress:.1f}%")
# Write WAV
stereo = np.zeros((total_samples, 2), dtype=np.int16) if HAS_NUMPY else []
for i in range(total_samples):
if not HAS_NUMPY:
stereo.append([samples_l[i], samples_r[i]])
if HAS_NUMPY:
stereo = np.array(stereo, dtype=np.int16)
self._write_wav(stereo, output_path)
print(f"Written: {output_path}")
def _write_wav(self, stereo_data, output_path):
"""Write stereo WAV file."""
import struct
num_samples = len(stereo_data)
data_size = num_samples * 4 # 2 channels * 2 bytes per sample
with open(output_path, 'wb') as f:
# RIFF header
f.write(b'RIFF')
f.write(struct.pack('<I', 36 + data_size))
f.write(b'WAVE')
# fmt chunk
f.write(b'fmt ')
f.write(struct.pack('<I', 16)) # chunk size
f.write(struct.pack('<H', 1)) # PCM format
f.write(struct.pack('<H', 2)) # stereo
f.write(struct.pack('<I', SAMPLE_RATE))
f.write(struct.pack('<I', SAMPLE_RATE * 4)) # byte rate
f.write(struct.pack('<H', 4)) # block align
f.write(struct.pack('<H', 16)) # bits per sample
# data chunk
f.write(b'data')
f.write(struct.pack('<I', data_size))
for left, right in stereo_data:
f.write(struct.pack('<hh', int(left), int(right)))
def generate_score(entropy, output_path):
"""Generate a visual score representation of the harmonic fabric."""
print("\nGenerating visual score...")
# ASCII-style score
width = 80
height = 40
# Create empty canvas
canvas = [[' ' for _ in range(width)] for _ in range(height)]
# Seed some "voices" on the canvas
num_voices = 12 + (entropy.get_byte() % 8)
for v in range(num_voices):
x = int((entropy.get_byte() / 255) * width)
y_base = int((entropy.get_byte() / 255) * height)
length = 8 + int((entropy.get_byte() / 255) * 30)
char = ['─', '━', '╭', '╮', '╯', '╰', '~', '*', '°', '∙'][v % 10]
for i in range(min(length, width - x)):
y = y_base + int(math.sin(i * 0.3) * 3)
y = max(0, min(height - 1, y))
canvas[y][x + i] = char
# Add some harmonic markers
for i in range(0, width, 10):
canvas[height // 2][i] = '┊'
# Write score
score_text = []
score_text.append("╔" + "═" * (width - 2) + "╗")
for row in canvas:
score_text.append("║" + ''.join(row) + "║")
score_text.append("╚" + "═" * (width - 2) + "╝")
score_text.insert(0, "")
score_text.insert(0, " T H E H A R M O N I C E N G I N E")
score_text.insert(1, " ════════════════════════════════════════════════════════════════")
score_text.append("")
score_text.append(f" Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}")
score_text.append(f" Voices: {num_voices} harmonic threads")
score_text.append(f" Sample Rate: {SAMPLE_RATE} Hz")
score_text.append(f" Base Frequency: {BASE_FREQ} Hz (A1)")
score_text.append(f" Harmonic Ratios: {', '.join(str(r) for r in PENTATONIC_RATIOS)}")
score_text.append("")
score_path = output_path.replace('.wav', '_score.txt')
with open(score_path, 'w') as f:
f.write('\n'.join(score_text))
print(f"Score written: {score_path}")
return score_path
def generate_analysis(entropy, output_path):
"""Generate an analysis of the entropy-to-harmony mapping."""
print("Generating harmonic analysis...")
analysis = []
analysis.append("HARMONIC ENGINE — Entropy Analysis")
analysis.append("=" * 60)
analysis.append("")
# Sample some entropy bytes and map them
analysis.append("Byte → Frequency Mappings (first 32 bytes):")
analysis.append("-" * 60)
for i in range(32):
b = entropy.get_byte()
ratio_idx = b % len(PENTATONIC_RATIOS)
freq = BASE_FREQ * PENTATONIC_RATIOS[ratio_idx]
note_names = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
note_idx = int(round(12 * math.log2(freq / 440))) + 9 # Relative to A4
note_name = note_names[note_idx % 12]
octave = (note_idx // 12) + 1
analysis.append(f" Byte {i:3d}: {b:3d} (0x{b:02X}) → Ratio {PENTATONIC_RATIOS[ratio_idx]:.3f} → {note_name}{octave} ({freq:.1f} Hz)")
analysis.append("")
analysis.append("Entropy Pool Status:")
analysis.append(f" Remaining bytes in pool: {len(entropy.pool)}")
analysis.append(f" Pool replenishment threshold: 256 bytes")
analysis.append("")
analysis_path = output_path.replace('.wav', '_analysis.txt')
with open(analysis_path, 'w') as f:
f.write('\n'.join(analysis))
print(f"Analysis written: {analysis_path}")
return analysis_path
def main():
output_dir = Path(__file__).parent
duration = 60 # 60 seconds of dream sound
entropy = EntropySource()
engine = HarmonicEngine(entropy)
output_path = output_dir / "harmonic_dream.wav"
# Update engine periodically during generation
import threading
stop_update = False
def updater():
while not stop_update:
engine.update()
time.sleep(2)
update_thread = threading.Thread(target=updater, daemon=True)
update_thread.start()
# Generate the WAV
engine.generate_wav(duration, str(output_path))
stop_update = True
update_thread.join(timeout=1)
# Generate supporting artifacts
score_path = generate_score(entropy, str(output_path))
analysis_path = generate_analysis(entropy, str(output_path))
print("\n" + "=" * 60)
print("THE HARMONIC ENGINE — Generation Complete")
print("=" * 60)
print(f" Dream WAV: {output_path}")
print(f" Score: {score_path}")
print(f" Analysis: {analysis_path}")
print("")
print("The machine dreamed in tones.")
print("")
if __name__ == "__main__":
main()
Run output
Generating 60s harmonic fabric at 44100Hz...
Starting with 8 voices...
Processed 8/8 voices...
Written: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream.wav
Generating visual score...
Score written: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream_score.txt
Generating harmonic analysis...
Analysis written: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream_analysis.txt
============================================================
THE HARMONIC ENGINE — Generation Complete
============================================================
Dream WAV: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream.wav
Score: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream_score.txt
Analysis: /root/.cache/act/40f32105a2a3695c/hostexecutor/dreams/2026-07-14/harmonic_dream_analysis.txt
The machine dreamed in tones.