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.
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.
Quick start
- Select exactly one Sound in Praat. The source must be at least 1 second long.
- Run
MCMC_Musical_Variation.praat. - Choose an Aesthetic mode. Conservative is the default.
- Choose Speed mode: Full Quality, Balanced, or Fast.
- Leave Seed = 0 for a fresh chain, or enter a non-zero integer to reproduce the same stochastic chain.
- Set chain length and Thinning_interval.
- Adjust phrase detection if the source contains useful silences between phrases.
- Set the PSOLA pitch range used by
Lengthen. - Choose the maximum number of rendered variations and whether individual variation objects should remain in the Objects list.
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:
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.
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.
Energy function
The total energy is a weighted sum of seven terms:
| Term | What the code measures |
|---|---|
| E1 — transposition-class conformity | For 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 smoothness | Mean absolute difference between adjacent local pc values. Leaps above 12 semitones receive an additional penalty. |
| E3 — transposition range | For each phrase, total shift |pc[i] + transpo| is unpenalized up to 12 semitones; excess distance is penalized quadratically. |
| E4 — timing stability | Variance 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 coherence | Variance of dynamic multipliers, plus penalties above 1.6 or below 0.08. |
| E6 — phrase integrity | Penalizes any transformed phrase duration below 0.25 s. |
| E7 — directional contour balance | If more than 75% of adjacent local pitch moves go in the same direction, the excess monotonicity is penalized. |
Lower energy means better fit to these selected criteria and weights. It is not a general measurement of musical quality.
Proposal operators
| Proposal | Actual operation |
|---|---|
| Pitch Nudge | Select 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 Swell | Add Gaussian noise with σ=0.12 to one phrase's dynamic multiplier, clipped to 0.08–1.8. |
| Micro Rubato | Add 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 Transpose | Select one phrase and add a uniformly chosen ±1 to ±5 semitones. |
| Temporal Swap | Swap the time ratios of two adjacent phrases. The source phrase order is not swapped. |
| Global Transpose | Add a uniformly chosen ±1 to ±3 semitones to the global transposition. |
| Tempo Warp | Multiply 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 Arch | Multiply 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.
| Mode | Temperature | Energy weights E1–E7 | Proposal weights P1–P8 |
|---|---|---|---|
| Custom | Form values | 2.0, 1.5, 1.0, 1.5, 0.8, 1.2, 0.7 | 0.25, 0.12, 0.20, 0.15, 0.10, 0.08, 0.07, 0.03 |
| Conservative | 0.8 fixed | 2.5, 2.0, 1.5, 2.0, 1.0, 1.2, 0.5 | 0.35, 0.15, 0.25, 0.05, 0.08, 0.03, 0.06, 0.03 |
| Expressive | 3.0 → 1.0 | 2.0, 1.5, 1.0, 1.5, 0.8, 1.2, 0.7 | 0.25, 0.12, 0.20, 0.15, 0.10, 0.08, 0.07, 0.03 |
| Exploratory | 8.0 → 2.0 | 1.5, 1.0, 0.7, 1.0, 0.6, 0.8, 1.2 | 0.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:
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
| Mode | Praat resample precision |
|---|---|
| Full Quality | 50 |
| Balanced | 20 |
| Fast | 10 |
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
| Parameter | Default | Behaviour |
|---|---|---|
| Aesthetic_mode | Conservative | Custom, Conservative, Expressive, Exploratory. Named modes replace temperatures and internal weight sets. |
| Speed_mode | Balanced | Controls per-phrase resample precision: 50 / 20 / 10. |
| Seed | 0 | 0 = 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_steps | 60 | Must be greater than 0. |
| Thinning_interval | 6 | Must be greater than 0. Defines eligible iteration numbers for rendering. |
| Start_temp | 2.0 | Used directly only by Custom mode. |
| End_temp | 0.5 | Used directly only by Custom mode. |
| Anneal | on | Used directly only by Custom mode; named modes set their own annealing behaviour. |
| Silence_thresh_dB | -35.0 | Passed to Praat silence segmentation. |
| Min_phrase_s | 0.5 s | Minimum detected sounding interval retained as a phrase. |
| Pitch_floor_Hz | 60 Hz | Lower pitch argument for Lengthen; must be below the ceiling. |
| Pitch_ceiling_Hz | 700 Hz | Upper pitch argument for Lengthen. |
| Tonal_center_st | 0 | Integer offset used by E1's transposition-class major-scale reference. Values are effectively handled modulo 12 by the energy calculation. |
| Max_variations | 8 | Must be greater than 0. Stops further render events after this many variations. |
| Keep_individual_variations | off | If off, individual variation Sounds are removed after the combined output is built. |
| Draw_visualization | on | Draws the analysis/process figure after the chain. |
| Play | on | Plays the final combined output. |
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
- Header: aesthetic mode, source name, processed phrase count, chain length, rendered-variation count, and acceptance rate.
- Source waveform: the mono analysis source. Dotted vertical lines mark the starts of the processed phrases.
- Variation 1 waveform: the first rendered variation, with its stored energy value. Source and variation are drawn as separate time-domain panels.
Energy trace
The full-width energy panel combines several chain variables without putting them on one numerical scale:
- Red line: the accepted-state total energy recorded after each MCMC step.
- Green line: the lowest recorded post-step energy reached so far.
- Dashed horizontal reference: the true energy of the unchanged initial state before step 1.
- Top tick row: green marks accepted proposals and red marks rejected proposals.
- Lilac vertical bands: the actual iterations at which audio variations were rendered, using the stored
renderStepvalues. - Dotted blue line: temperature, read from its own numbered right-hand axis. It is no longer rescaled into the energy axis.
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:
- Pale bar: number of times the proposal type was tried.
- Solid bar: number of those proposals that were accepted.
- accepted/tried: the counts printed for each proposal.
- acceptance rate: accepted proposals divided by trials for that proposal type.
- mean dE: mean proposed energy difference
proposedEnergy - currentEnergy, measured before the accept/reject decision.
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:
- src row: the unchanged starting local contour stored before the chain.
- V1, V2, ...: each rendered state's
pc + transpovalue for every processed phrase. - Colour: blue represents the lower value found in the displayed matrix and red the higher value.
- Cell numbers: when both phrase count and variation count are at most 10, the semitone value is printed inside each cell.
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.
- If exactly one variation exists, the output is mono and named
<source>_mcmc_output. - If two or more variations exist, each variation becomes a separate channel and the output is named
<source>_mcmc_multichannel. - A 3–8 variation result therefore has 3–8 channels. It is not a stereo mix.
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.