Skip to content

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}.

Code, comments and printed output are in Turkish. The explanations are translated.

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, Literal

Kind

constant
Kind = Literal["M", "m"]

Chord

class

A 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: int

Chord.__str__

method
    def __str__(self) -> str:        return f"{self.kind}({self.root})"

Tonnetz

class

The 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

method

The 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

property

The 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

property

The 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

method

The 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

method

The 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

method

The major chord M(x) with root x.

    def major(self, x: int) -> Chord:        """Kökü x olan majör akor M(x)."""        return Chord("M", x % self.N)

Tonnetz.minor

method

The minor chord m(x) with root x.

    def minor(self, x: int) -> Chord:        """Kökü x olan minör akor m(x)."""        return Chord("m", x % self.N)

Tonnetz.chords

property

All chords: first the N major chords, then the N minor chords.

    @cached_property    def chords(self) -> list[Chord]:        """Bütün akorlar: önce N majör, sonra N minör."""        return [Chord("M", x) for x in range(self.N)] + [Chord("m", x) for x in range(self.N)]

Tonnetz.triangles

property

The triangles: the set of notes of each chord.

    @cached_property    def triangles(self) -> frozenset[frozenset[int]]:        """Üçgenler: her akorun ses kümesi."""        return frozenset(self.pitches(c) for c in self.chords)

Tonnetz.euler_characteristic

property

The Euler characteristic: number of nodes - number of edges + number of triangles.

    @property    def euler_characteristic(self) -> int:        """Euler karakteristiği: düğüm sayısı - kenar sayısı + üçgen sayısı."""        return self.N - len(self.edges) + len(self.triangles)

Tonnetz.chords_within

method

The chords whose notes all lie in the given set.

    # --- alt kümeler ------------------------------------------------------    def chords_within(self, pitch_set: Iterable[int]) -> list[Chord]:        """Bütün sesleri verilen kümede bulunan akorlar."""        s = {p % self.N for p in pitch_set}        return [c for c in self.chords if self.pitches(c) <= s]

Tonnetz.edges_within

method

The 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

method

The 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

method

The components of a set of chords, where two chords are adjacent when they share an edge (P, L, R).

    def chord_components(self, chords: Iterable[Chord]) -> list[list[Chord]]:        """Akorların kenar paylaşma (P, L, R) komşuluğuna göre bileşenleri."""        from .plr import L, P, R        s = set(chords)        return _components(s, lambda c: (d for d in (P(self, c), L(self, c), R(self, c)) if d in s))

_components

function

Finds 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

Every number on this site comes from data produced by the Python core and is checked by tests.

TÜBİTAK 2204-A mathematics project