Cadences#

Hide imports
%load_ext autoreload
%autoreload 2
import os
from collections import Counter, defaultdict

import dimcat as dc
import ms3
import pandas as pd
import plotly.express as px
from dimcat import plotting
from dimcat.steps import filters, groupers, slicers

import utils
/usr/lib/python3/dist-packages/requests/__init__.py:106: RequestsDependencyWarning: urllib3 (2.0.7) or chardet (6.0.0.post1)/charset_normalizer (None) doesn't match a supported version!
  warnings.warn(
Hide source
RESULTS_PATH = os.path.abspath(os.path.join(utils.OUTPUT_FOLDER, "cadences"))
os.makedirs(RESULTS_PATH, exist_ok=True)


def make_output_path(
    filename: str,
    extension=None,
    path=RESULTS_PATH,
) -> str:
    return utils.make_output_path(filename=filename, extension=extension, path=path)


def save_figure_as(
    fig, filename, formats=("png", "pdf"), directory=RESULTS_PATH, **kwargs
):
    if formats is not None:
        for fmt in formats:
            plotting.write_image(fig, filename, directory, format=fmt, **kwargs)
    else:
        plotting.write_image(fig, filename, directory, **kwargs)

Loading data

Hide source
D = utils.get_dataset("rachmaninoff_piano", corpus_release="v2.4")
package = D.inputs.get_package()
package_info = package._package.custom
git_tag = package_info.get("git_tag")
utils.print_heading("Data and software versions")
print("Sergei Rachmaninoff – Variations on a Theme of Corelli, Op. 42 version v2.4")
print(f"Datapackage '{package.package_name}' @ {git_tag}")
print(f"dimcat version {dc.__version__}\n")
D
Data and software versions
--------------------------

Sergei Rachmaninoff – Variations on a Theme of Corelli, Op. 42 version v2.4
Datapackage 'rachmaninoff_piano' @ v2.4
dimcat version 3.4.1
Dataset
=======
{'inputs': {'basepath': None,
            'packages': {'rachmaninoff_piano': ["'rachmaninoff_piano.measures' (MuseScoreFacetName.MuseScoreMeasures)",
                                                "'rachmaninoff_piano.notes' (MuseScoreFacetName.MuseScoreNotes)",
                                                "'rachmaninoff_piano.expanded' (MuseScoreFacetName.MuseScoreHarmonies)",
                                                "'rachmaninoff_piano.chords' (MuseScoreFacetName.MuseScoreChords)",
                                                "'rachmaninoff_piano.metadata' (FeatureName.Metadata)"]}},
 'outputs': {'basepath': None, 'packages': {}},
 'pipeline': []}
try:
    cadence_labels = D.get_feature("cadencelabels")
except Exception:
    raise ValueError("Corpus has no cadence annotations.")
cadence_labels
mc mn quarterbeats quarterbeats_all_endings duration_qb mc_onset mn_onset timesig staff voice ... globalkey localkey globalkey_is_minor localkey_is_minor globalkey_mode localkey_mode localkey_resolved localkey_and_mode cadence_type cadence
corpus piece i
rachmaninoff_piano op42_01a 11 8 8 21 21 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor HC HC
27 16 16 46 46 2.00 1/4 1/4 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_01b 16 8 8 21 21 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor HC HC
34 16 16 45 45 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_02 11 8 8 21 21 3.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor HC HC
23 16 16 45 45 3.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_03 23 8 8 21 21 3.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor HC HC
51 16 16 45 45 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_04 9 8 8 21 21 3.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor DC DC
21 16 16 45 45 3.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_05 16 15 15 38 38 6.00 0 0 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_06 35 8 8 21 21 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor HC HC
81 16 16 47 47 1.00 1/2 1/2 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_07 25 8 8 23 23 1.00 1/2 1/2 3/4 2 1 ... d i True True minor minor i i, minor HC HC
50 18 18 51 51 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PC PC
op42_08 20 7 7 20 20 1.00 1/2 1/2 3/4 2 2 ... d i True True minor minor i i, minor HC HC
44 15 15 44 44 1.00 1/2 1/2 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_09 20 8 8 23 23 1.00 1/2 1/2 3/4 2 1 ... d i True True minor minor i i, minor HC HC
27 11 11 30 30 2.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PC PC
51 19 19 56 56 1.00 1/2 1/2 3/4 2 1 ... d i True True minor minor i i, minor HC HC
op42_10 10 10 10 30 30 5.00 0 0 4/4 2 1 ... d i True True minor minor i i, minor EC EC
12 12 12 36 36 3.00 0 0 4/4 2 1 ... d i True True minor minor i i, minor HC HC
35 19 19 62 62 5.50 0 0 4/4 2 1 ... d i True True minor minor i i, minor PAC PAC
44 24 24 79 79 6.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_11 53 16 16 45 45 3.00 0 0 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_12 46 15 15 42 42 1.00 0 0 3/4 2 1 ... d iv True True minor minor iv iv, minor DC DC
67 22 22 64 64 4.00 1/2 1/2 3/4 2 2 ... d i True True minor minor i i, minor PAC PAC
op42_13a 20 5 5 19 19 0.50 1/4 1/4 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
35 9 9 71/2 71/2 0.50 1/4 1/4 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
67 17 17 135/2 135/2 3.00 0 0 6/8 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_14 33 16 16 45 45 1.00 0 0 3/4 2 1 ... Db I False False major major I I, major PAC PAC
op42_16 23 9 8 57/2 57/2 3.50 0 0 4/4 2 1 ... d i True True minor minor i i, minor HC HC
op42_17 14 11 11 79/2 79/2 6.00 11/8 11/8 6/4 2 1 ... d i True True minor minor i i, minor IAC IAC
33 20 20 80 80 5.50 0 0 4/4 2 1 ... d i True True minor minor i i, minor DC DC
35 22 22 88 88 1.50 0 0 4/4 2 1 ... d i True True minor minor i i, minor PC PC
op42_18 6 5 5 18 18 0.75 0 0 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
31 9 9 36 36 3.50 0 0 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
38 13 13 54 54 3.00 0 0 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
48 16 16 135/2 135/2 4.50 0 0 9/8 2 1 ... d i True True minor minor i i, minor PAC PAC
op42_19 12 3 3 9 9 0.75 0 0 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
22 5 5 18 18 0.75 0 0 9/8 2 1 ... d i True True minor minor i i, minor IAC IAC
45 9 9 36 36 1.00 0 0 9/8 2 1 ... d i True True minor minor i i, minor PAC PAC
69 13 13 54 54 1.00 0 0 9/8 2 1 ... d III True False minor major III III, minor IAC IAC
op42_20 8 5 5 18 18 3.00 0 0 9/8 2 1 ... d i True True minor minor i i, minor PAC PAC
16 9 9 36 36 3.00 0 0 9/8 2 1 ... d i True True minor minor i i, minor PAC PAC
27 13 13 54 54 1.50 0 0 9/8 2 1 ... d i True True minor minor i i, minor EC EC
42 17 17 141/2 141/2 4.50 0 0 9/8 2 1 ... d i True True minor minor i i, minor EC EC
71 24 24 211/2 211/2 11.50 7/8 7/8 9/8 2 1 ... d i True True minor minor i i, minor PAC PAC
99 44 44 172 172 2.00 1/4 1/4 3/4 2 1 ... d i True True minor minor i i, minor PAC PAC

49 rows × 22 columns

cadence_labels.plot_grouped(
    title="Distribution of cadence types over the DLC",
    output=make_output_path("all_cadences_pie"),
    width=1000,
    height=1000,
)

Metadata#

cadence_filter = filters.HasCadenceAnnotationsFilter()
filtered_D = cadence_filter.process(D)
hascadence_metadata = filtered_D.get_metadata()
chronological_corpus_names = hascadence_metadata.get_corpus_names()
cadence_counts = cadence_labels.apply_step("Counter")
cadence_counts.plot_grouped("corpus")
mean_composition_years = (
    hascadence_metadata.groupby(level="corpus").composed_end.mean().astype(int).sort_values()
)
chronological_corpus_names = hascadence_metadata.get_corpus_names()
bar_data = pd.concat(
    [
        mean_composition_years.rename("year"),
        hascadence_metadata.groupby(level="corpus").size().rename("pieces"),
    ],
    axis=1,
).rename_axis("corpus").reset_index()
fig = px.bar(
    bar_data,
    x="year",
    y="pieces",
    color="corpus",
    title="Pieces contained in the dataset",
)
fig.update_traces(width=5)

Overall#

  • PAC: Perfect Authentic Cadence

  • IAC: Imperfect Authentic Cadence

  • HC: Half Cadence

  • DC: Deceptive Cadence

  • EC: Evaded Cadence

  • PC: Plagal Cadence

print(f"{len(cadence_labels)} cadence labels.")
utils.value_count_df(cadence_labels.cadence)
49 cadence labels.
counts %
cadence
PAC 20 40.82
HC 11 22.45
IAC 9 18.37
DC 3 6.12
PC 3 6.12
EC 3 6.12

Per dataset#

all_labels = D.get_feature("harmonylabels")
cadence_count_per_dataset = all_labels.groupby("corpus").cadence.value_counts()
cadence_fraction_per_dataset = (
    cadence_count_per_dataset / cadence_count_per_dataset.groupby(level=0).sum()
)
cadence_fraction_per_dataset = cadence_fraction_per_dataset.rename(
    "fraction"
).reset_index()
cadence_fraction_per_dataset["corpus_name"] = cadence_fraction_per_dataset.corpus.map(
    utils.get_corpus_display_name
)
fig = px.bar(
    cadence_fraction_per_dataset,
    x="corpus_name",
    y="fraction",
    title="Distribution of cadence types per corpus",
    color="cadence",
    color_discrete_map=plotting.CADENCE_COLORS,
    labels=dict(corpus_name="", fraction="Fraction of all cadences"),
    category_orders=dict(corpus_name=chronological_corpus_names),
)
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "all_cadences_corpuswise_stacked_bars", height=1000)
fig.show()
fig = px.pie(
    cadence_count_per_dataset.rename("count").reset_index(),
    names="cadence",
    color="cadence",
    values="count",
    facet_col="corpus",
    facet_col_wrap=4,
    height=2000,
    color_discrete_map=plotting.CADENCE_COLORS,
)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "all_cadences_corpuswise_pies")
fig.show()
cadence_count_per_mode = (
    all_labels.groupby("localkey_is_minor").cadence.value_counts().reset_index()
)
cadence_count_per_mode["mode"] = cadence_count_per_mode.localkey_is_minor.map(
    {False: "major", True: "minor"}
)
fig = px.pie(
    cadence_count_per_mode,
    names="cadence",
    color="cadence",
    values="count",
    facet_col="mode",
    height=2000,
    color_discrete_map=plotting.CADENCE_COLORS,
)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "all_cadences_modewise_pies")
fig.show()

Per phrase#

Number of cadences per phrase#

grouped_by_corpus = groupers.CorpusGrouper().process(D)
phrase_slicer = slicers.PhraseSlicer()
segmented = phrase_slicer.process(grouped_by_corpus)
phrases = phrase_slicer.slice_metadata.df
phrase_segments = segmented.get_feature("DcmlAnnotations").df
phrase_index_names = list(phrase_segments.index.names[:3])
if phrases.index.nlevels > 3:
    phrases = phrases.droplevel(list(range(3, phrases.index.nlevels)))
if phrases.index.nlevels != 3:
    raise ValueError("Phrase metadata index must have corpus, piece, and phrase levels.")
phrases.index = phrases.index.set_names(phrase_index_names)
if phrases.index.has_duplicates:
    phrases = phrases[~phrases.index.duplicated(keep="first")]
phrase_gpb = phrase_segments.groupby(level=[0, 1, 2])
local_keys_per_phrase = phrase_gpb.localkey.unique().map(tuple)
n_local_keys_per_phrase = local_keys_per_phrase.map(len)
phrases_with_keys = pd.concat(
    [
        n_local_keys_per_phrase.rename("n_local_keys"),
        local_keys_per_phrase.rename("local_keys"),
        phrases,
    ],
    axis=1,
)
phrases_with_cadences = pd.concat(
    [
        phrase_gpb.cadence.nunique().rename("n_cadences"),
        phrase_gpb.cadence.unique()
        .rename("cadences")
        .map(lambda arr: tuple(e for e in arr if not pd.isnull(e))),
        phrases_with_keys,
    ],
    axis=1,
)
utils.value_count_df(phrases_with_cadences.n_cadences, counts_column="#phrases")
/home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py:320: FutureWarning:

Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value '[<NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>]' has dtype incompatible with float64, please explicitly cast to a compatible dtype first.
WARNING  dimcat.data.resources.features.CadenceLabels -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 39.0), [37.0, 62.0), [62.0, 85.0)], dtype='interval[float64, left]', name='phrase_slice')
/home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py:1345: FutureWarning:

The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.

WARNING  dimcat.data.resources.features.CadenceLabels -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 6.0), [5.0, 11.0), [11.0, 24.0), [24.0, 30.0), [29.0, 35.0), [35.0, 48.0)], dtype='interval[float64, left]', name='phrase_slice')
/home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py:1345: FutureWarning:

The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.
WARNING  dimcat.data.resources.features.HarmonyLabels -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 39.0), [37.0, 62.0), [62.0, 85.0)], dtype='interval[float64, left]', name='phrase_slice')
WARNING  dimcat.data.resources.features.HarmonyLabels -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 6.0), [5.0, 11.0), [11.0, 24.0), [24.0, 30.0), [29.0, 35.0), [35.0, 48.0)], dtype='interval[float64, left]', name='phrase_slice')
WARNING  dimcat.data.resources.features.DcmlAnnotations -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 39.0), [37.0, 62.0), [62.0, 85.0)], dtype='interval[float64, left]', name='phrase_slice')
WARNING  dimcat.data.resources.features.DcmlAnnotations -- /home/runner/.local/lib/python3.12/site-packages/dimcat/data/resources/utils.py (line 1317) in overlapping_chunk_per_interval_cutoff_direct():
	Intervals are not non-overlapping and/or not monotonically increasing:
IntervalIndex([[0.0, 6.0), [5.0, 11.0), [11.0, 24.0), [24.0, 30.0), [29.0, 35.0), [35.0, 48.0)], dtype='interval[float64, left]', name='phrase_slice')
#phrases %
n_cadences
1.0 40 50.63
0.0 34 43.04
2.0 5 6.33
n_cad = (
    phrases_with_cadences.groupby(level="corpus")
    .n_cadences.value_counts()
    .rename("counts")
    .reset_index()
    .sort_values("n_cadences")
)
n_cad.n_cadences = n_cad.n_cadences.astype(str)
fig = px.bar(
    n_cad,
    x="corpus",
    y="counts",
    color="n_cadences",
    height=800,
    barmode="group",
    labels=dict(n_cadences="#cadences in a phrase"),
    category_orders=dict(dataset=chronological_corpus_names),
)
save_figure_as(fig, "n_cadences_per_phrase_corpuswise_absolute_grouped_bars")
fig.show()

Combinations of cadence types for phrases with more than one cadence#

utils.value_count_df(
    phrases_with_cadences[phrases_with_cadences.n_cadences > 1].cadences
)
counts %
cadences
(PC, HC) 1 20.0
(EC, HC) 1 20.0
(DC, PAC) 1 20.0
(DC, PC) 1 20.0
(IAC, PAC) 1 20.0

Positioning of cadences within phrases#

df_rows = []
y_position = 0
for ix in (
    phrases_with_cadences[phrases_with_cadences.n_cadences > 0]
    .sort_values("duration_qb")
    .index
):
    df = phrase_segments.loc[ix]
    description = str(ix)
    if df.cadence.notna().any():
        interval = ix[2]
        df_rows.append((y_position, interval.length, "end of phrase", description))
        start_pos = interval.left
        cadences = df.loc[df.cadence.notna(), ["quarterbeats", "cadence"]]
        cadences.quarterbeats = cadences.quarterbeats.map(float) - start_pos
        for cadence_x, cadence_type in cadences.itertuples(index=False, name=None):
            df_rows.append((y_position, cadence_x, cadence_type, description))
        y_position += 1
    # else:
    #    df_rows.append((y_position, pd.NA, pd.NA, description))

data = pd.DataFrame(df_rows, columns=["phrase_ix", "x", "marker", "description"])
fig = px.scatter(
    data[data.x.notna()],
    x="x",
    y="phrase_ix",
    color="marker",
    hover_name="description",
    height=3000,
    labels=dict(marker="legend"),
    color_discrete_map=plotting.CADENCE_COLORS,
)
fig.update_traces(marker_size=5)
fig.update_yaxes(autorange="reversed")
save_figure_as(fig, "cadence_positions_within_all_phrases")
fig.show()

Cadence ultima#

phrase_segments = phrase_segments.copy()
cadence_selector = phrase_segments.cadence.notna()
missing_chord_selector = phrase_segments.chord.isna()
cadence_with_missing_chord_selector = cadence_selector & missing_chord_selector
missing = phrase_segments[cadence_with_missing_chord_selector]
if cadence_with_missing_chord_selector.any():
    expanded = ms3.expand_dcml.expand_labels(
        phrase_segments[cadence_with_missing_chord_selector],
        propagate=False,
        chord_tones=True,
        skip_checks=True,
    )
    phrase_segments.loc[cadence_with_missing_chord_selector] = expanded
print(
    f"Ultima harmony missing for {(phrase_segments.cadence.notna() & phrase_segments.bass_note.isna()).sum()} cadence "
    f"labels."
)
Ultima harmony missing for 0 cadence labels.

Ultimae as Roman numeral#

def highlight(row, color="#ffffb3"):
    if row.counts < 10:
        return [None, None, None, None]
    else:
        return ["background-color: {color};"] * 4


cadence_counts = all_labels.cadence.value_counts()
ultima_root = (
    phrase_segments.groupby(["localkey_is_minor", "cadence"])
    .numeral.value_counts()
    .rename("counts")
    .to_frame()
    .reset_index()
)
ultima_root.localkey_is_minor = ultima_root.localkey_is_minor.map(
    {False: "in major", True: "in minor"}
)
# ultima_root.style.apply(highlight, axis=1)
fig = px.pie(
    ultima_root,
    names="numeral",
    values="counts",
    facet_row="cadence",
    facet_col="localkey_is_minor",
    height=1500,
    category_orders={"cadence": cadence_counts.index},
)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_traces(textposition="inside", textinfo="percent+label")
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "ultima_root_distributions_over_cadence_types_maj_min_pies")
fig.show()
# phrase_segments.groupby(level=[0,1,2], group_keys=False).apply(lambda df: df if ((df.cadence == 'PAC') &
# (df.numeral == 'V')).any() else None)

Ultimae bass note as scale degree#

ultima_bass = (
    phrase_segments.groupby(["localkey_is_minor", "cadence"])
    .bass_note.value_counts()
    .rename("counts")
    .reset_index()
)
ultima_bass.bass_note = ms3.transform(
    ultima_bass, ms3.fifths2sd, dict(fifths="bass_note", minor="localkey_is_minor")
)
ultima_bass.localkey_is_minor = ultima_bass.localkey_is_minor.map(
    {False: "in major", True: "in minor"}
)
# ultima_bass.style.apply(highlight, axis=1)
fig = px.pie(
    ultima_bass,
    names="bass_note",
    values="counts",
    facet_row="cadence",
    facet_col="localkey_is_minor",
    height=1500,
    category_orders={"cadence": cadence_counts.index},
)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_traces(textposition="inside", textinfo="percent+label")
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "ultima_degree_distributions_over_cadence_types_maj_min_pies")
fig.show()

Chord progressions#

PACs with ultima I/i#

def remove_immediate_duplicates(lst):
    return tuple(a for a, b in zip(lst, (None,) + lst) if a != b)


def get_progressions(
    selected="PAC",
    last_row={},
    feature="chord",
    dataset=None,
    as_series=True,
    remove_duplicates=False,
):
    """Uses the nonlocal variable phrase_segments."""
    last_row = {k: v if isinstance(v, tuple) else (v,) for k, v in last_row.items()}
    progressions = []

    for (corp, fname, *_), df in phrase_segments[
        phrase_segments[feature].notna()
    ].groupby(level=[0, 1, 2]):
        if dataset is not None and dataset not in corp:
            continue
        if (df.cadence == selected).fillna(False).any():
            # remove chords after the last cadence label
            df = df[df.cadence.bfill().notna()]
            # group segments leading up to a cadence label
            cadence_groups = df.cadence.notna().shift().fillna(False).cumsum()
            for i, cadence in df.groupby(cadence_groups):
                last_r = cadence.iloc[-1]
                typ = last_r.cadence
                if typ != selected:
                    continue
                if any(last_r[feat] not in values for feat, values in last_row.items()):
                    continue
                if remove_duplicates:
                    progressions.append(
                        remove_immediate_duplicates(cadence[feature].to_list())
                    )
                else:
                    progressions.append(tuple(cadence[feature]))
    if as_series:
        return pd.Series(progressions, dtype="object")
    return progressions
chord_progressions = get_progressions("PAC", dict(numeral=("I", "i")), "chord")
print(f"Progressions for {len(chord_progressions)} cadences:")
utils.value_count_df(chord_progressions, "chord progressions")
Progressions for 19 cadences:
counts %
chord progressions
(i,) 3 15.79
(iv6(11), V43/III, V6(11)/#vi, i64/#vi, V6(11)/VI, i64/VI, ii6(11), V64, i) 1 5.26
(i, #vii, i, #vii64, i64, iii, i, vi, VII, bv, VI, #iii, i, #vii2, i, #vii64, i, #iii7, i, V+7/VI, i, V2/#vi, i, Fr43/iv, V(4), i) 1 5.26
(V(4)/III, V/III, bII+64, iv, V(4)/iv, V/iv, III+64, vi, V(6), i) 1 5.26
(V7/ii, #IM7(#8), V7(6), V7(9)/IV, IV(13), #i, iv7, V7, I(4)) 1 5.26
(iii/III, v(13)/III, v7/III, ivM43(9), V7(b94)/III, V7(b964)/III, IIIM43(9), iiM43(#9), biiM43(9), V(6), V/iv, bV64/iv, iv7(94), V7, i) 1 5.26
(V7, iii64/V, IIIM7, V7/ii, iii64/V/ii, #iii7/ii, V7(b9)/bII, V7/ii, V7(+#9), V7(b9)/bII, V7/VII, viio2(4)/VII, V7(6^2)/VII, viio2(4)/VII, V7(6^2)/VII, viio2(4)/VII, V7(6^2)/VII, viio2(4)/VII, v, VM7(2), i) 1 5.26
(i6, V6, i6, V6, i6, V6, bI, i6, V6, i6, V6, i6, V6, III64, i6, V6, i6, V6, i6, V6, i64(+6), v64, V, V64, i6(+6), V, i6, V6, i6, V6, i6, V6, v, bI, i6, V6, i6, V6, i6, V6, v/bI, III64, i6, V6, i6, V6, i6, V6, ii, bI64, i64, i, V, i) 1 5.26
(i, V, i, iv7, V/III, V+/III, I/III, V43/III, I/III, #viio7, i, ii65, V(4), V7, i(4), i) 1 5.26
(i, i6, ii%65, V, i, i6, V7/V/III, V/III, I/III, I6/III, V65/V/III, V/III, #viio7, i, ii%65, V7(4), V7, i) 1 5.26
(i, IV7(9), V+6/V, V+, IVM7, VM7/III, i/III, IV7(9)/III, biii6/III, V7/III, viio65/V/III, viio7/III, I/bV, bIII64/bV, iv, IM7, #IV2, III64, II, iv6, #viio7/iv, bI64, V7(4), i) 1 5.26
(i, V2/iv, VI/iv, I/VI, iv/VI, V, i, i6(#6), V, I/III, V/iv, i/iv, V/#iii, i/#iii, V/III, I/III, I6/III, V/III, iv, V, I/VI, IV/VI, V/VII, I/VII, #vii/iv, i6/iv, V/iv, i/iv, V, i, III, VI, V/iv, i/iv, I/VI, IV/VI, V, i, #viio2, i43, #viio43(4), i6, bIIM7, i, V7, i) 1 5.26
(i(^2), v, I(9)/III, v/III, iv7, IIIM7, bIIM7, V(b9), i) 1 5.26
(I, i6, v6, i, v6, iv, IV7/III, I/III, ii%65/bII, I/bII, V7(4), i) 1 5.26
(i/i, bIIM7, V, V7(11)/V, Fr43/iv, i, ii%65, i, V(6)/V/III, V/III, i/III, Fr7(4)/III, Fr43/VI, i7(b5), i64/V, viio43/V, i6/V, iv7(^4)/III, I/III, iv65(^4)/III, I64/III, iio43/i, bVI/III, V, i, ii%65, V7(^4), i) 1 5.26
(i, Fr43, V7, i, viio7/V/III, V7/III, I/III, V7/III, viio7(4), i, V7, i) 1 5.26
(III, V/III, V43/#vi, i(b9), ii%65, V7, i) 1 5.26
numeral_progressions = get_progressions("PAC", dict(numeral=("I", "i")), "numeral")
utils.value_count_df(numeral_progressions, "numeral progressions")
counts %
numeral progressions
(i,) 3 15.79
(iv, V, V, i, V, i, ii, V, i) 1 5.26
(i, #vii, i, #vii, i, iii, i, vi, VII, bv, VI, #iii, i, #vii, i, #vii, i, #iii, i, V, i, V, i, V, V, i) 1 5.26
(V, V, bII, iv, V, V, III, vi, V, i) 1 5.26
(V, #I, V, V, IV, #i, iv, V, I) 1 5.26
(iii, v, v, iv, V, V, III, ii, bii, V, V, bV, iv, V, i) 1 5.26
(V, iii, III, V, iii, #iii, V, V, V, V, V, vii, V, vii, V, vii, V, vii, v, V, i) 1 5.26
(i, V, i, V, i, V, bI, i, V, i, V, i, V, III, i, V, i, V, i, V, i, v, V, V, i, V, i, V, i, V, i, V, v, bI, i, V, i, V, i, V, v, III, i, V, i, V, i, V, ii, bI, i, i, V, i) 1 5.26
(i, V, i, iv, V, V, I, V, I, #vii, i, ii, V, V, i, i) 1 5.26
(i, i, ii, V, i, i, V, V, I, I, V, V, #vii, i, ii, V, V, i) 1 5.26
(i, IV, V, V, IV, V, i, IV, biii, V, vii, vii, I, bIII, iv, I, #IV, III, II, iv, #vii, bI, V, i) 1 5.26
(i, V, VI, I, iv, V, i, i, V, I, V, i, V, i, V, I, I, V, iv, V, I, IV, V, I, #vii, i, V, i, V, i, III, VI, V, i, I, IV, V, i, #vii, i, #vii, i, bII, i, V, i) 1 5.26
(i, v, I, v, iv, III, bII, V, i) 1 5.26
(I, i, v, i, v, iv, IV, I, ii, I, V, i) 1 5.26
(i, bII, V, V, V, i, ii, i, V, V, i, V, V, i, i, vii, i, iv, I, iv, I, ii, bVI, V, i, ii, V, i) 1 5.26
(i, V, V, i, vii, V, I, V, vii, i, V, i) 1 5.26
(III, V, V, i, ii, V, i) 1 5.26
numeral_prog_no_dups = numeral_progressions.map(remove_immediate_duplicates)
utils.value_count_df(numeral_prog_no_dups)
counts %
(i,) 3 15.79
(iv, V, i, V, i, ii, V, i) 1 5.26
(i, #vii, i, #vii, i, iii, i, vi, VII, bv, VI, #iii, i, #vii, i, #vii, i, #iii, i, V, i, V, i, V, i) 1 5.26
(V, bII, iv, V, III, vi, V, i) 1 5.26
(V, #I, V, IV, #i, iv, V, I) 1 5.26
(iii, v, iv, V, III, ii, bii, V, bV, iv, V, i) 1 5.26
(V, iii, III, V, iii, #iii, V, vii, V, vii, V, vii, V, vii, v, V, i) 1 5.26
(i, V, i, V, i, V, bI, i, V, i, V, i, V, III, i, V, i, V, i, V, i, v, V, i, V, i, V, i, V, i, V, v, bI, i, V, i, V, i, V, v, III, i, V, i, V, i, V, ii, bI, i, V, i) 1 5.26
(i, V, i, iv, V, I, V, I, #vii, i, ii, V, i) 1 5.26
(i, ii, V, i, V, I, V, #vii, i, ii, V, i) 1 5.26
(i, IV, V, IV, V, i, IV, biii, V, vii, I, bIII, iv, I, #IV, III, II, iv, #vii, bI, V, i) 1 5.26
(i, V, VI, I, iv, V, i, V, I, V, i, V, i, V, I, V, iv, V, I, IV, V, I, #vii, i, V, i, V, i, III, VI, V, i, I, IV, V, i, #vii, i, #vii, i, bII, i, V, i) 1 5.26
(i, v, I, v, iv, III, bII, V, i) 1 5.26
(I, i, v, i, v, iv, IV, I, ii, I, V, i) 1 5.26
(i, bII, V, i, ii, i, V, i, V, i, vii, i, iv, I, iv, I, ii, bVI, V, i, ii, V, i) 1 5.26
(i, V, i, vii, V, I, V, vii, i, V, i) 1 5.26
(III, V, i, ii, V, i) 1 5.26

PACs ending on scale degree 1#

Scale degrees expressed w.r.t. major scale, regardless of actual key.

bass_progressions = get_progressions("PAC", dict(bass_note=0), "bass_note")
bass_prog = bass_progressions.map(ms3.fifths2sd)
print(f"Progressions for {len(bass_progressions)} cadences:")
utils.value_count_df(bass_prog, "bass progressions")
Progressions for 19 cadences:
counts %
bass progressions
(1,) 3 15.79
(b6, 4, #5, 3, 5, b3, 4, 2, 1) 1 5.26
(1, 7, 1, #4, 5, b3, 1, b6, b7, b5, b6, 3, 1, 6, 1, #4, 1, 3, 1, b3, 1, 2, 1, b2, 5, 1) 1 5.26
(b7, b7, 6, 4, 1, 1, 7, b6, 5, 1) 1 5.26
(6, #1, 5, 1, 4, #1, 4, 5, 1) 1 5.26
(5, b7, b7, 1, b7, b7, b7, 6, b6, 5, 1, b5, 4, 5, 1) 1 5.26
(5, #4, b3, 6, #5, #4, b6, 6, 5, b6, 4, b5, 4, b5, 4, b5, 4, b5, 5, b6, 1) 1 5.26
(b3, 7, b3, 7, b3, 7, b1, b3, 7, b3, 7, b3, 7, b7, b3, 7, b3, 7, b3, 7, 5, 2, 5, 2, b3, 5, b3, 7, b3, 7, b3, 7, 5, b1, b3, 7, b3, 7, b3, 7, b5, b7, b3, 7, b3, 7, b3, 7, 2, b5, 5, 1, 5, 1) 1 5.26
(1, 5, 1, 4, b7, b7, b3, 4, b3, 7, 1, 4, 5, 5, 1, 1) 1 5.26
(1, b3, 4, 5, 1, b3, 4, b7, b3, 5, 6, b7, 7, 1, 4, 5, 5, 1) 1 5.26
(1, 4, #4, 5, 4, b7, b3, b6, bb7, b7, 1, 2, b5, b4, 4, 1, 3, b7, 2, b6, 3, b5, 5, 1) 1 5.26
(1, b7, b2, b6, b2, 5, 1, b3, 5, b3, 1, 4, 7, 3, b7, b3, 5, b7, 4, 5, b6, b2, 4, b7, 3, b6, 1, 4, 5, 1, b3, b6, 1, 4, b6, b2, 5, 1, b6, 5, 4, b3, b2, 1, 5, 1) 1 5.26
(1, 5, b3, b7, 4, b3, b2, 5, 1) 1 5.26
(1, b3, b7, 1, b7, 4, b6, b3, b5, b2, 5, 1) 1 5.26
(1, b2, 5, 2, b2, 1, 4, 1, 4, b7, b3, 4, b4, 1, 2, 1, b7, b6, b3, b1, b7, b6, b1, 5, 1, 4, 5, 1) 1 5.26
(1, b6, 5, 1, 6, b7, b3, b7, b7, 1, 5, 1) 1 5.26
(b3, b7, 7, 1, 4, 5, 1) 1 5.26
bass_prog_no_dups = bass_prog.map(remove_immediate_duplicates)
utils.value_count_df(bass_prog_no_dups)
counts %
(1,) 3 15.79
(b6, 4, #5, 3, 5, b3, 4, 2, 1) 1 5.26
(1, 7, 1, #4, 5, b3, 1, b6, b7, b5, b6, 3, 1, 6, 1, #4, 1, 3, 1, b3, 1, 2, 1, b2, 5, 1) 1 5.26
(b7, 6, 4, 1, 7, b6, 5, 1) 1 5.26
(6, #1, 5, 1, 4, #1, 4, 5, 1) 1 5.26
(5, b7, 1, b7, 6, b6, 5, 1, b5, 4, 5, 1) 1 5.26
(5, #4, b3, 6, #5, #4, b6, 6, 5, b6, 4, b5, 4, b5, 4, b5, 4, b5, 5, b6, 1) 1 5.26
(b3, 7, b3, 7, b3, 7, b1, b3, 7, b3, 7, b3, 7, b7, b3, 7, b3, 7, b3, 7, 5, 2, 5, 2, b3, 5, b3, 7, b3, 7, b3, 7, 5, b1, b3, 7, b3, 7, b3, 7, b5, b7, b3, 7, b3, 7, b3, 7, 2, b5, 5, 1, 5, 1) 1 5.26
(1, 5, 1, 4, b7, b3, 4, b3, 7, 1, 4, 5, 1) 1 5.26
(1, b3, 4, 5, 1, b3, 4, b7, b3, 5, 6, b7, 7, 1, 4, 5, 1) 1 5.26
(1, 4, #4, 5, 4, b7, b3, b6, bb7, b7, 1, 2, b5, b4, 4, 1, 3, b7, 2, b6, 3, b5, 5, 1) 1 5.26
(1, b7, b2, b6, b2, 5, 1, b3, 5, b3, 1, 4, 7, 3, b7, b3, 5, b7, 4, 5, b6, b2, 4, b7, 3, b6, 1, 4, 5, 1, b3, b6, 1, 4, b6, b2, 5, 1, b6, 5, 4, b3, b2, 1, 5, 1) 1 5.26
(1, 5, b3, b7, 4, b3, b2, 5, 1) 1 5.26
(1, b3, b7, 1, b7, 4, b6, b3, b5, b2, 5, 1) 1 5.26
(1, b2, 5, 2, b2, 1, 4, 1, 4, b7, b3, 4, b4, 1, 2, 1, b7, b6, b3, b1, b7, b6, b1, 5, 1, 4, 5, 1) 1 5.26
(1, b6, 5, 1, 6, b7, b3, b7, 1, 5, 1) 1 5.26
(b3, b7, 7, 1, 4, 5, 1) 1 5.26
def progressions2graph_data(progressions, cut_at_stage=None):
    stage_nodes = defaultdict(dict)
    edge_weights = Counter()
    node_counter = 0
    for progression in progressions:
        previous_node = None
        for stage, current in enumerate(reversed(progression)):
            if cut_at_stage and stage > cut_at_stage:
                break
            if current in stage_nodes[stage]:
                current_node = stage_nodes[stage][current]
            else:
                stage_nodes[stage][current] = node_counter
                current_node = node_counter
                node_counter += 1
            if previous_node is not None:
                edge_weights.update([(current_node, previous_node)])
            previous_node = current_node
    return stage_nodes, edge_weights


def plot_progressions(progressions, cut_at_stage=None, **kwargs):
    stage_nodes, edge_weights = progressions2graph_data(
        progressions, cut_at_stage=cut_at_stage
    )
    if not stage_nodes:
        fig = px.scatter(pd.DataFrame({"x": [], "y": []}), x="x", y="y")
        fig.update_layout(
            title="No matching progressions",
            xaxis=dict(visible=False),
            yaxis=dict(visible=False),
            annotations=[dict(text="No matching progressions", x=0.5, y=0.5, xref="paper", yref="paper", showarrow=False)],
        )
        return fig
    return utils.graph_data2sankey(stage_nodes, edge_weights, **kwargs)

Chordal roots for the 3 last stages#

fig = plot_progressions(
    numeral_prog_no_dups,
    cut_at_stage=3,
    font=dict(size=30),
)
save_figure_as(fig, "last_3_roots_before_pacs_ending_on_1_sankey", height=800)
fig.show()

Complete chords for the last four stages in major#

pac_major = get_progressions("PAC", dict(numeral="I", localkey_is_minor=False), "chord")
fig = plot_progressions(pac_major, cut_at_stage=4)
save_figure_as(fig, "last_4_stages_before_pacs_in_major_sankey")
fig.show()

Bass degrees for the last 6 stages.#

fig = plot_progressions(bass_prog_no_dups, cut_at_stage=7)
save_figure_as(fig, "last_7_degrees_before_pacs_ending_on_1_sankey")
fig.show()

Bass degrees without accidentals#

def remove_sd_accidentals(t):
    return tuple(map(lambda sd: sd[-1], t))


bass_prog_no_acc_no_dup = bass_prog.map(remove_sd_accidentals).map(
    remove_immediate_duplicates
)
fig = plot_progressions(bass_prog_no_acc_no_dup, cut_at_stage=7)
save_figure_as(fig, "last_7_degrees_before_pacs_ending_on_1_without_accdentals_sankey")
fig.show()

HCs ending on V#

half = get_progressions("HC", dict(numeral="V"), "bass_note").map(ms3.fifths2sd)
print(f"Progressions for {len(half)} cadences:")
fig = plot_progressions(half.map(remove_immediate_duplicates), cut_at_stage=5)
save_figure_as(fig, "last_7_degrees_before_hcs_ending_on_V_sankey")
fig.show()
Progressions for 12 cadences: