Annotations#
Show imports
%load_ext autoreload
%autoreload 2
import os
import dimcat as dc
import ms3
import plotly.express as px
from dimcat import groupers, plotting
import utils
Show source
RESULTS_PATH = os.path.abspath(os.path.join(utils.OUTPUT_FOLDER, "overview"))
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
Show source
D = utils.get_dataset("debussy_piano", corpus_release="v0.9.1")
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("The Claude Debussy Solo Piano Corpus version v0.9.1")
print(f"Datapackage '{package.package_name}' @ {git_tag}")
print(f"dimcat version {dc.__version__}\n")
D
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
File ~/work/workflow_deployment/debussy_piano/tmp_corpus_docs/notebooks/utils.py:3604, in get_dataset.<locals>.download_if_missing(filename, filepath)
3603 url = f"https://github.com/DCMLab/{corpus_name}/{url_release_component}/{filename}"
-> 3604 urlretrieve(url, filepath)
3605 except HTTPError as e:
File /usr/lib/python3.12/urllib/request.py:240, in urlretrieve(url, filename, reporthook, data)
238 url_type, path = _splittype(url)
--> 240 with contextlib.closing(urlopen(url, data)) as fp:
241 headers = fp.info()
File /usr/lib/python3.12/urllib/request.py:215, in urlopen(url, data, timeout, cafile, capath, cadefault, context)
214 opener = _opener
--> 215 return opener.open(url, data, timeout)
File /usr/lib/python3.12/urllib/request.py:521, in OpenerDirector.open(self, fullurl, data, timeout)
520 meth = getattr(processor, meth_name)
--> 521 response = meth(req, response)
523 return response
File /usr/lib/python3.12/urllib/request.py:630, in HTTPErrorProcessor.http_response(self, request, response)
629 if not (200 <= code < 300):
--> 630 response = self.parent.error(
631 'http', request, response, code, msg, hdrs)
633 return response
File /usr/lib/python3.12/urllib/request.py:559, in OpenerDirector.error(self, proto, *args)
558 args = (dict, 'default', 'http_error_default') + orig_args
--> 559 return self._call_chain(*args)
File /usr/lib/python3.12/urllib/request.py:492, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
491 func = getattr(handler, meth_name)
--> 492 result = func(*args)
493 if result is not None:
File /usr/lib/python3.12/urllib/request.py:639, in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs)
638 def http_error_default(self, req, fp, code, msg, hdrs):
--> 639 raise HTTPError(req.full_url, code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 D = utils.get_dataset("debussy_piano", corpus_release="v0.9.1")
2 package = D.inputs.get_package()
3 package_info = package._package.custom
File ~/work/workflow_deployment/debussy_piano/tmp_corpus_docs/notebooks/utils.py:3617, in get_dataset(corpus_name, target_dir, corpus_release)
3613 zip_name, json_name = f"{corpus_name}.zip", f"{corpus_name}.datapackage.json"
3614 zip_path, json_path = os.path.join(target_dir, zip_name), os.path.join(
3615 target_dir, json_name
3616 )
-> 3617 download_if_missing(zip_name, zip_path)
3618 download_if_missing(json_name, json_path)
3619 return dc.Dataset.from_package(json_path)
File ~/work/workflow_deployment/debussy_piano/tmp_corpus_docs/notebooks/utils.py:3606, in get_dataset.<locals>.download_if_missing(filename, filepath)
3604 urlretrieve(url, filepath)
3605 except HTTPError as e:
-> 3606 raise RuntimeError(
3607 f"Retrieving {corpus_name!r}@{corpus_release!r} from {url!r} failed: {e}"
3608 ) from e
3609 assert os.path.exists(
3610 filepath
3611 ), f"An error occured and {filepath} is not available."
RuntimeError: Retrieving 'debussy_piano'@'v0.9.1' from 'https://github.com/DCMLab/debussy_piano/releases/download/v0.9.1/debussy_piano.zip' failed: HTTP Error 404: Not Found
filtered_D = D.apply_step("HasHarmonyLabelsFilter")
all_metadata = filtered_D.get_metadata()
assert len(all_metadata) > 0, "No pieces selected for analysis."
chronological_corpus_names = all_metadata.get_corpus_names()
DCML harmony labels#
Show source
all_annotations = filtered_D.get_feature("DcmlAnnotations")
is_annotated_mask = all_metadata.label_count > 0
is_annotated_index = all_metadata.index[is_annotated_mask]
annotated_notes = filtered_D.get_feature("notes").subselect(is_annotated_index)
print(f"The annotated pieces have {len(annotated_notes)} notes.")
all_chords = filtered_D.get_feature("harmonylabels")
print(
f"{len(all_annotations)} annotations, of which {len(all_chords)} are harmony labels."
)
Harmony labels#
Unigrams#
For computing unigram statistics, the tokens need to be grouped by their occurrence within a major or a minor key
because this changes their meaning. To that aim, the annotated corpus needs to be sliced into contiguous localkey
segments which are then grouped into a major (is_minor=False
) and a minor group.
root_durations = (
all_chords[all_chords.root.between(-5, 6)]
.groupby(["root", "chord_type"])
.duration_qb.sum()
)
# sort by stacked bar length:
# root_durations = root_durations.sort_values(key=lambda S: S.index.get_level_values(0).map(S.groupby(level=0).sum()),
# ascending=False)
bar_data = root_durations.reset_index()
bar_data.root = bar_data.root.map(ms3.fifths2iv)
fig = px.bar(
bar_data,
x="root",
y="duration_qb",
color="chord_type",
title="Distribution of chord types over chord roots",
labels=dict(
root="Chord root expressed as interval above the local (or secondary) tonic",
duration_qb="duration in quarter notes",
chord_type="chord type",
),
)
fig.update_layout(**utils.STD_LAYOUT)
save_figure_as(fig, "chord_type_distribution_over_scale_degrees_absolute_stacked_bars")
fig.show()
relative_roots = all_chords[
["numeral", "duration_qb", "relativeroot", "localkey_is_minor", "chord_type"]
].copy()
relative_roots["relativeroot_resolved"] = ms3.transform(
relative_roots, ms3.resolve_relative_keys, ["relativeroot", "localkey_is_minor"]
)
has_rel = relative_roots.relativeroot_resolved.notna()
relative_roots.loc[has_rel, "localkey_is_minor"] = relative_roots.loc[
has_rel, "relativeroot_resolved"
].str.islower()
relative_roots["root"] = ms3.transform(
relative_roots, ms3.roman_numeral2fifths, ["numeral", "localkey_is_minor"]
)
chord_type_frequency = all_chords.chord_type.value_counts()
replace_rare = ms3.map_dict(
{t: "other" for t in chord_type_frequency[chord_type_frequency < 500].index}
)
relative_roots["type_reduced"] = relative_roots.chord_type.map(replace_rare)
# is_special = relative_roots.chord_type.isin(('It', 'Ger', 'Fr'))
# relative_roots.loc[is_special, 'root'] = -4
root_durations = (
relative_roots.groupby(["root", "type_reduced"])
.duration_qb.sum()
.sort_values(ascending=False)
)
bar_data = root_durations.reset_index()
bar_data.root = bar_data.root.map(ms3.fifths2iv)
root_order = (
bar_data.groupby("root")
.duration_qb.sum()
.sort_values(ascending=False)
.index.to_list()
)
fig = px.bar(
bar_data,
x="root",
y="duration_qb",
color="type_reduced",
barmode="group",
log_y=True,
color_discrete_map=utils.TYPE_COLORS,
category_orders=dict(
root=root_order,
type_reduced=relative_roots.type_reduced.value_counts().index.to_list(),
),
labels=dict(
root="intervallic difference between chord root to the local or secondary tonic",
duration_qb="duration in quarter notes",
type_reduced="chord type",
),
width=1000,
height=400,
)
fig.update_layout(
**utils.STD_LAYOUT,
legend=dict(
orientation="h",
xanchor="right",
x=1,
y=1,
),
)
save_figure_as(fig, "chord_type_distribution_over_scale_degrees_absolute_grouped_bars")
fig.show()
print(
f"Reduced to {len(set(bar_data.iloc[:,:2].itertuples(index=False, name=None)))} types. "
f"Paper cites the sum of types in major and types in minor (see below), treating them as distinct."
)
dim_or_aug = bar_data[
bar_data.root.str.startswith("a") | bar_data.root.str.startswith("d")
].duration_qb.sum()
complete = bar_data.duration_qb.sum()
print(
f"On diminished or augmented scale degrees: {dim_or_aug} / {complete} = {dim_or_aug / complete}"
)
chords_by_mode = groupers.ModeGrouper().process(all_chords)
chords_by_mode.format = "scale_degree"
Whole dataset#
unigram_proportions = chords_by_mode.get_default_analysis()
unigram_proportions.make_ranking_table()
chords_by_mode.apply_step("Counter")
chords_by_mode.format = "scale_degree"
chords_by_mode.get_default_analysis().make_ranking_table()
unigram_proportions.plot_grouped()