MCMC (Markov Chain Monte Carlo) Musical Variation — User Guide

Phrase-level stochastic variation using an annealed Metropolis-style acceptance rule over pitch-shift, timing, and dynamic maps, with chain diagnostics for energy terms, proposal behaviour, and rendered states.

Author: Shai Cohen Affiliation: Department of Music, Bar-Ilan University, Israel Version: 1.4 (2026) Category: Composition / Markov Chain Monte Carlo (MCMC) License: MIT License Repo: https://github.com/ShaiCohen-ops/Praat-plugin_AudioTools
Contents:

What this does

MCMC (Markov Chain Monte Carlo) Musical Variation transforms a selected Sound by first dividing it into phrases, then exploring phrase-level states containing local pitch shifts, time ratios, dynamic scales, and one global transposition. At each chain step, one stochastic proposal modifies the current state. A weighted energy function scores the proposed state, and an annealed Metropolis-style rule decides whether to keep it.

Selected chain states are rendered back to audio. Each phrase can be pitch-shifted by tape-speed resampling, independently time-stretched with Praat's overlap-add Lengthen, dynamically scaled, and reassembled with 20 ms overlaps.

What is the state?

For each processed phrase i, the chain stores three values:

  • pc[i] — local transposition offset in semitones.
  • tm[i] — time ratio; 1.0 means unchanged phrase duration.
  • dm[i] — amplitude multiplier; 1.0 means unchanged phrase level before final normalization.

A separate integer transpo applies an additional global semitone shift to every phrase.

Methodological scope: this script uses a Metropolis-style acceptance probability for annealed exploration. It is not a strict Metropolis-Hastings posterior sampler. Several proposal operators use clipping or compensating changes and therefore do not satisfy the symmetry/reversibility assumptions required for a full Hastings interpretation.

Quick start

  1. Select exactly one Sound in Praat. The source must be at least 1 second long.
  2. Run MCMC_Musical_Variation.praat.
  3. Choose an Aesthetic mode. Conservative is the default.
  4. Choose Speed mode: Full Quality, Balanced, or Fast.
  5. Leave Seed = 0 for a fresh chain, or enter a non-zero integer to reproduce the same stochastic chain.
  6. Set chain length and Thinning_interval.
  7. Adjust phrase detection if the source contains useful silences between phrases.
  8. Set the PSOLA pitch range used by Lengthen.
  9. Choose the maximum number of rendered variations and whether individual variation objects should remain in the Objects list.
What does Thinning_interval mean here? A variation is rendered only when the current iteration number is divisible by Thinning_interval and the proposal at that iteration was accepted. It is therefore an accepted-state render gate at fixed iteration positions, not conventional MCMC thinning and not “every N accepted proposals.” If no iteration satisfies both conditions, the final chain state is rendered once as a fallback.

Markov Chain Monte Carlo (MCMC) method

Markov Chain Monte Carlo (MCMC) is a family of stochastic methods that explores a sequence of states by proposing changes and deciding whether to accept them. In this script, that idea is used compositionally: the chain explores phrase-level musical transformations under an annealed Metropolis-style acceptance rule.

Let the current state be θ with energy E(θ), and let θ′ be a proposed state. For each iteration:

1. Save the current state. 2. Select one proposal according to the active proposal weights. 3. Apply the proposal to obtain θ′. 4. Compute E(θ′). 5. Let ΔE = E(θ′) - E(θ). 6. If ΔE ≤ 0, accept. 7. Otherwise accept with probability exp(-ΔE / T). 8. If rejected, restore the previous state.

If annealing is enabled, temperature follows a linear schedule from Start_temp to End_temp over the requested number of MCMC steps. Conservative mode uses a fixed temperature of 0.8; Expressive and Exploratory replace the form temperatures with their preset schedules.

What does temperature do? Lower-energy proposals are always accepted. Higher-energy proposals can also be accepted, with probability decreasing as their energy increase grows relative to the current temperature. Higher temperature therefore permits broader exploration; lower temperature makes upward energy moves less likely.

Phrase model

Mono analysis source

The engine works from a mono source. Multichannel material is normally averaged to mono. Before using that average, the script measures RMS in every source channel. If the channel average is less than 10% of the strongest channel RMS, it is treated as near-cancellation and the strongest channel is used instead.

Silence-based segmentation

Praat's To TextGrid (silences) is called with the user-defined silence threshold, a 0.15 s minimum silence duration, and a 0.05 s minimum sounding duration. The script then keeps only sounding intervals whose duration is at least Min_phrase_s.

If fewer than two qualifying sounding intervals remain, the script does not stop. It replaces the segmentation with four equal segments spanning the whole source.

20-phrase limit: if more than 20 phrases are detected, only the first 20 are processed. The Info window prints a warning. Material after the twentieth qualifying phrase is not included in the rendered variations.
When silence detection succeeds, the detected silent gaps themselves are not rendered. The state operates on the sounding phrases and reassembles those phrases with overlaps. The reference duration used by the rhythmic energy term is therefore the sum of the original processed phrase durations, not the full source duration including stripped silences.

Energy function

The total energy is a weighted sum of seven terms:

E = w1·E1 + w2·E2 + w3·E3 + w4·E4 + w5·E5 + w6·E6 + w7·E7
TermWhat the code measures
E1 — transposition-class conformityFor each phrase, pc[i] + transpo - Tonal_center_st is reduced modulo 12 and measured against the nearest major-scale degree {0,2,4,5,7,9,11}. The source audio's actual pitch is not analysed here.
E2 — local contour smoothnessMean absolute difference between adjacent local pc values. Leaps above 12 semitones receive an additional penalty.
E3 — transposition rangeFor each phrase, total shift |pc[i] + transpo| is unpenalized up to 12 semitones; excess distance is penalized quadratically.
E4 — timing stabilityVariance of phrase time ratios plus a duration-preservation penalty comparing the transformed phrase-duration sum against the original silence-stripped phrase-duration sum.
E5 — dynamic coherenceVariance of dynamic multipliers, plus penalties above 1.6 or below 0.08.
E6 — phrase integrityPenalizes any transformed phrase duration below 0.25 s.
E7 — directional contour balanceIf more than 75% of adjacent local pitch moves go in the same direction, the excess monotonicity is penalized.
What does Tonal_center_st mean in this implementation? It shifts the major-scale reference used to score the transposition offsets. The script does not estimate the original phrase pitches or infer a musical key. Therefore E1 should not be read as a measurement of whether the sounding output itself belongs to a detected major key.

Lower energy means better fit to these selected criteria and weights. It is not a general measurement of musical quality.

Proposal operators

ProposalActual operation
Pitch NudgeSelect one phrase and add a rounded Gaussian semitone step with σ=1.5. A rounded zero is replaced by +1 or -1 with equal probability.
Dynamic SwellAdd Gaussian noise with σ=0.12 to one phrase's dynamic multiplier, clipped to 0.08–1.8.
Micro RubatoAdd Gaussian noise with σ=0.10 to one phrase's time ratio, clipped to 0.3–2.5, and compensate an adjacent phrase when possible to preserve their approximate combined duration.
Phrase TransposeSelect one phrase and add a uniformly chosen ±1 to ±5 semitones.
Temporal SwapSwap the time ratios of two adjacent phrases. The source phrase order is not swapped.
Global TransposeAdd a uniformly chosen ±1 to ±3 semitones to the global transposition.
Tempo WarpMultiply all time ratios by a Gaussian factor centered at 1.0 with σ=0.06; the factor is clipped to 0.75–1.25 and each resulting ratio to 0.3–2.5.
Dynamic ArchMultiply all phrase dynamics by one of three shapes: rising, falling, or sinusoidal arch, then clip each multiplier to 0.08–1.8.

Aesthetic modes

The three named modes override temperature behaviour, energy weights, and proposal weights. Custom keeps the form's temperature settings but uses the hard-coded Custom energy/proposal weights shown below.

ModeTemperatureEnergy weights E1–E7Proposal weights P1–P8
CustomForm values2.0, 1.5, 1.0, 1.5, 0.8, 1.2, 0.70.25, 0.12, 0.20, 0.15, 0.10, 0.08, 0.07, 0.03
Conservative0.8 fixed2.5, 2.0, 1.5, 2.0, 1.0, 1.2, 0.50.35, 0.15, 0.25, 0.05, 0.08, 0.03, 0.06, 0.03
Expressive3.0 → 1.02.0, 1.5, 1.0, 1.5, 0.8, 1.2, 0.70.25, 0.12, 0.20, 0.15, 0.10, 0.08, 0.07, 0.03
Exploratory8.0 → 2.01.5, 1.0, 0.7, 1.0, 0.6, 0.8, 1.20.18, 0.10, 0.15, 0.18, 0.12, 0.12, 0.10, 0.05

Audio rendering

Each rendered state is converted to audio phrase by phrase:

For each phrase i: semitones = pc[i] + transpo pitchRatio = 2^(semitones/12) target phrase duration = original phrase duration × tm[i] 1. Extract the source phrase. 2. If pitch shift is non-zero, override sampling rate by srcSr × pitchRatio, then resample back to srcSr. 3. Apply Lengthen (overlap-add) with factor tm[i] × pitchRatio so timing can be controlled independently of the tape-speed pitch shift. 4. Multiply samples by dm[i]. 5. Apply short edge fades. 6. Concatenate to the previous phrase with 20 ms overlap.

Lengthen is skipped when its calculated factor is within ±0.02 of 1.0. The factor is clamped to 0.1–8.0. The form's Pitch_floor_Hz and Pitch_ceiling_Hz are the pitch-range arguments passed to this overlap-add operation; they are not a source-pitch analysis range.

Speed modes

ModePraat resample precision
Full Quality50
Balanced20
Fast10

Each individual variation is peak-scaled to 0.95 after assembly. This preserves dynamic relationships within a variation but removes absolute peak-level differences between separately rendered variations.

Parameters

ParameterDefaultBehaviour
Aesthetic_modeConservativeCustom, Conservative, Expressive, Exploratory. Named modes replace temperatures and internal weight sets.
Speed_modeBalancedControls per-phrase resample precision: 50 / 20 / 10.
Seed00 = unpredictable chain; non-zero integer = reproducible proposals and acceptance draws. After all stochastic draws, the script returns Praat's global RNG to safe/unpredictable mode.
Mcmc_steps60Must be greater than 0.
Thinning_interval6Must be greater than 0. Defines eligible iteration numbers for rendering.
Start_temp2.0Used directly only by Custom mode.
End_temp0.5Used directly only by Custom mode.
AnnealonUsed directly only by Custom mode; named modes set their own annealing behaviour.
Silence_thresh_dB-35.0Passed to Praat silence segmentation.
Min_phrase_s0.5 sMinimum detected sounding interval retained as a phrase.
Pitch_floor_Hz60 HzLower pitch argument for Lengthen; must be below the ceiling.
Pitch_ceiling_Hz700 HzUpper pitch argument for Lengthen.
Tonal_center_st0Integer offset used by E1's transposition-class major-scale reference. Values are effectively handled modulo 12 by the energy calculation.
Max_variations8Must be greater than 0. Stops further render events after this many variations.
Keep_individual_variationsoffIf off, individual variation Sounds are removed after the combined output is built.
Draw_visualizationonDraws the analysis/process figure after the chain.
PlayonPlays the final combined output.
The form's default Aesthetic_mode index is 2, which selects Conservative. Its preset therefore overrides the form's displayed 2.0 → 0.5 temperature values with a fixed temperature of 0.8.

Visualization

The v1.4 figure is a process/diagnostic view of the chain. It uses numbered axes and aligned label rails, and separates the state trajectory from diagnostics about the energy terms and proposal operators.

Header and waveforms

Energy trace

The full-width energy panel combines several chain variables without putting them on one numerical scale:

What is the initial-energy reference? The unchanged state is evaluated before the chain begins. The dashed reference therefore provides a baseline against which the later accepted-state energies can be compared.

Weighted energy components

The Energy components panel plots the seven terms as their actual weighted contributions wN × EN, not as raw unweighted criteria. The traces are labelled scale, voice, range, rhythm, dyn, phrase, and contour. Their sum is the total energy used by the acceptance rule.

The component values follow the current accepted state: after a rejected proposal the previous accepted component values are retained.

Proposal diagnostics

The Proposal diagnostics panel summarizes all eight proposal types over the complete chain:

This panel reports what the chain actually attempted; it does not alter proposal probabilities or acceptance decisions.

Pitch-contour heatmap

The heatmap shows phrase-level transposition state, not measured audio pitch:

What is the pitch heatmap showing? The values are the chain's transposition offsets in semitones. The src row is a state reference, not an acoustic pitch analysis of the source recording.

Energy per rendered variation

One bar is drawn for each rendered variation. The bar height and printed value are the stored total energy of that state; lower values mean better fit to the selected energy criteria and weights. The x-axis explicitly refers back to the render iterations shown in the Energy trace.

Summary

The summary reports source duration, aesthetic mode, processed phrase count, temperature range, seed, chain steps, accepted-step count and rate, number of rendered variations, thinning interval, initial and final energy, energy delta, active energy weights, and Tonal_center_st.

v1.4 also prints a short heuristic acceptance-rate note. This note is derived from the overall acceptance percentage alone; it is a diagnostic prompt rather than a statistical inference about why a particular acceptance rate occurred. The per-proposal diagnostics and energy trace provide the more specific evidence for interpreting chain behaviour.

Output, naming, and edge cases

Variation objects

Rendered variations are named <source>_mcmc_v1, ..._v2, and so on. Their durations may differ because time ratios change, silence intervals may have been removed, and each phrase join uses a 20 ms overlap.

Combined output

Before combining, shorter variations are zero-padded to the longest variation duration.

The combined output is peak-scaled to 0.95. If more than two channels are present, the Info window warns that ordinary stereo playback may expose only two channels meaningfully.

Guaranteed fallback

If no accepted proposal occurs at an iteration eligible for rendering, the script renders the final chain state once. This guarantees at least one output variation.

Reproducibility

A non-zero Seed reproduces the stochastic chain because both proposal selection/values and acceptance draws use the seeded Praat RNG. After the chain completes, the global RNG is reset to safe/unpredictable mode; subsequent scripts do not inherit the deterministic sequence.