from __future__ import annotations
__version__ = "1.5.5"
import math
from typing import Dict, List, Tuple
import plotly.graph_objects as go
# Colour mapping by chord quality (triads/7ths/sus/etc.)
QUALITY_COLOR = {
"maj": "#2563eb",
"min": "#16a34a",
"dim": "#dc2626",
"aug": "#a855f7",
"sus2": "#0ea5e9",
"sus4": "#0ea5e9",
"6": "#f59e0b",
"m6": "#f59e0b",
"maj7": "#1d4ed8",
"7": "#ea580c",
"m7": "#15803d",
"m(maj7)": "#7c3aed",
"ΓΈ7": "#b91c1c",
"dim7": "#991b1b",
"aug7": "#9333ea",
}
def pc_angle(pc: int) -> float:
return (pc % 12) * (2 * math.pi / 12)
def _chord_colour(chord: Dict) -> str:
return QUALITY_COLOR.get(chord.get("quality",""), "#334155")
def chord_helix_figure(chord: Dict, show_labels: bool = True, show_connections: bool = True) -> go.Figure:
# Spiral guide configuration (must be defined before use)
oct_min, oct_max = 3, 7
steps_per_oct = 12
y_step = 0.10 # vertical rise per semitone
pcs: List[int] = chord["pitch_classes"]
notes: List[str] = chord["notes"]
midi: List[int] = chord["midi"]
colour = _chord_colour(chord)
# Helix geometry:
# - Circular placement by pitch class (theta)
# - Height is mapped to Y axis (pitch goes UP)
r = 1.0
# Pitch-spiral mapping helper (single source of truth)
def pitch_to_xyz(pc: int, octave: int) -> tuple[float,float,float]:
s = (octave - oct_min) * 12 + (pc % 12)
turns = s / 12.0
theta = pc_angle(pc) + (2 * math.pi) * turns
x = r * math.cos(theta)
z = r * math.sin(theta)
y = (oct_min - 3) + s * y_step
return x, y, z
xs, ys, zs, labels = [], [], [], [] # Chord nodes: plot chord tones ON the rising pitch spiral (same mapping as the guide)
for pc, note, m in zip(pcs, notes, midi[:len(pcs)]):
octave = (m // 12) - 1
x, y, z = pitch_to_xyz(pc, octave)
xs.append(x); ys.append(y); zs.append(z)
labels.append(note)
fig = go.Figure()
fig.add_trace(go.Scatter3d(
x=xs, y=ys, z=zs,
mode="markers+text" if show_labels else "markers",
text=labels if show_labels else None,
textposition="top center",
marker=dict(size=8, color=colour),
name="Chord tones",
hovertemplate="Note: %{text}
x=%{x:.2f}, y=%{y:.2f}, z=%{z:.2f}",
))
# Connection lines (coloured)
if show_connections and len(xs) >= 2:
xline = xs + [xs[0]]
yline = ys + [ys[0]]
zline = zs + [zs[0]]
fig.add_trace(go.Scatter3d(
x=xline, y=yline, z=zline,
mode="lines",
line=dict(color=colour, width=6),
name="Chord shape",
hoverinfo="skip",
opacity=0.9
))
# Fill the area between chord nodes (semi-transparent) and project onto a reference plane
if len(xs) >= 3:
# 3D fill (fan triangulation)
i = [0] * (len(xs) - 2)
j = list(range(1, len(xs) - 1))
k = list(range(2, len(xs)))
fig.add_trace(go.Mesh3d(
x=xs, y=ys, z=zs,
i=i, j=j, k=k,
color=colour,
opacity=0.20,
name="Chord fill",
hoverinfo="skip",
))
# Projection plane is y = min(ys) - small padding
y0 = min(ys) - 0.35
fig.add_trace(go.Mesh3d(
x=xs,
y=[y0 for _ in ys],
z=zs,
color=colour,
opacity=0.18,
name="Projection",
hoverinfo="skip",
))
# Reference helix: TRUE upward pitch spiral (continuous rise)
spiral_x, spiral_y, spiral_z = [], [], []
total_steps = (oct_max - oct_min) * steps_per_oct
# Make the spiral visually curved by sampling between semitone steps
substeps = 10 # higher = smoother curve (more points)
for si in range(total_steps * substeps + 1):
s = si / substeps # fractional semitone steps
turns = s / 12.0
# Anchor phase to C=0 so the curve is smooth
theta = pc_angle(0) + (2 * math.pi) * turns + (2 * math.pi) * ((s % 12) / 12.0)
x = r * math.cos(theta)
z = r * math.sin(theta)
y = (oct_min - 3) + s * y_step
spiral_x.append(x); spiral_y.append(y); spiral_z.append(z)
fig.add_trace(go.Scatter3d(
x=spiral_x, y=spiral_y, z=spiral_z,
mode="lines",
line=dict(color="#ffffff", width=4, dash="dot"),
name="Pitch spiral",
hoverinfo="skip",
opacity=0.65
))
# Labels: place one chromatic turn of labels on the spiral for readability
prefer_sharps = bool(chord.get('prefer_sharps', True)) if isinstance(chord, dict) else True
label_names = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"] if prefer_sharps else ["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"]
lab_x, lab_y, lab_z, lab_t = [], [], [], []
base_s = int(steps_per_oct * 1.5) # mid-turn
for pc in range(12):
s = base_s + pc
octave = oct_min + (s // 12)
x, y, z = pitch_to_xyz(pc, octave)
lab_x.append(x); lab_y.append(y); lab_z.append(z)
lab_t.append(label_names[pc])
fig.add_trace(go.Scatter3d(
x=lab_x, y=lab_y, z=lab_z,
mode="text",
text=lab_t,
textposition="middle center",
textfont=dict(size=12, color="#ffffff"),
name="Note labels",
hoverinfo="skip",
opacity=0.85
))
# Camera: slight elevation and centred; allow orbit (user can spin easily)
fig.update_layout(
margin=dict(l=0, r=0, t=10, b=0),
scene=dict(
bgcolor="rgba(0,0,0,0)",
xaxis=dict(visible=False),
yaxis=dict(title="Helix axis (upward)", showgrid=False),
zaxis=dict(visible=False),
aspectmode="data",
camera=dict(
eye=dict(x=2.2, y=1.6, z=1.2),
up=dict(x=0, y=1, z=0), # x-axis as "up" feel for rotation
),
),
dragmode="orbit",
height=540,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),
)
return fig
def chord_helix_figure_overlays(chords: list[dict], active_idx: int | None = None, pulse: float = 1.0):
"""Render multiple chords over the same pitch spiral."""
if not chords:
return chord_helix_figure({"pitch_classes": [], "midi": [], "name": "No chord", "prefer_sharps": True})
base = chord_helix_figure(chords[0])
for i, ch in enumerate(chords):
fig_i = chord_helix_figure(ch)
for tr in fig_i.data:
name = getattr(tr, "name", "") or ""
if name in ("Pitch spiral", "Note labels"):
continue
is_active = (active_idx is not None and i == active_idx)
# Marker highlight
if getattr(tr, "mode", "") and "markers" in tr.mode and hasattr(tr, "marker"):
tr.marker.size = (11 * pulse) if is_active else 7
tr.marker.opacity = 1.0 if is_active else 0.55
if hasattr(tr.marker, "line"):
tr.marker.line.width = 2 if is_active else 0
# Glow ring around active chord
if is_active and hasattr(tr, 'x') and tr.x is not None and len(tr.x) >= 3:
try:
xs = [float(v) for v in tr.x]
ys = [float(v) for v in tr.y]
zs = [float(v) for v in tr.z]
cx = sum(xs) / len(xs)
cy = sum(ys) / len(ys)
cz = sum(zs) / len(zs)
r0 = max(( (x-cx)**2 + (z-cz)**2 )**0.5 for x,z in zip(xs,zs))
r1 = max(0.15, r0 * 1.6)
ring_n = 64
ring_x = [cx + r1 * math.cos(2*math.pi*k/ring_n) for k in range(ring_n+1)]
ring_z = [cz + r1 * math.sin(2*math.pi*k/ring_n) for k in range(ring_n+1)]
ring_y = [cy for _ in range(ring_n+1)]
base.add_trace(go.Scatter3d(
x=ring_x, y=ring_y, z=ring_z,
mode='lines',
line=dict(width=6, color='rgba(255,255,255,0.45)'),
name=f'Active ring {i+1}',
hoverinfo='skip',
opacity=0.55
))
except Exception:
pass
# Surface/area highlight
if hasattr(tr, "opacity"):
tr.opacity = 0.35 if is_active else min(float(getattr(tr, "opacity", 0.25)), 0.18)
tr.name = f"Chord {i+1}: {ch.get('name','')}".strip()
base.add_trace(tr)
return base