core.py
The file math/src/tonnetz/core.py. 156 lines, 20 definitions.
N-TET Tonnetz: nodes, edges, triangles.
The pitch classes are Z_N. a is the minor third, b the major third and a + b the fifth (in steps). The major chord is M(x) = {x, x + b, x + a + b} and the minor chord is m(x) = {x, x + a, x + a + b}.
Top of file: imports
"""N-TET Tonnetz: düğümler, kenarlar, üçgenler.Perde sınıfları Z_N'dir. a küçük üçlü, b büyük üçlü, a + b beşlidir (adım cinsinden).Majör akor M(x) = {x, x + b, x + a + b}, minör akor m(x) = {x, x + a, x + a + b}."""from __future__ import annotationsfrom dataclasses import dataclassfrom functools import cached_propertyfrom math import gcd, log2from typing import Iterable, LiteralKind
constantKind = Literal["M", "m"]Chord
classA triangle (chord). kind: "M" for major, "m" for minor. root: the pitch class of the root.
@dataclass(frozen=True, order=True)class Chord: """Bir üçgen (akor). kind: "M" majör, "m" minör. root: kök perde sınıfı.""" kind: Kind root: intChord.__str__
method def __str__(self) -> str: return f"{self.kind}({self.root})"Tonnetz
classThe Tonnetz on Z_N built from the steps a (minor third) and b (major third).
The nodes are the pitch classes. Two nodes are joined by an edge when they are a, b or a + b steps apart. The constructor rejects degenerate parameters: the six directions (±a, ±b, ±(a + b)) must be non-zero and distinct, and the network must be connected.
class Tonnetz: """Z_N üzerinde, a (küçük üçlü) ve b (büyük üçlü) adımlarıyla kurulan Tonnetz. Düğümler perde sınıflarıdır. İki düğüm arasında a, b ya da a + b adım varsa kenar vardır. Kurucu, yozlaşmış parametreleri reddeder: altı yön (±a, ±b, ±(a + b)) sıfırdan ve birbirinden farklı olmalı, ağ da bağlantılı olmalıdır. """Tonnetz.__init__
method def __init__(self, N: int, a: int, b: int) -> None: if N < 3: raise ValueError("N en az 3 olmalı.") self.N = N self.a = a % N self.b = b % N self.fifth = (a + b) % N steps = {self.a, self.b, self.fifth} signed = steps | {(-s) % N for s in steps} if 0 in signed or len(signed) != 6: raise ValueError( f"Yozlaşmış parametreler: N={N}, a={a}, b={b}. " "±a, ±b, ±(a+b) sıfırdan ve birbirinden farklı olmalı." ) if gcd(gcd(self.a, self.b), N) != 1: raise ValueError("ebob(a, b, N) = 1 olmalı, yoksa ağ bağlantılı değildir.")Tonnetz.tet
methodThe N-TET Tonnetz with the steps closest to the pure intervals (6/5, 5/4, 3/2).
@classmethod def tet(cls, N: int) -> "Tonnetz": """Saf aralıklara en yakın adımlarla N-TET Tonnetz'i (6/5, 5/4, 3/2).""" a = round(N * log2(6 / 5)) b = round(N * log2(5 / 4)) if a + b != round(N * log2(3 / 2)): raise ValueError(f"N={N} için en yakın üçlüler en yakın beşliyi vermiyor.") return cls(N, a, b)Tonnetz.__repr__
method def __repr__(self) -> str: return f"Tonnetz(N={self.N}, a={self.a}, b={self.b})"Tonnetz.nodes
propertyThe nodes: the pitch classes from 0 to N - 1.
# --- yapı taşları ----------------------------------------------------- @property def nodes(self) -> range: """Düğümler: 0 ile N - 1 arasındaki perde sınıfları.""" return range(self.N)Tonnetz.edges
propertyThe edges: pairs of pitches that are a, b or a + b steps apart.
@cached_property def edges(self) -> frozenset[frozenset[int]]: """Kenarlar: aralarında a, b ya da a + b adım bulunan perde çiftleri.""" N = self.N return frozenset( frozenset({x, (x + s) % N}) for x in range(N) for s in (self.a, self.b, self.fifth) )Tonnetz.neighbors
methodThe six neighbours of node x: x ± a, x ± b, x ± (a + b).
def neighbors(self, x: int) -> list[int]: """x düğümünün altı komşusu: x ± a, x ± b, x ± (a + b).""" N = self.N return sorted({(x + s * d) % N for d in (self.a, self.b, self.fifth) for s in (1, -1)})Tonnetz.pitches
methodThe three notes of a chord: the root, the third (b steps up for major, a steps up for minor) and the fifth.
def pitches(self, chord: Chord) -> frozenset[int]: """Akorun üç sesi: kök, üçlü (majörde b, minörde a adım yukarı) ve beşli.""" third = self.b if chord.kind == "M" else self.a N = self.N return frozenset({chord.root % N, (chord.root + third) % N, (chord.root + self.fifth) % N})Tonnetz.major
methodThe major chord M(x) with root x.
Tonnetz.minor
methodThe minor chord m(x) with root x.
Tonnetz.chords
propertyAll chords: first the N major chords, then the N minor chords.
Tonnetz.triangles
propertyThe triangles: the set of notes of each chord.
Tonnetz.euler_characteristic
propertyThe Euler characteristic: number of nodes - number of edges + number of triangles.
Tonnetz.chords_within
methodThe chords whose notes all lie in the given set.
Tonnetz.edges_within
methodThe edges whose two ends both lie in the given set.
def edges_within(self, pitch_set: Iterable[int]) -> list[tuple[int, int]]: """İki ucu da verilen kümede bulunan kenarlar.""" s = {p % self.N for p in pitch_set} return sorted(tuple(sorted(e)) for e in self.edges if e <= s)Tonnetz.node_components
methodThe connected components of the subgraph spanned by the given nodes.
def node_components(self, pitch_set: Iterable[int]) -> list[list[int]]: """Verilen düğümlerin ürettiği alt grafın bağlantılı bileşenleri.""" s = {p % self.N for p in pitch_set} return _components(s, lambda x: (y for y in self.neighbors(x) if y in s))Tonnetz.chord_components
methodThe components of a set of chords, where two chords are adjacent when they share an edge (P, L, R).
_components
functionFinds connected components by depth-first search. adjacent(x) gives the neighbours of x.
def _components(items, adjacent): """Derinlik öncelikli aramayla bağlantılı bileşenleri bulur. adjacent(x), x'in komşularını verir.""" seen = set() out = [] for start in sorted(items): if start in seen: continue comp, stack = [], [start] seen.add(start) while stack: x = stack.pop() comp.append(x) for y in adjacent(x): if y not in seen: seen.add(y) stack.append(y) out.append(sorted(comp)) return out