diff --git a/homepage/.nojekyll b/homepage/.nojekyll
new file mode 100644
index 0000000..e69de29
diff --git a/homepage/Makefile b/homepage/Makefile
new file mode 100644
index 0000000..ed88099
--- /dev/null
+++ b/homepage/Makefile
@@ -0,0 +1,20 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS ?=
+SPHINXBUILD ?= sphinx-build
+SOURCEDIR = .
+BUILDDIR = build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/homepage/README.md b/homepage/README.md
new file mode 100644
index 0000000..1b87752
--- /dev/null
+++ b/homepage/README.md
@@ -0,0 +1,32 @@
+# corpus_docs
+Sphinx project template to create a corpus documentation homepage including rendered Jupytext notebooks
+
+## Usage
+
+
+1. `git clone --recurse-submodules git@github.com:DCMLab/corpus_docs.git` will include https://github.com/DCMLab/data_reports
+ as the submodule `notebooks`
+1. `pip install -r requirements.txt` will install the requirements for both the Sphinx project and the notebooks.
+1. [set the environment variable] `CORPUS_PATH` to the path where the corpus repo or metarepo is located
+1. [set the environment variable] `ANNOTATED_ONLY` to one of `false|f|0` if non-annotated files are to be included
+1. `make html` builds the homepage which you can view at `_build/html/index.html`.
+
+## Next steps
+
+This sphinx project includes that need to be completed using the Jinja templating library: https://realpython.com/primer-on-jinja-templating/
+Currently these placeholders include:
+* `repo_name`: repository name as in the URLs, e.g. `beethoven_piano_sonatas`
+* `pretty_repo_name`: title, e.g. `Ludwig van Beethoven - The piano sonatas`
+* `zenodo_badge_id`: ID assigned by Zenodo to ensure that the badge always shows the DOI of the latest version.
+* `example_fname`: one of the pieces' file names (without extension) to be used in the docs (e.g. for file paths)
+* `example_full_title`: full title of the example, to be included in the text, e.g. `the first movement of the first sonata Op. 2 no. 1`
+* `example_subcorpus`: (only for meta-corpora) name of the submodule to which the example belongs
+
+The `index.rst` includes the file `repo_readme.md` which is a dummy file. During the actual building it should be
+replaced by the actual README of the repo. Nevertheless, the dummy could be used to create this README from the
+placeholder variables.
+
+`introduction.rst` requires that for metarepos (which include submodules), the `git clone` command be extended with `--recurse-submodules -j8`
+
+`analyses.rst` needs to be adapted such that non-annotated repos (setting yet to be introduced), the `annotations` and `cadences` notebooks are not included.
+Could also be done with two different .rst files for each of the cases.
\ No newline at end of file
diff --git a/homepage/_static/custom.css b/homepage/_static/custom.css
new file mode 100644
index 0000000..7564589
--- /dev/null
+++ b/homepage/_static/custom.css
@@ -0,0 +1,9 @@
+.bd-main .bd-content .bd-article-container {
+ max-width: 100%; /* default is 60em */
+}
+.bd-page-width {
+ max-width: 100%; /* maximizes overall horizontal space */
+}
+.bd-sidebar-primary {
+ max-width: var(--pst-sidebar-secondary); /* same maximal width for the left side bar as for the right one */
+}
\ No newline at end of file
diff --git a/homepage/analyses.rst b/homepage/analyses.rst
new file mode 100644
index 0000000..ee63cd1
--- /dev/null
+++ b/homepage/analyses.rst
@@ -0,0 +1,14 @@
+********
+Analyses
+********
+
+The following notebooks contain a couple of standard analysis and have been rendered for
+display as a static homepage:
+
+.. toctree::
+ :maxdepth: 2
+ :caption: Contents:
+
+ notebooks/overview
+ notebooks/notes_stats
+
diff --git a/homepage/conf.py b/homepage/conf.py
new file mode 100644
index 0000000..aa331d1
--- /dev/null
+++ b/homepage/conf.py
@@ -0,0 +1,45 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+
+project = "Claude Debussy – Préludes"
+copyright = '2023, Johannes Hentschel'
+author = 'Johannes Hentschel'
+release = 'v0.9.1'
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = [
+ "myst_nb", # rendering Jupyter notebooks
+ "jupyter_sphinx", # rendering interactive Plotly in notebooks
+]
+
+templates_path = ['_templates']
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '**README.md']
+
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = 'pydata_sphinx_theme'
+html_static_path = ['_static']
+
+html_css_files = [
+ 'custom.css',
+]
+
+# -- MyST Notebook configuration-----------------------------------------------
+# https://myst-nb.readthedocs.io/en/latest/configuration.html
+
+nb_execution_mode = "cache"
+nb_execution_timeout = 300
+nb_execution_allow_errors = False
+nb_execution_show_tb = True
+# toggle text:
+nb_code_prompt_show = "Show {type}"
+nb_code_prompt_hide = "Hide {type}"
\ No newline at end of file
diff --git a/homepage/index.rst b/homepage/index.rst
new file mode 100644
index 0000000..8f00d45
--- /dev/null
+++ b/homepage/index.rst
@@ -0,0 +1,13 @@
+.. contents:: README
+ :local:
+
+.. include:: repo_readme.md
+ :parser: myst_parser.sphinx_
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Further information:
+
+ introduction
+ analyses
+
diff --git a/homepage/introduction.rst b/homepage/introduction.rst
new file mode 100644
index 0000000..e919f6d
--- /dev/null
+++ b/homepage/introduction.rst
@@ -0,0 +1,184 @@
+**********
+How to use
+**********
+
+.. contents:: Contents
+ :local:
+
+Getting the data
+================
+
+With full version history
+-------------------------
+
+The dataset is version-controlled via `git `__. In order to download the files with all revisions they have gone through, git needs to be installed on your machine.
+Then you can clone this repository using the command
+
+.. code:: bash
+
+
+ git clone https://github.com/DCMLab/debussy_preludes.git
+
+
+Without full version history
+----------------------------
+
+
+If you are only interested in the current version of the corpus, you can download and unpack:
+
+* `Claude Debussy – Préludes `__
+
+
+Data Formats
+============
+
+Each piece in this corpus is represented by four files with identical names, each in its own folder. For example, the first prelude from the first book, *Danseuses de Delphes*, has the following files:
+
+- ``MS3/l117-01_preludes_danseuses.mscx``: Uncompressed MuseScore file including the music and annotation labels.
+- ``notes/l117-01_preludes_danseuses.tsv``: A table of all note heads contained in the score and their relevant features (not each of them represents an onset, some are tied together)
+- ``measures/l117-01_preludes_danseuses.tsv``: A table with relevant information about the measures in the score.
+- ``harmonies/l117-01_preludes_danseuses.tsv``: A list of the included harmony labels (including cadences and phrases) with their positions in the score.
+
+Opening Scores
+--------------
+
+After navigating to your local copy, you can open the scores in the folder ``MS3`` with the free and open source score editor `MuseScore `__. Please note that the scores have been edited, annotated and tested with `MuseScore 3.6.2 `__. MuseScore 4 has since been released and preliminary tests suggest that it renders them correctly.
+
+Opening TSV files in a spreadsheet
+----------------------------------
+
+Tab-separated value (TSV) files are like Comma-separated value (CSV) files and can be opened with most modern text editors. However, for correctly displaying the columns, you might want to use a spreadsheet or an addon for your favourite text editor. When you use a spreadsheet such as Excel, it might annoy you by interpreting fractions as dates. This can be circumvented by using ``Data --> From Text/CSV`` or the free alternative `LibreOffice Calc `__. Other than that, TSV data can be loaded with every modern programming language.
+
+Loading TSV files in Python
+---------------------------
+
+Since the TSV files contain null values, lists, fractions, and numbers that are to be treated as strings, you may want to use this code to load any TSV files related to this repository (provided you’re doing it in Python). After a quick ``pip install -U ms3`` (requires Python 3.10) you’ll be able to load any TSV like this:
+
+.. code:: python
+
+ import ms3
+
+ labels = ms3.load_tsv('harmonies/l117-01_preludes_danseuses.tsv')
+ notes = ms3.load_tsv('notes/l117-01_preludes_danseuses.tsv')
+
+How to read ``metadata.tsv``
+============================
+
+This section explains the meaning of the columns contained in ``metadata.tsv``.
+
+File information
+----------------
+
++------------------------+------------------------------------------------------------+
+| column | content |
++========================+============================================================+
+| **fname** | name without extension (for referencing related files) |
++------------------------+------------------------------------------------------------+
+| **rel_path** | relative file path of the score, including extension |
++------------------------+------------------------------------------------------------+
+| **subdirectory** | folder where the score is located |
++------------------------+------------------------------------------------------------+
+| **last_mn** | last measure number |
++------------------------+------------------------------------------------------------+
+| **last_mn_unfolded** | number of measures when playing all repeats |
++------------------------+------------------------------------------------------------+
+| **length_qb** | length of the piece, measured in quarter notes |
++------------------------+------------------------------------------------------------+
+| **length_qb_unfolded** | length of the piece when playing all repeats |
++------------------------+------------------------------------------------------------+
+| **volta_mcs** | measure counts of first and second endings |
++------------------------+------------------------------------------------------------+
+| **all_notes_qb** | summed up duration of all notes, measured in quarter notes |
++------------------------+------------------------------------------------------------+
+| **n_onsets** | number of note onsets |
++------------------------+------------------------------------------------------------+
+| **n_onset_positions** | number of unique note onsets (“slices”) |
++------------------------+------------------------------------------------------------+
+
+Composition information
+-----------------------
+
++--------------------+---------------------------+
+| column | content |
++====================+===========================+
+| **composer** | composer name |
++--------------------+---------------------------+
+| **workTitle** | work title |
++--------------------+---------------------------+
+| **composed_start** | earliest composition date |
++--------------------+---------------------------+
+| **composed_end** | latest composition date |
++--------------------+---------------------------+
+| **workNumber** | Catalogue number(s) |
++--------------------+---------------------------+
+| **movementNumber** | 1, 2, or 3 |
++--------------------+---------------------------+
+| **movementTitle** | title of the movement |
++--------------------+---------------------------+
+
+Score information
+-----------------
+
++-----------------+--------------------------------------------------------+
+| column | content |
++=================+========================================================+
+| **label_count** | number of chord labels |
++-----------------+--------------------------------------------------------+
+| **KeySig** | key signature(s) (negative = flats, positive = sharps) |
++-----------------+--------------------------------------------------------+
+| **TimeSig** | time signature(s) |
++-----------------+--------------------------------------------------------+
+| **musescore** | MuseScore version |
++-----------------+--------------------------------------------------------+
+| **source** | URL to the first typesetter’s file |
++-----------------+--------------------------------------------------------+
+| **typesetter** | first typesetter |
++-----------------+--------------------------------------------------------+
+| **annotators** | creator(s) of the chord labels |
++-----------------+--------------------------------------------------------+
+| **reviewers** | reviewer(s) of the chord labels |
++-----------------+--------------------------------------------------------+
+
+Identifiers
+-----------
+
+These columns provide a mapping between multiple identifiers for the sonatas (not for individual movements).
+
++-----------------+------------------------------------------------------------------------------------------------------------+
+| column | content |
++=================+============================================================================================================+
+| **wikidata** | URL of the `WikiData `__ item |
++-----------------+------------------------------------------------------------------------------------------------------------+
+| **viaf** | URL of the Virtual International Authority File (`VIAF `__) entry |
++-----------------+------------------------------------------------------------------------------------------------------------+
+| **musicbrainz** | `MusicBrainz `__ identifier |
++-----------------+------------------------------------------------------------------------------------------------------------+
+| **imslp** | URL to the wiki page within the International Music Score Library Project (`IMSLP `__) |
++-----------------+------------------------------------------------------------------------------------------------------------+
+
+Generating all TSV files from the scores
+========================================
+
+When you have made changes to the scores and want to update the TSV files accordingly, you can use the following command (provided you have pip-installed `ms3 `__):
+
+.. code:: python
+
+ ms3 extract -M -N -X -F -D # for measures, notes, expanded harmony labels, form labels, and metadata
+
+If, in addition, you want to generate the reviewed scores with out-of-label notes colored in red, you can do
+
+.. code:: python
+
+ ms3 review -M -N -X -F -D # for extracting measures, notes, expanded harmony labels, form labels, and metadata
+
+By adding the flag ``-c`` to the review command, it will additionally compare the (potentially modified) annotations in the score with the ones currently present in the harmonies TSV files and reflect the comparison in the reviewed scores.
+
+Questions, Suggestions, Corrections, Bug Reports
+================================================
+
+For questions, remarks etc., please `create an issue `__ and feel free to fork and submit pull requests.
+
+License
+=======
+
+Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (`CC BY-NC-SA 4.0 `__).
\ No newline at end of file
diff --git a/homepage/make.bat b/homepage/make.bat
new file mode 100644
index 0000000..207019d
--- /dev/null
+++ b/homepage/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=.
+set BUILDDIR=build
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.https://www.sphinx-doc.org/
+ exit /b 1
+)
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+
+:end
+popd
diff --git a/homepage/notebooks/LICENSE b/homepage/notebooks/LICENSE
new file mode 100644
index 0000000..0ad25db
--- /dev/null
+++ b/homepage/notebooks/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/homepage/notebooks/README.md b/homepage/notebooks/README.md
new file mode 100644
index 0000000..703a54c
--- /dev/null
+++ b/homepage/notebooks/README.md
@@ -0,0 +1,23 @@
+# Data reports: Code for generating figures and tables
+
+This repo contains five Jupyter notebooks in [{MySt}NB](https://myst-nb.readthedocs.io/en/latest/)
+Markdown format. They can be opend in Jupyter Notebook or Lab using the
+[Jupytext](https://jupytext.readthedocs.io/) extension. We use this format because
+
+* Jupytext notebooks are great for version control
+* MyST-flavoured can be integrated in a [Sphinx](https://www.sphinx-doc.org/) homepage and treated
+ like any other document
+
+## Running the notebooks
+
+* clone the corpus: `git clone --recurse-submodules -j8 git@github.com:DCMLab/dcml_corpora.git`
+* create new environment, make it visible to your Jupyter
+ * for conda do `conda create --name {name} python=3.10`
+ * activate it and install `pip install ipykernel`
+ * `ipython kernel install --user --name={name}`
+* within the new environment, install requirements, e.g. `pip install -r requirements.txt`
+* open up jupyter notebook or jupyter lab and open the `.md`
+ ([documentation](https://jupytext.readthedocs.io/en/latest/paired-notebooks.html#how-to-open-scripts-with-either-the-text-or-notebook-view-in-jupyter))
+* change the value `~/dcml_corpora` in the second cell to your local clone.
+
+If the plots are not displayed and you are in JupyterLab, use [this guide](https://plotly.com/python/getting-started/#jupyterlab-support).
\ No newline at end of file
diff --git a/homepage/notebooks/annotations.md b/homepage/notebooks/annotations.md
new file mode 100644
index 0000000..7d9246e
--- /dev/null
+++ b/homepage/notebooks/annotations.md
@@ -0,0 +1,575 @@
+---
+jupytext:
+ formats: md:myst,ipynb
+ text_representation:
+ extension: .md
+ format_name: myst
+ format_version: 0.13
+ jupytext_version: 1.15.0
+kernelspec:
+ display_name: corpus_docs
+ language: python
+ name: corpus_docs
+---
+
+# Annotations
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide imports
+ code_prompt_show: Show imports
+tags: [hide-cell]
+---
+import os
+from collections import defaultdict, Counter
+from fractions import Fraction
+
+from git import Repo
+import dimcat as dc
+import ms3
+import pandas as pd
+import plotly.express as px
+import plotly.graph_objects as go
+
+from utils import STD_LAYOUT, CADENCE_COLORS, CORPUS_COLOR_SCALE, TYPE_COLORS, chronological_corpus_order, color_background, corpus_mean_composition_years, get_corpus_display_name, get_repo_name, resolve_dir, value_count_df, get_repo_name, print_heading, resolve_dir
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+CORPUS_PATH = os.path.abspath(os.path.join('..', '..'))
+print_heading("Notebook settings")
+print(f"CORPUS_PATH: {CORPUS_PATH!r}")
+CORPUS_PATH = resolve_dir(CORPUS_PATH)
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+repo = Repo(CORPUS_PATH)
+print_heading("Data and software versions")
+print(f"Data repo '{get_repo_name(repo)}' @ {repo.commit().hexsha[:7]}")
+print(f"dimcat version {dc.__version__}")
+print(f"ms3 version {ms3.__version__}")
+```
+
+```{code-cell} ipython3
+:tags: [remove-output]
+
+dataset = dc.Dataset()
+dataset.load(directory=CORPUS_PATH, parse_tsv=False)
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+annotated_view = dataset.data.get_view('annotated')
+annotated_view.include('facets', 'measures', 'notes$', 'expanded')
+annotated_view.fnames_with_incomplete_facets = False
+dataset.data.set_view(annotated_view)
+dataset.data.parse_tsv(choose='auto')
+dataset.get_indices()
+dataset.data
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+print(f"N = {dataset.data.count_pieces()} annotated pieces, {dataset.data.count_parsed_tsvs()} parsed dataframes.")
+```
+
+```{code-cell} ipython3
+all_metadata = dataset.data.metadata()
+assert len(all_metadata) > 0, "No pieces selected for analysis."
+print(f"Metadata covers {len(all_metadata)} of the {dataset.data.count_pieces()} scores.")
+mean_composition_years = corpus_mean_composition_years(all_metadata)
+chronological_order = mean_composition_years.index.to_list()
+corpus_colors = dict(zip(chronological_order, CORPUS_COLOR_SCALE))
+corpus_names = {corp: get_corpus_display_name(corp) for corp in chronological_order}
+chronological_corpus_names = list(corpus_names.values())
+corpus_name_colors = {corpus_names[corp]: color for corp, color in corpus_colors.items()}
+```
+
+## DCML harmony labels
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+try:
+ all_annotations = dataset.get_facet('expanded')
+except Exception:
+ all_annotations = pd.DataFrame()
+n_annotations = len(all_annotations.index)
+includes_annotations = n_annotations > 0
+if includes_annotations:
+ display(all_annotations.head())
+ print(f"Concatenated annotation tables contain {all_annotations.shape[0]} rows.")
+ no_chord = all_annotations.root.isna()
+ if no_chord.sum() > 0:
+ print(f"{no_chord.sum()} of them are not chords. Their values are: {all_annotations.label[no_chord].value_counts(dropna=False).to_dict()}")
+ all_chords = all_annotations[~no_chord].copy()
+ print(f"Dataset contains {all_chords.shape[0]} tokens and {len(all_chords.chord.unique())} types over {len(all_chords.groupby(level=[0,1]))} documents.")
+ all_annotations['corpus_name'] = all_annotations.index.get_level_values(0).map(corpus_names)
+ all_chords['corpus_name'] = all_chords.index.get_level_values(0).map(corpus_names)
+else:
+ print(f"Dataset contains no annotations.")
+```
+
+## Phrases
+### Presence of phrase annotation symbols per dataset:
+
+```{code-cell} ipython3
+all_annotations.groupby(["corpus"]).phraseend.value_counts()
+```
+
+### Presence of legacy phrase endings
+
+```{code-cell} ipython3
+legacy = all_annotations[all_annotations.phraseend == r'\\']
+legacy.groupby(level=0).size()
+```
+
+### A table with the extents of all annotated phrases
+**Relevant columns:**
+* `quarterbeats`: start position for each phrase
+* `duration_qb`: duration of each phrase, measured in quarter notes
+* `phrase_slice`: time interval of each annotated phrases (for segmenting chord progressions and notes)
+
+```{code-cell} ipython3
+phrase_segmented = dc.PhraseSlicer().process_data(dataset)
+phrases = phrase_segmented.get_slice_info()
+print(f"Overall number of phrases is {len(phrases.index)}")
+phrases.head(10).style.apply(color_background, subset=["quarterbeats", "duration_qb"])
+```
+
+### A table with the chord sequences of all annotated phrases
+
+```{code-cell} ipython3
+phrase_segments = phrase_segmented.get_facet('expanded')
+phrase_segments
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+phrase2timesigs = phrase_segments.groupby(level=[0,1,2]).timesig.unique()
+n_timesignatures_per_phrase = phrase2timesigs.map(len)
+uniform_timesigs = phrase2timesigs[n_timesignatures_per_phrase == 1].map(lambda l: l[0])
+more_than_one = n_timesignatures_per_phrase > 1
+print(f"Filtered out the {more_than_one.sum()} phrases incorporating more than one time signature.")
+n_timesigs = n_timesignatures_per_phrase.value_counts()
+display(n_timesigs.reset_index().rename(columns=dict(index='#time signatures', timesig='#phrases')))
+uniform_timesig_phrases = phrases.loc[uniform_timesigs.index]
+timesig_in_quarterbeats = uniform_timesigs.map(Fraction) * 4
+exact_measure_lengths = uniform_timesig_phrases.duration_qb / timesig_in_quarterbeats
+uniform_timesigs = pd.concat([exact_measure_lengths.rename('duration_measures'), uniform_timesig_phrases], axis=1)
+fig = px.histogram(uniform_timesigs, x='duration_measures', log_y=True,
+ labels=dict(duration_measures='phrase length bin in number of measures'),
+ color_discrete_sequence=CORPUS_COLOR_SCALE,
+ )
+fig.update_traces(xbins=dict( # bins used for histogram
+ #start=0.0,
+ #end=100.0,
+ size=1
+ ))
+fig.update_layout(**STD_LAYOUT)
+fig.update_xaxes(dtick=4, gridcolor='lightgrey')
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+### Local keys per phrase
+
+```{code-cell} ipython3
+local_keys_per_phrase = phrase_segments.groupby(level=[0,1,2]).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_keys.head(10).style.apply(color_background, subset=['n_local_keys', 'local_keys'])
+```
+
+#### Number of unique local keys per phrase
+
+```{code-cell} ipython3
+count_n_keys = phrases_with_keys.n_local_keys.value_counts().rename("#phrases").to_frame()
+count_n_keys.index.rename("unique keys", inplace=True)
+count_n_keys
+```
+
+#### The most frequent keys for non-modulating phrases
+
+```{code-cell} ipython3
+unique_key_selector = phrases_with_keys.n_local_keys == 1
+phrases_with_unique_key = phrases_with_keys[unique_key_selector].copy()
+phrases_with_unique_key.local_keys = phrases_with_unique_key.local_keys.map(lambda t: t[0])
+value_count_df(phrases_with_unique_key.local_keys, counts="#phrases")
+```
+
+#### Most frequent modulations within one phrase
+
+```{code-cell} ipython3
+two_keys_selector = phrases_with_keys.n_local_keys > 1
+phrases_with_unique_key = phrases_with_keys[two_keys_selector].copy()
+value_count_df(phrases_with_unique_key.local_keys, "modulations")
+```
+
+## Key areas
+
+```{code-cell} ipython3
+from ms3 import roman_numeral2fifths, transform, resolve_all_relative_numerals, replace_boolean_mode_by_strings
+keys_segmented = dc.LocalKeySlicer().process_data(dataset)
+keys = keys_segmented.get_slice_info()
+print(f"Overall number of key segments is {len(keys.index)}")
+keys["localkey_fifths"] = transform(keys, roman_numeral2fifths, ['localkey', 'globalkey_is_minor'])
+keys.head(5).style.apply(color_background, subset="localkey")
+```
+
+### Durational distribution of local keys
+
+All durations given in quarter notes
+
+```{code-cell} ipython3
+key_durations = keys.groupby(['globalkey_is_minor', 'localkey']).duration_qb.sum().sort_values(ascending=False)
+print(f"{len(key_durations)} keys overall including hierarchical such as 'III/v'.")
+```
+
+```{code-cell} ipython3
+keys_resolved = resolve_all_relative_numerals(keys)
+key_resolved_durations = keys_resolved.groupby(['globalkey_is_minor', 'localkey']).duration_qb.sum().sort_values(ascending=False)
+print(f"{len(key_resolved_durations)} keys overall after resolving hierarchical ones.")
+key_resolved_durations
+```
+
+#### Distribution of local keys for piece in major and in minor
+
+`globalkey_mode=minor` => Piece is in Minor
+
+```{code-cell} ipython3
+pie_data = replace_boolean_mode_by_strings(key_resolved_durations.reset_index())
+px.pie(pie_data, names='localkey', values='duration_qb', facet_col='globalkey_mode')
+```
+
+#### Distribution of intervals between localkey tonic and global tonic
+
+```{code-cell} ipython3
+localkey_fifths_durations = keys.groupby(['localkey_fifths', 'localkey_is_minor']).duration_qb.sum()
+bar_data = replace_boolean_mode_by_strings(localkey_fifths_durations.reset_index())
+bar_data.localkey_fifths = bar_data.localkey_fifths.map(ms3.fifths2iv)
+fig = px.bar(bar_data, x='localkey_fifths', y='duration_qb', color='localkey_mode', log_y=True, barmode='group',
+ labels=dict(localkey_fifths='Roots of local keys as intervallic distance from the global tonic',
+ duration_qb='total duration in quarter notes',
+ localkey_mode='mode'
+ ),
+ color_discrete_sequence=CORPUS_COLOR_SCALE,
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+### Ratio between major and minor key segments by aggregated durations
+#### Overall
+
+```{code-cell} ipython3
+keys.duration_qb = pd.to_numeric(keys.duration_qb)
+maj_min_ratio = keys.groupby("localkey_is_minor").duration_qb.sum().to_frame()
+maj_min_ratio['fraction'] = (100.0 * maj_min_ratio.duration_qb / maj_min_ratio.duration_qb.sum()).round(1)
+maj_min_ratio
+```
+
+#### By dataset
+
+```{code-cell} ipython3
+segment_duration_per_dataset = keys.groupby(["corpus", "localkey_is_minor"]).duration_qb.sum().round(2)
+norm_segment_duration_per_dataset = 100 * segment_duration_per_dataset / segment_duration_per_dataset.groupby(level="corpus").sum()
+maj_min_ratio_per_dataset = pd.concat([segment_duration_per_dataset,
+ norm_segment_duration_per_dataset.rename('fraction').round(1).astype(str)+" %"],
+ axis=1)
+maj_min_ratio_per_dataset['corpus_name'] = maj_min_ratio_per_dataset.index.get_level_values('corpus').map(corpus_names)
+maj_min_ratio_per_dataset['mode'] = maj_min_ratio_per_dataset.index.get_level_values('localkey_is_minor').map({False: 'major', True: 'minor'})
+```
+
+```{code-cell} ipython3
+fig = px.bar(maj_min_ratio_per_dataset.reset_index(),
+ x="corpus_name",
+ y="duration_qb",
+ color="mode",
+ text='fraction',
+ labels=dict(dataset='', duration_qb="duration in 𝅘𝅥", corpus_name='Key segments grouped by corpus'),
+ category_orders=dict(dataset=chronological_order)
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.show()
+```
+
+### Tone profiles for all major and minor local keys
+
+```{code-cell} ipython3
+notes_by_keys = keys_segmented.get_facet("notes")
+notes_by_keys
+```
+
+```{code-cell} ipython3
+keys = keys[[col for col in keys.columns if col not in notes_by_keys]]
+notes_joined_with_keys = notes_by_keys.join(keys, on=keys.index.names)
+notes_by_keys_transposed = ms3.transpose_notes_to_localkey(notes_joined_with_keys)
+mode_tpcs = notes_by_keys_transposed.reset_index(drop=True).groupby(['localkey_is_minor', 'tpc']).duration_qb.sum().reset_index(-1).sort_values('tpc').reset_index()
+mode_tpcs['sd'] = ms3.fifths2sd(mode_tpcs.tpc)
+mode_tpcs['duration_pct'] = mode_tpcs.groupby('localkey_is_minor', group_keys=False).duration_qb.apply(lambda S: S / S.sum())
+mode_tpcs['mode'] = mode_tpcs.localkey_is_minor.map({False: 'major', True: 'minor'})
+```
+
+```{code-cell} ipython3
+#mode_tpcs = mode_tpcs[mode_tpcs['duration_pct'] > 0.001]
+#sd_order = ['b1', '1', '#1', 'b2', '2', '#2', 'b3', '3', 'b4', '4', '#4', '##4', 'b5', '5', '#5', 'b6','6', '#6', 'b7', '7']
+xaxis = dict(
+ tickmode = 'array',
+ tickvals = mode_tpcs.tpc,
+ ticktext = mode_tpcs.sd
+ )
+legend=dict(
+ yanchor="top",
+ y=0.99,
+ xanchor="right",
+ x=0.99
+)
+fig = px.bar(mode_tpcs,
+ x='tpc',
+ y='duration_pct',
+ color='mode',
+ barmode='group',
+ labels=dict(duration_pct='normalized duration',
+ tpc="Notes transposed to the local key, as major-scale degrees",
+ ),
+ #log_y=True,
+ #category_orders=dict(sd=sd_order)
+ )
+fig.update_layout(**STD_LAYOUT, xaxis=xaxis, legend=legend)
+fig.show()
+```
+
+## 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.
+
+```{code-cell} ipython3
+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)
+px.bar(bar_data, x='root', y='duration_qb', color='chord_type')
+```
+
+```{code-cell} ipython3
+relative_roots = all_chords[['numeral', 'duration_qb', 'relativeroot', 'localkey_is_minor', 'chord_type']].copy()
+relative_roots['relativeroot_resolved'] = 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'] = transform(relative_roots, 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
+```
+
+```{code-cell} ipython3
+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=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(**STD_LAYOUT,
+ legend=dict(
+ orientation='h',
+ xanchor="right",
+ x=1,
+ y=1,
+ )
+ )
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+```{code-cell} ipython3
+print(f"Reduced to {len(set(bar_data.iloc[:,:2].itertuples(index=False, name=None)))} types. Paper cites the sum of types in major and types in minor (see below), treating them as distinct.")
+```
+
+```{code-cell} ipython3
+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}")
+```
+
+```{code-cell} ipython3
+mode_slices = dc.ModeGrouper().process_data(keys_segmented)
+```
+
+### Whole dataset
+
+```{code-cell} ipython3
+mode_slices.get_slice_info()
+```
+
+```{code-cell} ipython3
+unigrams = dc.ChordSymbolUnigrams(once_per_group=True).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+unigrams.group2pandas = "group_of_series2series"
+```
+
+```{code-cell} ipython3
+unigrams.get(as_pandas=True)
+```
+
+```{code-cell} ipython3
+k = 20
+modes = {True: 'MINOR', False: 'MAJOR'}
+for (is_minor,), ugs in unigrams.iter():
+ print(f"TOP {k} {modes[is_minor]} UNIGRAMS\n{ugs.shape[0]} types, {ugs.sum()} tokens")
+ print(ugs.head(k).to_string())
+```
+
+```{code-cell} ipython3
+ugs_dict = {modes[is_minor].lower(): (ugs/ugs.sum() * 100).round(2).rename('%').reset_index() for (is_minor,), ugs in unigrams.iter()}
+ugs_df = pd.concat(ugs_dict, axis=1)
+ugs_df.columns = ['_'.join(map(str, col)) for col in ugs_df.columns]
+ugs_df.index = (ugs_df.index + 1).rename('k')
+print(ugs_df.iloc[:50].to_markdown())
+```
+
+### Per corpus
+
+```{code-cell} ipython3
+corpus_wise_unigrams = dc.Pipeline([dc.CorpusGrouper(), dc.ChordSymbolUnigrams(once_per_group=True)]).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+corpus_wise_unigrams.get()
+```
+
+```{code-cell} ipython3
+for (is_minor, corpus_name), ugs in corpus_wise_unigrams.iter():
+ print(f"{corpus_name} {modes[is_minor]} unigrams ({ugs.shape[0]} types, {ugs.sum()} tokens)")
+ print(ugs.head(5).to_string())
+```
+
+```{code-cell} ipython3
+types_shared_between_corpora = {}
+for (is_minor, corpus_name), ugs in corpus_wise_unigrams.iter():
+ if is_minor in types_shared_between_corpora:
+ types_shared_between_corpora[is_minor] = types_shared_between_corpora[is_minor].intersection(ugs.index)
+ else:
+ types_shared_between_corpora[is_minor] = set(ugs.index)
+types_shared_between_corpora = {k: sorted(v, key=lambda x: unigrams.get()[(k, x)], reverse=True) for k, v in types_shared_between_corpora.items()}
+n_types = {k: len(v) for k, v in types_shared_between_corpora.items()}
+print(f"Chords which occur in all corpora, sorted by descending global frequency:\n{types_shared_between_corpora}\nCounts: {n_types}")
+```
+
+### Per piece
+
+```{code-cell} ipython3
+piece_wise_unigrams = dc.Pipeline([dc.PieceGrouper(), dc.ChordSymbolUnigrams(once_per_group=True)]).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+piece_wise_unigrams.get()
+```
+
+```{code-cell} ipython3
+types_shared_between_pieces = {}
+for (is_minor, corpus_name), ugs in piece_wise_unigrams.iter():
+ if is_minor in types_shared_between_pieces:
+ types_shared_between_pieces[is_minor] = types_shared_between_pieces[is_minor].intersection(ugs.index)
+ else:
+ types_shared_between_pieces[is_minor] = set(ugs.index)
+print(types_shared_between_pieces)
+```
+
+## Bigrams
+
++++
+
+### Whole dataset
+
+```{code-cell} ipython3
+bigrams = dc.ChordSymbolBigrams(once_per_group=True).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+bigrams.get()
+```
+
+```{code-cell} ipython3
+modes = {True: 'MINOR', False: 'MAJOR'}
+for (is_minor,), ugs in bigrams.iter():
+ print(f"{modes[is_minor]} BIGRAMS\n{ugs.shape[0]} transition types, {ugs.sum()} tokens")
+ print(ugs.head(20).to_string())
+```
+
+### Per corpus
+
+```{code-cell} ipython3
+corpus_wise_bigrams = dc.Pipeline([dc.CorpusGrouper(), dc.ChordSymbolBigrams(once_per_group=True)]).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+corpus_wise_bigrams.get()
+```
+
+```{code-cell} ipython3
+for (is_minor, corpus_name), ugs in corpus_wise_bigrams.iter():
+ print(f"{corpus_name} {modes[is_minor]} bigrams ({ugs.shape[0]} transition types, {ugs.sum()} tokens)")
+ print(ugs.head(5).to_string())
+```
+
+```{code-cell} ipython3
+normalized_corpus_unigrams = {group: (100 * ugs / ugs.sum()).round(1).rename("frequency") for group, ugs in corpus_wise_unigrams.iter()}
+```
+
+```{code-cell} ipython3
+transitions_from_shared_types = {
+ False: {},
+ True: {}
+}
+for (is_minor, corpus_name), bgs in corpus_wise_bigrams.iter():
+ transitions_normalized_per_from = bgs.groupby(level="from", group_keys=False).apply(lambda S: (100 * S / S.sum()).round(1))
+ most_frequent_transition_per_from = transitions_normalized_per_from.rename('fraction').reset_index(level=1).groupby(level=0).nth(0)
+ most_frequent_transition_per_shared = most_frequent_transition_per_from.loc[types_shared_between_corpora[is_minor]]
+ unigram_frequency_of_shared = normalized_corpus_unigrams[(is_minor, corpus_name)].loc[types_shared_between_corpora[is_minor]]
+ combined = pd.concat([unigram_frequency_of_shared, most_frequent_transition_per_shared], axis=1)
+ transitions_from_shared_types[is_minor][corpus_name] = combined
+```
+
+```{code-cell} ipython3
+pd.concat(transitions_from_shared_types[False].values(), keys=transitions_from_shared_types[False].keys(), axis=1)
+```
+
+```{code-cell} ipython3
+pd.concat(transitions_from_shared_types[True].values(), keys=transitions_from_shared_types[False].keys(), axis=1)
+```
+
+### Per piece
+
+```{code-cell} ipython3
+piece_wise_bigrams = dc.Pipeline([dc.PieceGrouper(), dc.ChordSymbolBigrams(once_per_group=True)]).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+piece_wise_bigrams.get()
+```
\ No newline at end of file
diff --git a/homepage/notebooks/cadences.md b/homepage/notebooks/cadences.md
new file mode 100644
index 0000000..c6a7c74
--- /dev/null
+++ b/homepage/notebooks/cadences.md
@@ -0,0 +1,478 @@
+---
+jupytext:
+ formats: md:myst,ipynb
+ text_representation:
+ extension: .md
+ format_name: myst
+ format_version: 0.13
+ jupytext_version: 1.15.0
+kernelspec:
+ display_name: corpus_docs
+ language: python
+ name: corpus_docs
+---
+
+# Cadences
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide imports
+ code_prompt_show: Show imports
+tags: [hide-cell]
+---
+import os
+from collections import defaultdict, Counter
+
+from git import Repo
+import dimcat as dc
+import ms3
+import pandas as pd
+import plotly.express as px
+import plotly.graph_objects as go
+
+from utils import STD_LAYOUT, CADENCE_COLORS, color_background, value_count_df, get_repo_name, print_heading, resolve_dir
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+CORPUS_PATH = os.path.abspath(os.path.join('..', '..'))
+print_heading("Notebook settings")
+print(f"CORPUS_PATH: {CORPUS_PATH!r}")
+CORPUS_PATH = resolve_dir(CORPUS_PATH)
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+repo = Repo(CORPUS_PATH)
+print_heading("Data and software versions")
+print(f"Data repo '{get_repo_name(repo)}' @ {repo.commit().hexsha[:7]}")
+print(f"dimcat version {dc.__version__}")
+print(f"ms3 version {ms3.__version__}")
+```
+
+```{code-cell} ipython3
+:tags: [remove-output]
+
+dataset = dc.Dataset()
+dataset.load(directory=CORPUS_PATH, parse_tsv=False)
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+annotated_view = dataset.data.get_view('annotated')
+annotated_view.include('facets', 'expanded')
+annotated_view.fnames_with_incomplete_facets = False
+dataset.data.set_view(annotated_view)
+dataset.data.parse_tsv(choose='auto')
+dataset.get_indices()
+dataset.data
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+print(f"N = {dataset.data.count_pieces()} annotated pieces, {dataset.data.count_parsed_tsvs()} parsed dataframes.")
+```
+
+## Metadata
+
+```{code-cell} ipython3
+all_metadata = dataset.data.metadata()
+assert len(all_metadata) > 0, "No pieces selected for analysis."
+print(f"Concatenated 'metadata.tsv' files cover {len(all_metadata)} of the {dataset.data.count_pieces()} scores.")
+all_metadata.reset_index(level=1).groupby(level=0).nth(0).iloc[:,:20]
+```
+
+## All annotation labels from the selected pieces
+
+```{code-cell} ipython3
+all_labels = dataset.data.get_facet('expanded')
+
+print(f"{len(all_labels.index)} hand-annotated harmony labels:")
+all_labels.iloc[:20].style.apply(color_background, subset="chord")
+```
+
+### Filtering out pieces without cadence annotations
+
+```{code-cell} ipython3
+hascadence = dc.HasCadenceAnnotationsFilter().process_data(dataset)
+assert () in hascadence.indices and len(hascadence.indices[()]) > 0, "No cadences found."
+print(f"Before: {len(dataset.indices[()])} pieces; after removing those without cadence labels: {len(hascadence.indices[()])}")
+```
+
+### Show corpora containing pieces with cadence annotations
+
+```{code-cell} ipython3
+grouped_by_corpus = dc.CorpusGrouper().process_data(hascadence)
+corpora = {group[0]: f"{len(ixs)} pieces" for group, ixs in grouped_by_corpus.indices.items()}
+print(f"{len(corpora)} corpora with {sum(map(len, grouped_by_corpus.indices.values()))} pieces containing cadence annotations:")
+corpora
+```
+
+### All annotation labels from the selected pieces
+
+```{code-cell} ipython3
+all_labels = hascadence.get_facet('expanded')
+
+print(f"{len(all_labels.index)} hand-annotated harmony labels:")
+all_labels.iloc[:10, 13:].style.apply(color_background, subset="chord")
+```
+
+### Metadata
+
+```{code-cell} ipython3
+dataset_metadata = hascadence.data.metadata()
+hascadence_metadata = dataset_metadata.loc[hascadence.indices[()]]
+hascadence_metadata.index.rename('dataset', level=0, inplace=True)
+hascadence_metadata.head()
+```
+
+```{code-cell} ipython3
+mean_composition_years = hascadence_metadata.groupby(level=0).composed_end.mean().astype(int).sort_values()
+chronological_order = mean_composition_years.index.to_list()
+bar_data = pd.concat([mean_composition_years.rename('year'),
+ hascadence_metadata.groupby(level='dataset').size().rename('pieces')],
+ axis=1
+ ).reset_index()
+fig = px.bar(bar_data, x='year', y='pieces', color='dataset', 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
+
+```{code-cell} ipython3
+print(f"{all_labels.cadence.notna().sum()} cadence labels.")
+value_count_df(all_labels.cadence)
+```
+
+```{code-cell} ipython3
+px.pie(all_labels[all_labels.cadence.notna()], names="cadence", color="cadence", color_discrete_map=CADENCE_COLORS)
+```
+
+## Per dataset
+
+```{code-cell} ipython3
+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()
+px.bar(cadence_fraction_per_dataset.rename('count').reset_index(), x='corpus', y='count', color='cadence',
+ color_discrete_map=CADENCE_COLORS, category_orders=dict(dataset=chronological_order))
+```
+
+```{code-cell} ipython3
+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=CADENCE_COLORS)
+fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
+fig.update_layout(**STD_LAYOUT)
+```
+
+## Per phrase
+### Number of cadences per phrase
+
+```{code-cell} ipython3
+segmented = dc.PhraseSlicer().process_data(grouped_by_corpus)
+phrases = segmented.get_slice_info()
+phrase_segments = segmented.get_facet("expanded")
+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 l: tuple(e for e in l if not pd.isnull(e))),
+ phrases_with_keys
+], axis=1)
+value_count_df(phrases_with_cadences.n_cadences, counts="#phrases")
+```
+
+```{code-cell} ipython3
+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_order)
+ )
+fig.show()
+```
+
+### Combinations of cadence types for phrases with more than one cadence
+
+```{code-cell} ipython3
+value_count_df(phrases_with_cadences[phrases_with_cadences.n_cadences > 1].cadences)
+```
+
+### Positioning of cadences within phrases
+
+```{code-cell} ipython3
+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 -= 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"])
+```
+
+```{code-cell} ipython3
+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=CADENCE_COLORS)
+fig.update_traces(marker_size=5)
+fig.update_yaxes(autorange="reversed")
+fig.show()
+```
+
+## Cadence ultima
+
+```{code-cell} ipython3
+phrase_segments = segmented.get_facet("expanded")
+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]
+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 labels.")
+```
+
+### Ultimae as Roman numeral
+
+```{code-cell} ipython3
+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)
+```
+
+```{code-cell} ipython3
+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(**STD_LAYOUT)
+fig.show()
+```
+
+```{code-cell} ipython3
+#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
+
+```{code-cell} ipython3
+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)
+```
+
+```{code-cell} ipython3
+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(**STD_LAYOUT)
+fig.show()
+```
+
+## Chord progressions
+
++++
+
+### PACs with ultima I/i
+
+```{code-cell} ipython3
+def remove_immediate_duplicates(l):
+ return tuple(a for a, b in zip(l, (None, ) + l) 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.fillna(method='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
+```
+
+```{code-cell} ipython3
+chord_progressions = get_progressions('PAC', dict(numeral=('I', 'i')), 'chord')
+print(f"Progressions for {len(chord_progressions)} cadences:")
+value_count_df(chord_progressions, "chord progressions")
+```
+
+```{code-cell} ipython3
+numeral_progressions = get_progressions('PAC', dict(numeral=('I', 'i')), 'numeral')
+value_count_df(numeral_progressions, "numeral progressions")
+```
+
+```{code-cell} ipython3
+numeral_prog_no_dups = numeral_progressions.map(remove_immediate_duplicates)
+value_count_df(numeral_prog_no_dups)
+```
+
+### PACs ending on scale degree 1
+
+**Scale degrees expressed w.r.t. major scale, regardless of actual key.**
+
+```{code-cell} ipython3
+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:")
+value_count_df(bass_prog, "bass progressions")
+```
+
+```{code-cell} ipython3
+bass_prog_no_dups = bass_prog.map(remove_immediate_duplicates)
+value_count_df(bass_prog_no_dups)
+```
+
+```{code-cell} ipython3
+def make_sankey(data, labels, node_pos=None, margin={'l': 10, 'r': 10, 'b': 10, 't': 10}, pad=20, color='auto', **kwargs):
+ if color=='auto':
+ unique_labels = set(labels)
+ color_step = 100 / len(unique_labels)
+ unique_colors = {label: f'hsv({round(i*color_step)}%,100%,100%)' for i, label in enumerate(unique_labels)}
+ color = list(map(lambda l: unique_colors[l], labels))
+ fig = go.Figure(go.Sankey(
+ arrangement = 'snap',
+ node = dict(
+ pad = pad,
+ #thickness = 20,
+ #line = dict(color = "black", width = 0.5),
+ label = labels,
+ x = [node_pos[i][0] if i in node_pos else 0 for i in range(len(labels))] if node_pos is not None else None,
+ y = [node_pos[i][1] if i in node_pos else 0 for i in range(len(labels))] if node_pos is not None else None,
+ color = color,
+ ),
+ link = dict(
+ source = data.source,
+ target = data.target,
+ value = data.value
+ ),
+ ),
+ )
+
+ fig.update_layout(margin=margin, **kwargs)
+ return fig
+
+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 graph_data2sankey(stage_nodes, edge_weights):
+ data = pd.DataFrame([(u, v, w) for (u, v), w in edge_weights.items()], columns = ['source', 'target', 'value'])
+ node2label = {node: label for stage, nodes in stage_nodes.items() for label, node in nodes.items()}
+ labels = [node2label[i] for i in range(len(node2label))]
+ return make_sankey(data, labels)
+
+def plot_progressions(progressions, cut_at_stage=None):
+ stage_nodes, edge_weights = progressions2graph_data(progressions, cut_at_stage=cut_at_stage)
+ return graph_data2sankey(stage_nodes, edge_weights)
+```
+
+#### Chordal roots for the 3 last stages
+
+```{code-cell} ipython3
+plot_progressions(numeral_prog_no_dups, cut_at_stage=3)
+```
+
+#### Complete chords for the last four stages in major
+
+```{code-cell} ipython3
+pac_major = get_progressions('PAC', dict(numeral='I', localkey_is_minor=False), 'chord')
+plot_progressions(pac_major, cut_at_stage=4)
+```
+
+#### Bass degrees for the last 6 stages.
+
+```{code-cell} ipython3
+plot_progressions(bass_prog_no_dups, cut_at_stage=7)
+```
+
+#### Bass degrees without accidentals
+
+```{code-cell} ipython3
+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)
+plot_progressions(bass_prog_no_acc_no_dup, cut_at_stage=7)
+```
+
+### HCs ending on V
+
+```{code-cell} ipython3
+half = get_progressions('HC', dict(numeral='V'), 'bass_note').map(ms3.fifths2sd)
+print(f"Progressions for {len(half)} cadences:")
+plot_progressions(half.map(remove_immediate_duplicates), cut_at_stage=5)
+```
\ No newline at end of file
diff --git a/homepage/notebooks/notes_stats.md b/homepage/notebooks/notes_stats.md
new file mode 100644
index 0000000..7880737
--- /dev/null
+++ b/homepage/notebooks/notes_stats.md
@@ -0,0 +1,290 @@
+---
+jupytext:
+ formats: ipynb,md:myst
+ text_representation:
+ extension: .md
+ format_name: myst
+ format_version: 0.13
+ jupytext_version: 1.15.0
+kernelspec:
+ display_name: corpus_docs
+ language: python
+ name: corpus_docs
+---
+
+# Notes
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide imports
+ code_prompt_show: Show imports
+tags: [hide-cell]
+---
+import os
+from collections import defaultdict, Counter
+
+from git import Repo
+import dimcat as dc
+import ms3
+import pandas as pd
+import plotly.express as px
+import plotly.graph_objects as go
+
+from utils import STD_LAYOUT, CADENCE_COLORS, CORPUS_COLOR_SCALE, chronological_corpus_order, color_background, get_corpus_display_name, get_repo_name, resolve_dir, value_count_df, get_repo_name, print_heading, resolve_dir
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+CORPUS_PATH = os.path.abspath(os.path.join('..', '..'))
+ANNOTATED_ONLY = os.getenv("ANNOTATED_ONLY", "True").lower() in ('true', '1', 't')
+print_heading("Notebook settings")
+print(f"CORPUS_PATH: {CORPUS_PATH!r}")
+print(f"ANNOTATED_ONLY: {ANNOTATED_ONLY}")
+CORPUS_PATH = resolve_dir(CORPUS_PATH)
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+repo = Repo(CORPUS_PATH)
+print_heading("Data and software versions")
+print(f"Data repo '{get_repo_name(repo)}' @ {repo.commit().hexsha[:7]}")
+print(f"dimcat version {dc.__version__}")
+print(f"ms3 version {ms3.__version__}")
+```
+
+```{code-cell} ipython3
+:tags: [remove-output]
+
+dataset = dc.Dataset()
+dataset.load(directory=CORPUS_PATH, parse_tsv=False)
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+if ANNOTATED_ONLY:
+ annotated_view = dataset.data.get_view('annotated')
+ annotated_view.include('facets', 'measures', 'notes$', 'expanded')
+ annotated_view.fnames_with_incomplete_facets = False
+ dataset.data.set_view(annotated_view)
+dataset.data.parse_tsv(choose='auto')
+dataset.get_indices()
+dataset.data
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+print(f"N = {dataset.data.count_pieces()} annotated pieces, {dataset.data.count_parsed_tsvs()} parsed dataframes.")
+```
+
+## Metadata
+
+```{code-cell} ipython3
+all_metadata = dataset.data.metadata()
+print(f"Concatenated 'metadata.tsv' files cover {len(all_metadata)} of the {dataset.data.count_pieces()} scores.")
+all_metadata.reset_index(level=1).groupby(level=0).nth(0).iloc[:,:20]
+```
+
+**Compute chronological order**
+
+```{code-cell} ipython3
+chronological_order = chronological_corpus_order(all_metadata)
+corpus_colors = dict(zip(chronological_order, CORPUS_COLOR_SCALE))
+chronological_order
+```
+
+```{code-cell} ipython3
+all_notes = dataset.data.get_all_parsed('notes', force=True, flat=True)
+print(f"{len(all_notes.index)} notes over {len(all_notes.groupby(level=[0,1]))} files.")
+all_notes.head()
+```
+
+```{code-cell} ipython3
+def weight_notes(nl, group_col='midi', precise=True):
+ summed_durations = nl.groupby(group_col).duration_qb.sum()
+ shortest_duration = summed_durations[summed_durations > 0].min()
+ summed_durations /= shortest_duration # normalize such that the shortest duration results in 1 occurrence
+ if not precise:
+ # This simple trick reduces compute time but also precision:
+ # The rationale is to have the smallest value be slightly larger than 0.5 because
+ # if it was exactly 0.5 it would be rounded down by repeat_notes_according_to_weights()
+ summed_durations /= 1.9999999
+ return repeat_notes_according_to_weights(summed_durations)
+
+def repeat_notes_according_to_weights(weights):
+ try:
+ counts = weights.round().astype(int)
+ except Exception:
+ return pd.Series(dtype=int)
+ counts_reflecting_weights = []
+ for pitch, count in counts.items():
+ counts_reflecting_weights.extend([pitch]*count)
+ return pd.Series(counts_reflecting_weights)
+```
+
+## Ambitus
+
+```{code-cell} ipython3
+corpus_names = {corp: get_corpus_display_name(corp) for corp in chronological_order}
+chronological_corpus_names = list(corpus_names.values())
+corpus_name_colors = {corpus_names[corp]: color for corp, color in corpus_colors.items()}
+all_notes['corpus_name'] = all_notes.index.get_level_values(0).map(corpus_names)
+```
+
+```{code-cell} ipython3
+grouped_notes = all_notes.groupby('corpus_name')
+weighted_midi = pd.concat([weight_notes(nl, 'midi', precise=False) for _, nl in grouped_notes], keys=grouped_notes.groups.keys()).reset_index(level=0)
+weighted_midi.columns = ['dataset', 'midi']
+weighted_midi
+```
+
+```{code-cell} ipython3
+yaxis=dict(tickmode= 'array',
+ tickvals= [12, 24, 36, 48, 60, 72, 84, 96],
+ ticktext = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7"],
+ gridcolor='lightgrey',
+ )
+fig = px.violin(weighted_midi,
+ x='dataset',
+ y='midi',
+ color='dataset',
+ box=True,
+ labels=dict(
+ dataset='',
+ midi='distribution of pitches by duration'
+ ),
+ category_orders=dict(dataset=chronological_corpus_names),
+ color_discrete_map=corpus_name_colors,
+ width=1000, height=600,
+ )
+fig.update_traces(spanmode='hard') # do not extend beyond outliers
+fig.update_layout(yaxis=yaxis,
+ **STD_LAYOUT,
+ showlegend=False)
+fig.show()
+```
+
+## Tonal Pitch Classes (TPC)
+
+```{code-cell} ipython3
+weighted_tpc = pd.concat([weight_notes(nl, 'tpc') for _, nl in grouped_notes], keys=grouped_notes.groups.keys()).reset_index(level=0)
+weighted_tpc.columns = ['dataset', 'tpc']
+weighted_tpc
+```
+
+### As violin plot
+
+```{code-cell} ipython3
+yaxis=dict(
+ tickmode= 'array',
+ tickvals= [-12, -9, -6, -3, 0, 3, 6, 9, 12, 15, 18],
+ ticktext = ["Dbb", "Bbb", "Gb", "Eb", "C", "A", "F#", "D#", "B#", "G##", "E##"],
+ gridcolor='lightgrey',
+ zerolinecolor='lightgrey',
+ zeroline=True
+ )
+fig = px.violin(weighted_tpc,
+ x='dataset',
+ y='tpc',
+ color='dataset',
+ box=True,
+ labels=dict(
+ dataset='',
+ tpc='distribution of tonal pitch classes by duration'
+ ),
+ category_orders=dict(dataset=chronological_corpus_names),
+ color_discrete_map=corpus_name_colors,
+ width=1000,
+ height=600,
+ )
+fig.update_traces(spanmode='hard') # do not extend beyond outliers
+fig.update_layout(yaxis=yaxis,
+ **STD_LAYOUT,
+ showlegend=False)
+fig.show()
+```
+
+### As bar plots
+
+```{code-cell} ipython3
+bar_data = all_notes.groupby('tpc').duration_qb.sum().reset_index()
+x_values = list(range(bar_data.tpc.min(), bar_data.tpc.max()+1))
+x_names = ms3.fifths2name(x_values)
+fig = px.bar(bar_data, x='tpc', y='duration_qb',
+ labels=dict(tpc='Named pitch class',
+ duration_qb='Duration in quarter notes'
+ ),
+ color_discrete_sequence=CORPUS_COLOR_SCALE,
+ width=1000, height=300,
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.update_xaxes(gridcolor='lightgrey', zerolinecolor='grey', tickmode='array',
+ tickvals=x_values, ticktext = x_names, dtick=1, ticks='outside', tickcolor='black',
+ minor=dict(dtick=6, gridcolor='grey', showgrid=True),
+ )
+fig.show()
+```
+
+```{code-cell} ipython3
+scatter_data = all_notes.groupby(['corpus_name', 'tpc']).duration_qb.sum().reset_index()
+fig = px.bar(scatter_data, x='tpc', y='duration_qb', color='corpus_name',
+ labels=dict(
+ duration_qb='duration',
+ tpc='named pitch class',
+ ),
+ category_orders=dict(dataset=chronological_corpus_names),
+ color_discrete_map=corpus_name_colors,
+ width=1000, height=500,
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.update_xaxes(gridcolor='lightgrey', zerolinecolor='grey', tickmode='array',
+ tickvals=x_values, ticktext = x_names, dtick=1, ticks='outside', tickcolor='black',
+ minor=dict(dtick=6, gridcolor='grey', showgrid=True),
+ )
+fig.show()
+```
+
+### As scatter plots
+
+```{code-cell} ipython3
+fig = px.scatter(scatter_data, x='tpc', y='duration_qb', color='corpus_name',
+ labels=dict(
+ duration_qb='duration',
+ tpc='named pitch class',
+ ),
+ category_orders=dict(dataset=chronological_corpus_names),
+ color_discrete_map=corpus_name_colors,
+ facet_col='corpus_name', facet_col_wrap=3, facet_col_spacing=0.03,
+ width=1000, height=1000,
+ )
+fig.update_traces(mode='lines+markers')
+fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
+fig.update_layout(**STD_LAYOUT, showlegend=False)
+fig.update_xaxes(gridcolor='lightgrey', zerolinecolor='lightgrey', tickmode='array', tickvals= [-12, -6, 0, 6, 12, 18],
+ ticktext = ["Dbb", "Gb", "C", "F#", "B#", "E##"], visible=True, )
+fig.update_yaxes(gridcolor='lightgrey', zeroline=False, matches=None, showticklabels=True)
+fig.show()
+```
+
+```{code-cell} ipython3
+no_accidental = bar_data[bar_data.tpc.between(-1,5)].duration_qb.sum()
+with_accidental = bar_data[~bar_data.tpc.between(-1,5)].duration_qb.sum()
+```
+
+```{code-cell} ipython3
+entire = no_accidental + with_accidental
+f"Fraction of note duration without accidental of the entire durations: {no_accidental} / {entire} = {no_accidental / entire}"
+```
+
+### Notes and staves
+
+```{code-cell} ipython3
+print("Distribution of notes over staves:")
+value_count_df(all_notes.staff)
+```
\ No newline at end of file
diff --git a/homepage/notebooks/overview.md b/homepage/notebooks/overview.md
new file mode 100644
index 0000000..d6e03e7
--- /dev/null
+++ b/homepage/notebooks/overview.md
@@ -0,0 +1,223 @@
+---
+jupytext:
+ formats: ipynb,md:myst
+ text_representation:
+ extension: .md
+ format_name: myst
+ format_version: 0.13
+ jupytext_version: 1.15.0
+kernelspec:
+ display_name: corpus_docs
+ language: python
+ name: corpus_docs
+---
+
+# Overview
+
+This notebook gives a general overview of the features included in the dataset.
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide imports
+ code_prompt_show: Show imports
+tags: [hide-cell]
+---
+import os
+from collections import defaultdict, Counter
+from fractions import Fraction
+
+from git import Repo
+import dimcat as dc
+import ms3
+import pandas as pd
+import plotly.express as px
+import plotly.graph_objects as go
+
+from utils import CADENCE_COLORS, CORPUS_COLOR_SCALE, STD_LAYOUT, TYPE_COLORS, color_background, corpus_mean_composition_years, value_count_df, get_corpus_display_name, get_repo_name, print_heading, resolve_dir
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+CORPUS_PATH = os.path.abspath(os.path.join('..', '..'))
+ANNOTATED_ONLY = os.getenv("ANNOTATED_ONLY", "True").lower() in ('true', '1', 't')
+print_heading("Notebook settings")
+print(f"CORPUS_PATH: {CORPUS_PATH!r}")
+print(f"ANNOTATED_ONLY: {ANNOTATED_ONLY}")
+CORPUS_PATH = resolve_dir(CORPUS_PATH)
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+repo = Repo(CORPUS_PATH)
+print_heading("Data and software versions")
+print(f"Data repo '{get_repo_name(repo)}' @ {repo.commit().hexsha[:7]}")
+print(f"dimcat version {dc.__version__}")
+print(f"ms3 version {ms3.__version__}")
+```
+
+```{code-cell} ipython3
+:tags: [remove-output]
+
+dataset = dc.Dataset()
+dataset.load(directory=CORPUS_PATH, parse_tsv=False)
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+if ANNOTATED_ONLY:
+ annotated_view = dataset.data.get_view('annotated')
+ annotated_view.include('facets', 'measures', 'notes$', 'expanded')
+ annotated_view.fnames_with_incomplete_facets = False
+ dataset.data.set_view(annotated_view)
+dataset.data.parse_tsv(choose='auto')
+dataset.get_indices()
+dataset.data
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+print(f"N = {dataset.data.count_pieces()} annotated pieces, {dataset.data.count_parsed_tsvs()} parsed dataframes.")
+```
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide data loading
+ code_prompt_show: Show data loading
+tags: [hide-cell]
+---
+all_metadata = dataset.data.metadata()
+assert len(all_metadata) > 0, "No pieces selected for analysis."
+print(f"Metadata covers {len(all_metadata)} of the {dataset.data.count_pieces()} scores.")
+all_notes = dataset.get_facet('notes')
+all_measures = dataset.get_facet('measures')
+mean_composition_years = corpus_mean_composition_years(all_metadata)
+chronological_order = mean_composition_years.index.to_list()
+corpus_colors = dict(zip(chronological_order, CORPUS_COLOR_SCALE))
+corpus_names = {corp: get_corpus_display_name(corp) for corp in chronological_order}
+chronological_corpus_names = list(corpus_names.values())
+corpus_name_colors = {corpus_names[corp]: color for corp, color in corpus_colors.items()}
+```
+
+## Composition dates
+
+This section relies on the dataset's metadata.
+
+```{code-cell} ipython3
+valid_composed_start = pd.to_numeric(all_metadata.composed_start, errors='coerce')
+valid_composed_end = pd.to_numeric(all_metadata.composed_end, errors='coerce')
+print(f"Composition dates range from {int(valid_composed_start.min())} {valid_composed_start.idxmin()} "
+ f"to {int(valid_composed_end.max())} {valid_composed_end.idxmax()}.")
+```
+
+### Mean composition years per corpus
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+summary = all_metadata.copy()
+summary.length_qb = all_measures.groupby(level=[0,1]).act_dur.sum() * 4.0
+summary = pd.concat([summary,
+ all_notes.groupby(level=[0,1]).size().rename('notes'),
+ ], axis=1)
+bar_data = pd.concat([mean_composition_years.rename('year'),
+ summary.groupby(level='corpus').size().rename('pieces')],
+ axis=1
+ ).reset_index()
+fig = px.bar(bar_data, x='year', y='pieces', color='corpus',
+ color_discrete_map=corpus_colors,
+ )
+fig.update_traces(width=5)
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.update_traces(width=5)
+```
+
+### Composition years histogram
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+hist_data = summary.reset_index()
+hist_data.corpus = hist_data.corpus.map(corpus_names)
+fig = px.histogram(hist_data, x='composed_end', color='corpus',
+ labels=dict(composed_end='decade',
+ count='pieces',
+ ),
+ color_discrete_map=corpus_name_colors,
+ )
+fig.update_traces(xbins=dict(
+ size=10
+))
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+## Dimensions
+
+### Overview
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+corpus_metadata = summary.groupby(level=0)
+n_pieces = corpus_metadata.size().rename('pieces')
+absolute_numbers = dict(
+ measures = corpus_metadata.last_mn.sum(),
+ length = corpus_metadata.length_qb.sum(),
+ notes = corpus_metadata.notes.sum(),
+ labels = corpus_metadata.label_count.sum(),
+)
+absolute = pd.DataFrame.from_dict(absolute_numbers)
+absolute = pd.concat([n_pieces, absolute], axis=1)
+sum_row = pd.DataFrame(absolute.sum(), columns=['sum']).T
+absolute = pd.concat([absolute, sum_row])
+relative = absolute.div(n_pieces, axis=0)
+complete_summary = pd.concat([absolute, relative, absolute.iloc[:1,2:].div(absolute.measures, axis=0)], axis=1, keys=['absolute', 'per piece', 'per measure'])
+complete_summary = complete_summary.apply(pd.to_numeric).round(2)
+complete_summary.index = complete_summary.index.map(dict(corpus_names, sum='sum'))
+complete_summary
+```
+
+### Measures
+
+```{code-cell} ipython3
+print(f"{len(all_measures.index)} measures over {len(all_measures.groupby(level=[0,1]))} files.")
+all_measures.head()
+```
+
+```{code-cell} ipython3
+print("Distribution of time signatures per XML measure (MC):")
+all_measures.timesig.value_counts(dropna=False)
+```
+
+### Harmony labels
+
+All symbols, independent of the local key (the mode of which changes their semantics).
+
+```{code-cell} ipython3
+try:
+ all_annotations = dataset.get_facet('expanded')
+except Exception:
+ all_annotations = pd.DataFrame()
+n_annotations = len(all_annotations.index)
+includes_annotations = n_annotations > 0
+if includes_annotations:
+ display(all_annotations.head())
+ print(f"Concatenated annotation tables contains {all_annotations.shape[0]} rows.")
+ no_chord = all_annotations.root.isna()
+ if no_chord.sum() > 0:
+ print(f"{no_chord.sum()} of them are not chords. Their values are: {all_annotations.label[no_chord].value_counts(dropna=False).to_dict()}")
+ all_chords = all_annotations[~no_chord].copy()
+ print(f"Dataset contains {all_chords.shape[0]} tokens and {len(all_chords.chord.unique())} types over {len(all_chords.groupby(level=[0,1]))} documents.")
+ all_annotations['corpus_name'] = all_annotations.index.get_level_values(0).map(get_corpus_display_name)
+ all_chords['corpus_name'] = all_chords.index.get_level_values(0).map(get_corpus_display_name)
+else:
+ print(f"Dataset contains no annotations.")
+```
\ No newline at end of file
diff --git a/homepage/notebooks/requirements.txt b/homepage/notebooks/requirements.txt
new file mode 100644
index 0000000..7b210af
--- /dev/null
+++ b/homepage/notebooks/requirements.txt
@@ -0,0 +1,14 @@
+colorlover==0.3.0
+dimcat==0.3.0
+ipython==8.11.0
+jupytext==1.14.5
+ipykernel==6.25.0
+kaleido==0.2.1
+matplotlib==3.7.1
+ms3>=2.2.0
+nbformat==5.7.3
+numpy==1.24.2
+pandas==1.5.3
+plotly==5.13.1
+jinja2==3.1.2
+tabulate==0.9.0
diff --git a/homepage/notebooks/scale_degrees.md b/homepage/notebooks/scale_degrees.md
new file mode 100644
index 0000000..5988742
--- /dev/null
+++ b/homepage/notebooks/scale_degrees.md
@@ -0,0 +1,495 @@
+---
+jupytext:
+ formats: md:myst,ipynb
+ text_representation:
+ extension: .md
+ format_name: myst
+ format_version: 0.13
+ jupytext_version: 1.15.0
+kernelspec:
+ display_name: corpus_docs
+ language: python
+ name: corpus_docs
+---
+
+# Annotations
+
+```{code-cell} ipython3
+---
+mystnb:
+ code_prompt_hide: Hide imports
+ code_prompt_show: Show imports
+tags: [hide-cell]
+---
+import os
+from collections import defaultdict, Counter
+from fractions import Fraction
+
+from git import Repo
+import dimcat as dc
+import ms3
+import pandas as pd
+pd.set_option('display.max_rows', 500)
+pd.set_option('display.max_columns', 100)
+import plotly.express as px
+import plotly.graph_objects as go
+
+from utils import STD_LAYOUT, CADENCE_COLORS, CORPUS_COLOR_SCALE, TYPE_COLORS, chronological_corpus_order, color_background, corpus_mean_composition_years, get_corpus_display_name, get_repo_name, resolve_dir, value_count_df, get_repo_name, print_heading, resolve_dir
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+CORPUS_PATH = os.getenv('CORPUS_PATH', "/home/hentsche/tmp/all_subcorpora/")
+print_heading("Notebook settings")
+print(f"CORPUS_PATH: {CORPUS_PATH!r}")
+CORPUS_PATH = resolve_dir(CORPUS_PATH)
+```
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+repo = Repo(CORPUS_PATH)
+print_heading("Data and software versions")
+print(f"Data repo '{get_repo_name(repo)}' @ {repo.commit().hexsha[:7]}")
+print(f"dimcat version {dc.__version__}")
+print(f"ms3 version {ms3.__version__}")
+```
+
+```{code-cell} ipython3
+:tags: [remove-output]
+
+dataset = dc.Dataset()
+dataset.load(directory=CORPUS_PATH, parse_tsv=False)
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+annotated_view = dataset.data.get_view('annotated')
+annotated_view.include('facets', 'measures', 'expanded')
+annotated_view.fnames_with_incomplete_facets = False
+dataset.data.set_view(annotated_view)
+dataset.data.parse_tsv(choose='auto')
+dataset.get_indices()
+dataset.data
+```
+
+```{code-cell} ipython3
+:tags: [remove-input]
+
+print(f"N = {dataset.data.count_pieces()} annotated pieces, {dataset.data.count_parsed_tsvs()} parsed dataframes.")
+```
+
+```{code-cell} ipython3
+all_metadata = dataset.data.metadata()
+assert len(all_metadata) > 0, "No pieces selected for analysis."
+print(f"Metadata covers {len(all_metadata)} of the {dataset.data.count_pieces()} scores.")
+mean_composition_years = corpus_mean_composition_years(all_metadata)
+chronological_order = mean_composition_years.index.to_list()
+corpus_colors = dict(zip(chronological_order, CORPUS_COLOR_SCALE))
+corpus_names = {corp: get_corpus_display_name(corp) for corp in chronological_order}
+chronological_corpus_names = list(corpus_names.values())
+corpus_name_colors = {corpus_names[corp]: color for corp, color in corpus_colors.items()}
+```
+
+## DCML harmony labels
+
+```{code-cell} ipython3
+:tags: [hide-input]
+
+try:
+ all_annotations = dataset.get_facet('expanded')
+except Exception:
+ all_annotations = pd.DataFrame()
+n_annotations = len(all_annotations.index)
+includes_annotations = n_annotations > 0
+if includes_annotations:
+ display(all_annotations.head())
+ print(f"Concatenated annotation tables contain {all_annotations.shape[0]} rows.")
+ no_chord = all_annotations.root.isna()
+ if no_chord.sum() > 0:
+ print(f"{no_chord.sum()} of them are not chords. Their values are: {all_annotations.label[no_chord].value_counts(dropna=False).to_dict()}")
+ all_chords = all_annotations[~no_chord].copy()
+ print(f"Dataset contains {all_chords.shape[0]} tokens and {len(all_chords.chord.unique())} types over {len(all_chords.groupby(level=[0,1]))} documents.")
+ all_annotations['corpus_name'] = all_annotations.index.get_level_values(0).map(corpus_names)
+ all_chords['corpus_name'] = all_chords.index.get_level_values(0).map(corpus_names)
+else:
+ print(f"Dataset contains no annotations.")
+```
+
+## Key areas
+
+```{code-cell} ipython3
+from ms3 import roman_numeral2fifths, transform, resolve_all_relative_numerals, replace_boolean_mode_by_strings
+keys_segmented = dc.LocalKeySlicer().process_data(dataset)
+keys = keys_segmented.get_slice_info()
+print(f"Overall number of key segments is {len(keys.index)}")
+keys["localkey_fifths"] = transform(keys, roman_numeral2fifths, ['localkey', 'globalkey_is_minor'])
+keys.head(5).style.apply(color_background, subset="localkey")
+```
+
+### Durational distribution of local keys
+
+All durations given in quarter notes
+
+```{code-cell} ipython3
+key_durations = keys.groupby(['globalkey_is_minor', 'localkey']).duration_qb.sum().sort_values(ascending=False)
+print(f"{len(key_durations)} keys overall including hierarchical such as 'III/v'.")
+```
+
+```{code-cell} ipython3
+keys_resolved = resolve_all_relative_numerals(keys)
+key_resolved_durations = keys_resolved.groupby(['globalkey_is_minor', 'localkey']).duration_qb.sum().sort_values(ascending=False)
+print(f"{len(key_resolved_durations)} keys overall after resolving hierarchical ones.")
+key_resolved_durations
+```
+
+#### Distribution of local keys for piece in major and in minor
+
+`globalkey_mode=minor` => Piece is in Minor
+
+```{code-cell} ipython3
+pie_data = replace_boolean_mode_by_strings(key_resolved_durations.reset_index())
+px.pie(pie_data, names='localkey', values='duration_qb', facet_col='globalkey_mode')
+```
+
+#### Distribution of intervals between localkey tonic and global tonic
+
+```{code-cell} ipython3
+localkey_fifths_durations = keys.groupby(['localkey_fifths', 'localkey_is_minor']).duration_qb.sum()
+bar_data = replace_boolean_mode_by_strings(localkey_fifths_durations.reset_index())
+bar_data.localkey_fifths = bar_data.localkey_fifths.map(ms3.fifths2iv)
+fig = px.bar(bar_data, x='localkey_fifths', y='duration_qb', color='localkey_mode', log_y=True, barmode='group',
+ labels=dict(localkey_fifths='Roots of local keys as intervallic distance from the global tonic',
+ duration_qb='total duration in quarter notes',
+ localkey_mode='mode'
+ ),
+ color_discrete_sequence=CORPUS_COLOR_SCALE,
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+### Ratio between major and minor key segments by aggregated durations
+#### Overall
+
+```{code-cell} ipython3
+keys.duration_qb = pd.to_numeric(keys.duration_qb)
+maj_min_ratio = keys.groupby("localkey_is_minor").duration_qb.sum().to_frame()
+maj_min_ratio['fraction'] = (100.0 * maj_min_ratio.duration_qb / maj_min_ratio.duration_qb.sum()).round(1)
+maj_min_ratio
+```
+
+#### By dataset
+
+```{code-cell} ipython3
+segment_duration_per_dataset = keys.groupby(["corpus", "localkey_is_minor"]).duration_qb.sum().round(2)
+norm_segment_duration_per_dataset = 100 * segment_duration_per_dataset / segment_duration_per_dataset.groupby(level="corpus").sum()
+maj_min_ratio_per_dataset = pd.concat([segment_duration_per_dataset,
+ norm_segment_duration_per_dataset.rename('fraction').round(1).astype(str)+" %"],
+ axis=1)
+maj_min_ratio_per_dataset['corpus_name'] = maj_min_ratio_per_dataset.index.get_level_values('corpus').map(corpus_names)
+maj_min_ratio_per_dataset['mode'] = maj_min_ratio_per_dataset.index.get_level_values('localkey_is_minor').map({False: 'major', True: 'minor'})
+```
+
+```{code-cell} ipython3
+fig = px.bar(maj_min_ratio_per_dataset.reset_index(),
+ x="corpus_name",
+ y="duration_qb",
+ color="mode",
+ text='fraction',
+ labels=dict(dataset='', duration_qb="duration in 𝅘𝅥", corpus_name='Key segments grouped by corpus'),
+ category_orders=dict(dataset=chronological_order)
+ )
+fig.update_layout(**STD_LAYOUT)
+fig.show()
+```
+
+## 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.
+
+```{code-cell} ipython3
+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)
+px.bar(bar_data, x='root', y='duration_qb', color='chord_type')
+```
+
+```{code-cell} ipython3
+relative_roots = all_chords[['numeral', 'duration_qb', 'relativeroot', 'localkey_is_minor', 'chord_type']].copy()
+relative_roots['relativeroot_resolved'] = 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'] = transform(relative_roots, 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
+```
+
+```{code-cell} ipython3
+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=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(**STD_LAYOUT,
+ legend=dict(
+ orientation='h',
+ xanchor="right",
+ x=1,
+ y=1,
+ )
+ )
+fig.update_yaxes(gridcolor='lightgrey')
+fig.show()
+```
+
+```{code-cell} ipython3
+print(f"Reduced to {len(set(bar_data.iloc[:,:2].itertuples(index=False, name=None)))} types. Paper cites the sum of types in major and types in minor (see below), treating them as distinct.")
+```
+
+```{code-cell} ipython3
+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}")
+```
+
+```{code-cell} ipython3
+mode_slices = dc.ModeGrouper().process_data(keys_segmented)
+```
+
+### Whole dataset
+
+```{code-cell} ipython3
+mode_slices.get_slice_info()
+```
+
+```{code-cell} ipython3
+unigrams = dc.ChordSymbolUnigrams(once_per_group=True).process_data(mode_slices)
+```
+
+```{code-cell} ipython3
+unigrams.group2pandas = "group_of_series2series"
+```
+
+```{code-cell} ipython3
+unigrams.get(as_pandas=True)
+```
+
+```{code-cell} ipython3
+k = 20
+modes = {True: 'MINOR', False: 'MAJOR'}
+for (is_minor,), ugs in unigrams.iter():
+ print(f"TOP {k} {modes[is_minor]} UNIGRAMS\n{ugs.shape[0]} types, {ugs.sum()} tokens")
+ print(ugs.head(k).to_string())
+```
+
+```{code-cell} ipython3
+ugs_dict = {modes[is_minor].lower(): (ugs/ugs.sum() * 100).round(2).rename('%').reset_index() for (is_minor,), ugs in unigrams.iter()}
+ugs_df = pd.concat(ugs_dict, axis=1)
+ugs_df.columns = ['_'.join(map(str, col)) for col in ugs_df.columns]
+ugs_df.index = (ugs_df.index + 1).rename('k')
+ugs_df.iloc[:50]
+```
+
+```{code-cell} ipython3
+chords_by_localkey = mode_slices.get_facet('expanded')
+chords_by_localkey
+```
+
+```{code-cell} ipython3
+for is_minor, df in chords_by_localkey.groupby(level=0, group_keys=False):
+ df = df.droplevel(0)
+ df = df[df.bass_note.notna()]
+ sd = ms3.fifths2sd(df.bass_note).rename('sd')
+ sd.index = df.index
+ sd_progression = df.groupby(level=[0,1,2], group_keys=False).bass_note.apply(lambda S: S.shift(-1) - S).rename('sd_progression')
+ if is_minor:
+ chords_by_localkey_minor = pd.concat([df, sd, sd_progression], axis=1)
+ else:
+ chords_by_localkey_major = pd.concat([df, sd, sd_progression], axis=1)
+```
+
+## Scale degrees
+
+```{code-cell} ipython3
+chords_by_localkey_minor
+```
+
+```{code-cell} ipython3
+import plotly.graph_objects as go
+from collections import Counter, defaultdict
+
+def make_sunburst(chords, mode):
+ in_scale = []
+ for sd, sd_prog in chords[['sd', 'sd_progression']].itertuples(index=False):
+ if len(sd) == 1:
+ in_scale.append(sd)
+ label_counts = Counter(in_scale)
+ labels, values = list(label_counts.keys()), list(label_counts.values())
+ #labels, values = zip(*list((sd, label_counts[sd]) for sd in sorted(label_counts)))
+ parents = [mode] * len(labels)
+ labels = [mode] + labels
+ parents = [""] + parents
+ values = [len(chords)] + values
+ fig =go.Figure(go.Sunburst(
+ labels=labels,
+ parents=parents,
+ values=values,
+ branchvalues="total"
+ ))
+ fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
+ return fig
+
+make_sunburst(chords_by_localkey_minor, 'minor')
+```
+
+```{code-cell} ipython3
+def make_sunburst(chords, mode):
+ in_scale = []
+ sd2prog = defaultdict(Counter)
+ for sd, sd_prog in chords[['sd', 'sd_progression']].itertuples(index=False):
+ if len(sd) == 1:
+ in_scale.append(sd)
+ sd2prog[sd].update(["∎"] if pd.isnull(sd_prog) else [str(sd_prog)])
+ label_counts = Counter(in_scale)
+ labels, values = list(label_counts.keys()), list(label_counts.values())
+ #labels, values = zip(*list((sd, label_counts[sd]) for sd in sorted(label_counts)))
+ parents = [mode] * len(labels)
+ labels = [mode] + labels
+ parents = [""] + parents
+ values = [len(chords)] + values
+ #print(sd2prog)
+ print(len(labels), len(parents), len(values))
+ for scad, prog_counts in sd2prog.items():
+ for prog, cnt in prog_counts.most_common():
+ labels.append(prog)
+ parents.append(scad)
+ values.append(cnt)
+ if cnt < 3000:
+ break
+ print(f"added {prog}, {scad}, {cnt}")
+ break
+
+ fig =go.Figure(go.Sunburst(
+ labels=labels,
+ parents=parents,
+ values=values,
+ branchvalues="total"
+ ))
+ fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
+ return fig
+
+make_sunburst(chords_by_localkey_minor, 'minor')
+```
+
+```{code-cell} ipython3
+fig =go.Figure(go.Sunburst(
+ labels=["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
+ parents=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],
+ values=[10, 14, 12, 10, 2, 6, 6, 4, 4],
+))
+fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
+
+fig.show()
+```
+
+```{code-cell} ipython3
+fig =go.Figure(go.Sunburst(
+ labels=["major", "Cain", "1", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
+ parents=["", "major", "major", "1", "1", "major", "major", "Awan", "major" ],
+ values=[10, 14, 12, 10, 2, 6, 6, 4, 4],
+))
+fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
+
+fig.show()
+```
+
+```{code-cell} ipython3
+df
+```
+
+```{code-cell} ipython3
+df = px.data.tips()
+fig = px.sunburst(df, path=['sex', 'day', 'time'], values='total_bill', color='time')
+fig.show()
+```
+
+```{code-cell} ipython3
+#localkey_major_no_repeats = ms3.segment_by_adjacency_groups(chords_by_localkey_major, ['sd', 'figbass'], )
+#localkey_major_no_repeats
+```
+
+```{code-cell} ipython3
+def safe_interval(fifths):
+ if pd.isnull(fifths):
+ return "∎"
+ return ms3.fifths2iv(fifths, smallest=True)
+```
+
+```{code-cell} ipython3
+def prepare_sunburst_data(chords):
+ chord_data = chords[chords.sd.str.len() == 1].copy()
+ chord_data["interval"] = ms3.transform(chord_data.sd_progression, safe_interval).fillna("∎")
+ chord_data.figbass.fillna('3', inplace=True)
+ chord_data["following_figbass"] = chord_data.groupby(level=[0,1,2],).figbass.shift(-1).fillna("∎")
+ return chord_data
+
+column2name = dict(
+ sd="scale degree",
+ figbass="bass figure",
+ interval="bass progression",
+ following_figbass="subsequent figure"
+)
+
+def rectangular_sunburst(
+ chords,
+ path = ['sd', 'figbass', 'interval'],
+ height = 1500,
+ title = "Sunburst",
+):
+ chord_data = prepare_sunburst_data(chords)
+ title = f"{title} ({' - '.join(column2name[col] for col in path)})"
+ return px.sunburst(
+ chord_data,
+ path=path,
+ height=height,
+ title=title,
+ )
+
+rectangular_sunburst(chords_by_localkey_major, title="MAJOR")
+```
+
+```{code-cell} ipython3
+rectangular_sunburst(chords_by_localkey_major, ['sd', 'interval', 'figbass', 'following_figbass'], title="MAJOR")
+```
+
+```{code-cell} ipython3
+rectangular_sunburst(chords_by_localkey_minor, title="MINOR")
+```
+
+```{code-cell} ipython3
+rectangular_sunburst(chords_by_localkey_minor, ['sd', 'interval', 'figbass'], title="MINOR")
+```
+
+```{code-cell} ipython3
+
+```
\ No newline at end of file
diff --git a/homepage/notebooks/utils.py b/homepage/notebooks/utils.py
new file mode 100644
index 0000000..6e6cd5a
--- /dev/null
+++ b/homepage/notebooks/utils.py
@@ -0,0 +1,122 @@
+import os
+from typing import List
+from functools import lru_cache
+import numpy as np
+import colorlover
+from git import Repo
+import plotly.express as px
+import pandas as pd
+
+STD_LAYOUT = {
+ 'paper_bgcolor': '#FFFFFF',
+ 'plot_bgcolor': '#FFFFFF',
+ 'margin': {'l': 40, 'r': 0, 'b': 0, 't': 40, 'pad': 0},
+ 'font': {'size': 15}
+}
+
+CADENCE_COLORS = dict(zip(('HC', 'PAC', 'PC', 'IAC', 'DC', 'EC'), colorlover.scales['6']['qual']['Set1']))
+CORPUS_COLOR_SCALE = px.colors.qualitative.D3
+TYPE_COLORS = dict(zip(('Mm7', 'M', 'o7', 'o', 'mm7', 'm', '%7', 'MM7', 'other'), colorlover.scales['9']['qual']['Paired']))
+
+CORPUS_NAMES = dict(
+ gastoldi_baletti = 'Gastoldi Baletti',
+ peri_euridice = 'Peri Euridice',
+ monteverdi_madrigals = 'Monteverdi Madrigals',
+ sweelinck_keyboard = 'Sweelinck Keyboard',
+ frescobaldi_fiori_musicali = 'Frescobaldi Fiori Musicali',
+ kleine_geistliche_konzerte = 'Schütz Kleine Geistliche Konzerte',
+ corelli = 'Corelli Trio Sonatas',
+ couperin_clavecin = 'Couperin Clavecin',
+ handel_keyboard = 'Handel Keyboard',
+ bach_en_fr_suites = 'Bach Suites',
+ bach_solo = 'Bach Solo',
+ couperin_concerts = 'Couperin Concerts Royaux',
+ pergolesi_stabat_mater = 'Pergolesi Stabat Mater',
+ scarlatti_sonatas = 'Scarlatti Sonatas',
+ wf_bach_sonatas = 'WF Bach Sonatas',
+ jc_bach_sonatas = 'JC Bach Sonatas',
+ mozart_piano_sonatas = 'Mozart Piano Sonatas',
+ pleyel_quartets = 'Pleyel Quartets',
+ beethoven_piano_sonatas = 'Beethoven Sonatas',
+ kozeluh_sonatas = 'Kozeluh Sonatas',
+ ABC = 'Beethoven String Quartets',
+ schubert_dances = 'Schubert Dances',
+ schubert_winterreise = 'Schubert Winterreise',
+ mendelssohn_quartets = 'Mendelssohn Quartets',
+ chopin_mazurkas = 'Chopin Mazurkas',
+ schumann_kinderszenen = 'R Schumann Kinderszenen',
+ schumann_liederkreis = 'R Schumann Liederkreis',
+ c_schumann_lieder = 'C Schumann Lieder',
+ liszt_pelerinage = 'Liszt Années',
+ wagner_overtures = 'Wagner Overtures',
+ tchaikovsky_seasons = 'Tchaikovsky Seasons',
+ dvorak_silhouettes = 'Dvořák Silhouettes',
+ grieg_lyric_pieces = 'Grieg Lyric Pieces',
+ mahler_kindertotenlieder = 'Mahler Kindertotenlieder',
+ ravel_piano = 'Ravel Piano',
+ debussy_suite_bergamasque = 'Debussy Suite Bergamasque',
+ bartok_bagatelles = 'Bartok Bagatelles',
+ medtner_tales = 'Medtner Tales',
+ poulenc_mouvements_perpetuels = 'Poulenc Mouvements Perpetuels',
+ rachmaninoff_piano = 'Rachmaninoff Piano',
+ schulhoff_suite_dansante_en_jazz = 'Schulhoff Suite Dansante En Jazz',
+)
+
+def color_background(x, color="#ffffb3"):
+ """Format DataFrame cells with given background color."""
+ return np.where(x.notna().to_numpy(), f"background-color: {color};", None)
+
+def corpus_mean_composition_years(df: pd.DataFrame,
+ year_column: str = 'composed_end') -> pd.Series:
+ """Expects a dataframe containing ``year_column`` and computes its means by grouping on the first index level ('corpus' by default).
+ Returns the result as a series where the index contains corpus names and the values are mean composition years.
+ """
+ return df.groupby(level=0)[year_column].mean().sort_values()
+
+def chronological_corpus_order(df: pd.DataFrame,
+ year_column: str = 'composed_end') -> List[str]:
+ """Expects a dataframe containing ``year_column`` and corpus names in the first index level.
+ Returns the corpus names in chronological order
+ """
+ mean_composition_years = corpus_mean_composition_years(df=df, year_column=year_column)
+ return mean_composition_years.index.to_list()
+
+
+@lru_cache()
+def get_corpus_display_name(repo_name: str) -> str:
+ """Looks up a repository name in the CORPUS_NAMES constant. If not present,
+ the repo name is returned as title case.
+ """
+ name = CORPUS_NAMES.get(repo_name, "")
+ if name == "":
+ name = ' '.join(s.title() for s in repo_name.split('_'))
+ return name
+
+
+def get_repo_name(repo: Repo) -> str:
+ """Gets the repo name from the origin's URL, or from the local path if there is None."""
+ if isinstance(repo, str):
+ repo = Repo(repo)
+ if len(repo.remotes) == 0:
+ return repo.git.rev_parse("--show-toplevel")
+ remote = repo.remotes[0]
+ return remote.url.split('.git')[0].split('/')[-1]
+
+def print_heading(heading: str, underline: chr = '-') -> None:
+ """Underlines the given heading and prints it."""
+ print(f"{heading}\n{underline * len(heading)}\n")
+
+def resolve_dir(directory: str):
+ return os.path.realpath(os.path.expanduser(directory))
+
+
+def value_count_df(S, thing=None, counts='counts'):
+ """Value counts as DataFrame where the index has the name of the given Series or ``thing`` and where the counts
+ are given in the column ``counts``.
+ """
+ thing = S.name if thing is None else thing
+ vc = S.value_counts().rename(counts)
+ normalized = vc / vc.sum()
+ df = pd.concat([vc.to_frame(), normalized.rename('%')], axis=1)
+ df.index.rename(thing, inplace=True)
+ return df
diff --git a/homepage/repo_readme.md b/homepage/repo_readme.md
new file mode 100644
index 0000000..2e80648
--- /dev/null
+++ b/homepage/repo_readme.md
@@ -0,0 +1,56 @@
+![Version](https://img.shields.io/github/v/release/DCMLab/debussy_preludes?display_name=tag)
+[![DOI](https://zenodo.org/badge/563841627.svg)](https://zenodo.org/badge/latestdoi/563841627)
+![GitHub repo size](https://img.shields.io/github/repo-size/DCMLab/debussy_preludes)
+![License](https://img.shields.io/badge/license-CC%20BY--NC--SA%204.0-9cf)
+
+
+This is a README file for a data repository originating from the [DCML corpus initiative](https://github.com/DCMLab/dcml_corpora)
+and serves as welcome page for both
+
+* the GitHub repo [https://github.com/DCMLab/debussy_preludes](https://github.com/DCMLab/debussy_preludes) and the corresponding
+* documentation page [https://dcmlab.github.io/debussy_preludes](https://dcmlab.github.io/debussy_preludes)
+
+For information on how to obtain and use the dataset, please refer to [this documentation page](https://dcmlab.github.io/debussy_preludes/introduction).
+
+# Claude Debussy – Préludes
+
+This dataset is part of [The Claude Debussy Solo Piano Corpus](https://github.com/DCMLab/debussy_piano).
+
+## Cite as
+
+> Laneve, S., Schaerf, L., Cecchetti, G., Hentschel, J., & Rohrmeier, M. (2023). The diachronic development of Debussy’s musical style: A corpus study with Discrete Fourier Transform. Humanities and Social Sciences Communications, 10(1), 289. https://doi.org/10.1057/s41599-023-01796-7
+
+## License
+
+Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License ([CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)).
+
+## Overview
+| file_name |measures|labels|
+|----------------------------|-------:|-----:|
+|l117-01_preludes_danseuses | 31| 0|
+|l117-02_preludes_voiles | 64| 0|
+|l117-03_preludes_vent | 59| 0|
+|l117-04_preludes_sons | 53| 0|
+|l117-05_preludes_collines | 96| 0|
+|l117-06_preludes_pas | 36| 0|
+|l117-07_preludes_ce | 70| 0|
+|l117-08_preludes_fille | 39| 0|
+|l117-09_preludes_serenade | 137| 0|
+|l117-10_preludes_cathedrale | 89| 0|
+|l117-11_preludes_danse | 96| 0|
+|l117-12_preludes_minstrels | 89| 0|
+|l123-01_preludes_brouillards| 52| 0|
+|l123-02_preludes_feuilles | 52| 0|
+|l123-03_preludes_puerta | 90| 0|
+|l123-04_preludes_fees | 127| 0|
+|l123-05_preludes_bruyeres | 51| 0|
+|l123-06_preludes_general | 109| 0|
+|l123-07_preludes_terrasse | 45| 0|
+|l123-08_preludes_ondine | 74| 0|
+|l123-09_preludes_hommage | 54| 0|
+|l123-10_preludes_canope | 33| 0|
+|l123-11_preludes_tierces | 165| 0|
+|l123-12_preludes_feux | 100| 0|
+
+
+*Overview table automatically updated using [ms3](https://johentsch.github.io/ms3/).*
\ No newline at end of file
diff --git a/homepage/requirements.txt b/homepage/requirements.txt
new file mode 100644
index 0000000..20ad274
--- /dev/null
+++ b/homepage/requirements.txt
@@ -0,0 +1,5 @@
+sphinx==5.3.0
+pydata-sphinx-theme==0.13.3
+myst-nb==0.17.1
+jupyter_sphinx==0.4.0
+-r notebooks/requirements.txt
\ No newline at end of file