Wednesday, October 29, 2025

Zero-Mode Composition: Palindrome, Inversion, and the Art of Cancellation

 


Majorana zero modes → self-conjugate motifs. Palindromic, sign-reversing lines that annihilate on superposition.

This essay proposes a compositional paradigm that fuses the physics of Majorana zero modes with the musical idea of self-conjugate motifs: lines that are their own inverse under time reversal and designated sign changes. Palindromic structure supplies the temporal geometry; sign inversion supplies the energetic algebra. When the original and its conjugate are superposed under precise conditions, they annihilate. The result is a practice where sound is composed together with its own engineered disappearance, so the work articulates presence as the management of absence.

Primer: from Majorana to motif

In condensed-matter physics, a Majorana mode is a quasiparticle that is its own antiparticle. At zero energy it behaves like a real degree of freedom, not paired with a distinct complex conjugate. Two such modes separated in space can encode nonlocal information; bringing them together allows fusion that yields either occupancy or vacuum. Translating this: a musical motif can be written to equal its own conjugate under a defined involution, and two spatially or formally separated instances may be made to fuse (cancel) when brought into coincidence.

  • Time involution: T[m](t)=m(Tt)\mathcal{T}[m](t) = m(T-t)

  • Sign conjugation: C[m]flips a chosen subset of parameters (phase, spectral centroid, dynamic, or registral inversion).

  • Majorana condition: a motif mm is self-conjugate when CT[m]=m\mathcal{C}\mathcal{T}[m] = m up to a small tolerance.

Annihilation then targets the superposition

s(t)=m(t)+ϕCT[m](t),ϕ=1,s(t)=m(t)+\phi\,\mathcal{C}\mathcal{T}[m](t), \quad \phi=-1,

achieving s(t)0s(t)\approx 0 under practical thresholds.

2) Theoretical assumptions (axioms for composition)

  1. Realness: Notation selects a parameter set whose conjugation is involutive and audible. Examples: phase inversion in electronics, pitch inversion around an axis, dynamic inversion around a reference, timbral complementarity defined by a spectral mask.

  2. Locality and nonlocality: Conjugate material may be remote in page space, stage space, or time, but is addressable through explicit links.

  3. Tolerance: Perfect annihilation is a limit case. The score encodes an error budget ϵ\epsilon for timing, tuning, and energy; partial annihilation is used dramaturgically.

  4. Palindromic governance: Time is tiled so that returns are not repetitions but returns as negations.

  5. Energetic accounting: The work is a ledger. Every increase of intensity demands a matched negative in its conjugate layer.

  6. Reversibility with memory: Even canceled sound leaves procedural residue (breath debt, bow pressure bias, standing feedback). The piece writes, cancels, and then lives with the dent.

3) Philosophical ground

  • Identity and difference: A self-conjugate motif is an object whose identity includes its own undoing. The figure does not oppose its other; it contains its other as a rule of transformation.

  • Temporal ethics: Palindromic time reorients authorship from accumulation to accountability. Form does not grow, it balances.

  • Presence as decision: Sound becomes a decision among mutually exclusive states. The silence that results from cancellation is not void; it is evidence of a fulfilled constraint.

  • Archive and erasure: The score acts as an archive of procedures, not a repository of sonic tokens. Erasure is not deletion but the last, most disciplined mark.

4) The algebra of annihilation (usable metrics)

Let ,\langle \cdot,\cdot\rangle be an energy-weighted inner product over the realization space (time–frequency–amplitude). Define the annihilation index



A(m)  =  1m+ϕCT[m]m+CT[m],ϕ=1.

\mathcal{A}(m) \;=\; 1 - \frac{\|m + \phi\,\mathcal{C}\mathcal{T}[m]\|}{\|m\|+\|\mathcal{C}\mathcal{T}[m]\|}, \quad \phi=-1.

Values near 1 indicate near-perfect cancellation. For performance notes, display A\mathcal{A} targets at sectional boundaries. A spectral variant weights bands by masks so you can cancel only the band you choose and leave the scar elsewhere.

5) Notational toolkit (traditional to radical)

Anchors

  • Conventional staves, clefs, articulations, microtonal accidentals; tuplets and irrational meters for palindromic tessellation.

Self-conjugacy devices

  • Self-conjugate rune (◊) on a motif head: declares that its printed companion is CT[m]\mathcal{C}\mathcal{T}[m].

  • Palindrome gates: vertical mirrors. Material between mirrors is performed forward and backward with specified inversion rules.

  • Sign bars: thin overlines with ± icons that label which parameter flips on return: phase, dynamic, spectral tilt, bow pressure.

Superposition & erasure

  • Annihilation brackets ⟦ ⟧: when two bracketed lines align temporally, performers enforce the superposition ++\, and states.

  • Zero glyph (∅): marks the expectation of null output at a bus, mic, or acoustic focus.

  • Memory ledgers: faint lines that persist after an impact, biasing subsequent intonation or color until cleared by ∅.

Linkage & locality

  • EPR-IDs on ties to connect remote instances; electronics cross-route those channels for phase inversion and latency compensation.

  • Axis stamps: note the inversion axis for pitch or spectrum on the system margin.

Electronics

  • Phase-flip cues: small ▷± tags aligned with noteheads, triggering 180° phase inversion or complementary filtering.

  • Correlation meters: miniature dials printed at staff edges; when the needle reaches the mark, the section may proceed to cancellation.

6) Temporal design: palindromic, sign-reversing time

Structure the work as tiled panels P1,P2,,PnP_1, P_2, …, P_n. Each PkP_k carries:

  • a forward script FkF_k and its conjugate Fk\*=CT[Fk]F_k^\*=\mathcal{C}\mathcal{T}[F_k],

  • a defect map that deliberately misaligns select parameters on the return, ensuring controlled partial survival after annihilation.
    This yields a dramaturgy of returns that do not restore, only reconcile.

7) Performance practice

  • Calibration: begin rehearsals by nulling pairs with electronics. Tune latency so summed signals produce audible minima at the designated focus.

  • Breath and bow economy: teach players to feel the ledger—after a loud forward stroke, the return performs with an inverted pressure to match mechanical conditions of cancellation.

  • Micro-alignment: assign one performer per subgroup as the conjugation captain to cue mirrors and sign flips.

  • Error as contour: the work tolerates controlled error ϵ\epsilon. Drift becomes a halo around the annihilation instant; score it as intended aura, not failure.

8) Transformational implications

  1. Form as conservation: You compose a conservation law, not a sequence of episodes. Energy is borrowed in the forward pass and repaid in the return.

  2. Nonlocal counterpoint: Musical meaning propagates through portals. A gesture on one stand carries a debt that can be discharged across the hall minutes later.

  3. New virtuosity: Mastery shifts from passagework to precision of negation. The most difficult feat is to make something not sound.

  4. Audience phenomenology: Cancellations localize; the “black spot” of silence moves through space as a choreographed object.

  5. Ethic of attention: The piece refuses excess. Every gesture is accountable to its own unwriting.

9) Three models for immediate use

Model A: Majorana Canon

  • Two lines begin at opposite margins; one is printed, the other only as an MCB code ring. As players decode and realize the conjugate, the lines meet mid-page under ⟦ ⟧ and ∅. The null is staged at a single loudspeaker; the hall hears the approach and the disappearance.

Model B: Palindromic Fault

  • A five-panel palindrome P1P2P3P2\*P1\*P_1 P_2 P_3 P_2^\* P_1^\* where only spectral bands 1 and 3 cancel. Bands 2 and 4 are deliberately mis-signed, leaving a colored seam. The audience learns to hear what remains when history is repaid.

Model C: Self-Conjugate Solo

  • One performer with live electronics performs a motif set bearing the ◊ rune. The rig auto-generates CT[m]\mathcal{C}\mathcal{T}[m] with programmable tolerances; the player’s job is to catch the null by micro-timing. A moving ∅ focus sweeps the space.

10) Implementation crib (practical)

  • Electronics: parallel buses per motif; one stays dry, one passes through a phase-flip and complementary EQ; summed to a target. Use cross-correlation to drive a meter that the performer can read.

  • Tuning: if pitch inversion is used, choose an axis that respects fingerings or slide positions; print it as an “axis staff” above the line.

  • Page design: wide margins carry the conjugation code; keep core notation 65–70 percent density for overlays.

  • Legend: include a one-page symbol sheet for ◊, ∅, ⟦ ⟧, ± bars, axis stamps, and EPR-IDs.

11) Coda

The promise of the Majorana metaphor is not sci-fi optics; it is discipline. A self-conjugate motif is a contract: whatever is set in motion must be met by its precise counter-motion. Palindrome makes time hospitable to this contract; sign reversal makes it audible. The score stops being a map of events and becomes a law the performance enforces. When annihilation happens and the room tips into cultivated nothing, that nothing is not absence; it is the trace of a perfectly kept agreement.

Sunday, October 26, 2025

Toward a Notation: The Pharmacological System in the Shadow of the Pharmaco-Aesthetic

 




Toward a Notation: The Pharmacological System in the Shadow of the Pharmaco-Aesthetic

Cabinets, Codices, and the Architecture of Belief

If the 20th-century artist once turned to the grid as a site of aesthetic order and ontological inquiry, the 21st-century artist-composer may be said to turn to the pharmacy. The shelves, the doses, the packets and capsules...symmetrical, seductive, and vaguely tyrannical form the contemporary altar of certainty. We find a profound and meticulously developed extension of this pharmaco-aesthetic tradition, now rendered through a new notational system: a compendium of circular, color-coded diagrams accompanied by invented pharmacological profiles. These are not merely visual provocations or poetic conceits; they are the structural glyphs of a musical language built atop the logics of compulsion and cure, diagnosis and transformation.



What I assemble, piece by piece, is the sonic corollary of a pharmacy shelf. It metaphoriclly translates to an immense, semiotic archive in which every diagram is at once a sign, a score, and a symptom. While I do not mimic the gallery-space-as-drugstore installations of my visual predecessors, the genealogy of this work is clear. It emerges in the long shadow of an artistic tradition that transformed the medicinal object into a fetishized symbol of faith, addiction, seduction, and the failure of reason.



We do not need to mention names to recognize this inheritance. There exists a well-known artist whose pill cabinets, pharmacy reconstructions, and seductive vitrines of drug paraphernalia have turned the act of medical consumption into a spectacle of aesthetic and existential reflection. Where that artist builds rooms out of dosage forms, I build an entire language. Where that earlier work invited the viewer to gaze into the spectacle of cure, mine invites us to perform it as an act of sonic inscription.



The Diagram as Dose: Score as Pharmakon

The circular notational diagrams that form the basis of my systems are more than visual devices. They are prescription objects, analogues to capsules intended not for ingestion but for interpretive release. Each one is layered with affective valence, its concentric color fields operating like chemical rings, each with its own temporal and physiological implications. Their titles, Azarthræquineticyn™, Glavendral™, Beurovenza echo the naming conventions of commercial pharmaceuticals: polysyllabic, vaguely Latinate, simultaneously authoritative and hallucinatory.


What Hirst achieved by stockpiling hundreds of manufactured pills into sterilized cabinets (inviting both fetish and critique), I achieve by transposing the logic of the dosage unit into the syntax of musical performance. In both cases, the viewer (or performer) is suspended between trust and doubt. The thing before them is a diagram, a promise, a warning. It does not say, “play this,” but “this is how the condition is structured.” The performer becomes a pharmacologist of sound, administering meaning through interpretation, dosage through gesture.

This shift from cabinet to codex is more than formal. Hirst’s works, particularly in Cathedrals Built on Sand, render pharmaceuticals as objects of religious devotion.  They are altarpieces of addiction and misplaced belief. My systems internalize this structure and turns it outward again as process. The circular score is the shrine; the performance, the liturgy. Interpretation becomes a sacramental act: precise, ritualized, opaque, and absolutely necessary.




Clinical Erotics: Color, Repetition, and Semantic Overload

Both my lexicon and its aesthetic predecessors share a visual and linguistic logic governed by overabundance. In the cabinets: hundreds of pills, nearly identical, each alluring, mysterious, absurd in number. In my diagrams: infinite rings of color, some harmonious, others jarring are coded with invented afflictions and implausible protocols. We are offered not clarity but controlled excess: too many pills to comprehend, too many rings to parse, too many diseases to ever master.

And yet it is in this overload that a strange erotics of interpretation emerges. In Hirst’s displays, the temptation was literal, candy-colored pills arranged like offerings. In my scores, the temptation is hermeneutic. The performer is seduced by the complexity of the diagram, the possibility that, with enough time, one could learn this language. One could treat it not as an image, but as a functional grammar, a system of keys unlocking rare sonic truths.

Indeed, my naming strategy mimics the very cultural machinery of pharmaceutical branding of names that suggest efficacy, softness, potency, mystery. Like the Prozac and OxyContin of the marketplace, Evinectys™ or Bravencurialthrum™ draw the eye and mouth toward them, even before meaning is affixed. They beg to be said aloud, performed, tasted. Just as the pill is engineered to appeal to the consumer’s desire for immediate resolution, these notational compounds appeal to the performer’s desire for a fix which becomes a stable symbol, a totalized prescription for what the work “means.”

But no such fix exists. This is perhaps the most profound tie between my work and my artistic predecessor: we both structure our works as closed systems with no exit. You are inside the logic now. There are no translations. You can catalogue the pills, count the rings, say the names, but no revelation will come. The meaning lies in the act itself: to classify, to name, to administer, to repeat.

Rare Affliction as Genre: The Disease as Form

What I offer, ultimately, is a shift in what it means to compose. I do not write melodies. I names syndromes. I dos not orchestrate textures. I code regimens. Each diagram corresponds not to a piece, but to a condition...real, invented, or misdiagnosed. And in doing so, I place composition squarely in the realm of pathological poetics. What the cabinets suggest as symptoms (overuse, addiction, fetishism), I install as genres.






Every syndrome is a musical condition. Systemic Delay Echo Syndrome implies recursive, ghosted materials. Somatic-Lexical Reversal Syndrome demands confusion between text and gesture, between utterance and touch. Narrative Urine Saturation, despite its absurdity, suggests saturation as form (flow, blockage, flood). These are not metaphors for music. They are music, at the level of diagnosis. To play the score is to enter the affliction, to inhabit it as form.


Just as Hirst’s works demanded the viewer confront their own belief in medical certainty, while never actually providing it, my lexicon offers musical conditions that cannot be resolved. They must be endured. Interpreted. Played. Over and over.

The Score as Clinical Fiction

The most radical gesture of this system is its commitment to clinical fiction. It borrows the format, tone, and formality of medical documents.  This is not a critique of medicine, but to propose that musical notation could be as prescriptive, as terrifying, as bureaucratically beautiful as a pharmaceutical label. Each diagram functions as both a fantasy and a warning: “This may treat your condition, but we can’t say how.”


In doing so, I implicate the composer in the same apparatus as the pharmacologist or the brand strategist (a curious analogy). The act of naming a new syndrome complete with invented therapy and regimen is not unlike naming a new musical form, with genre, idiom, and duration. My work suggests that composition is already prescription, that every piece of music is already a treatment protocol for a condition we may not yet have diagnosed.


From Vitrine to Lexicon

Where one artist offered vitrines filled with color-coded salvation, another has offered a lexicon filled with symbolic affliction. What was once displayed to seduce the eye is now encoded to seduce the mind, the body, and the interpretive drive of the performer. My pharmacological notation system is not a commentary on that earlier pharmaco-art, it is its mutation. It is what happens when the pills stop working, and you begin writing new ones yourself. When art ceases to display the object of desire and instead becomes the manual for how to administer meaning.

We are, in the end, left not with a cabinet but a codex. Not with belief, but with practice. This is not the death of notation, nor its resurrection.  It  is its reformulation as a speculative clinic, a registry of undiagnosable sound, a pharmakon of pure musical contagion.


Saturday, October 25, 2025

Prescriptive Noise: Composing with the Pharmacopoeia by Bil Smith

 



Prescriptive Noise: Composing with the Pharmacopoeia
By Bil Smith


My intent has never been to render music in the traditional sense. Rather, it is to transmute the language of authority, whether be it clinical, legislative, or linguisticinto notation. In Prescriptive Noise, I found in the pharmacopoeia not just metaphor but medium. It offered a dense, bureaucratic lexicon that mirrored the regulatory pressures of composition itself. Dosage became a form of articulation. Adverse events, my dynamics. Contraindications, the structural parameters of ensemble behavior. It was never about drugs.  It was about systems of control masked as systems of care.

The materials of the pharmaceutical world are precise, impersonal, codified and designed to regulate and minimize ambiguity. But I was interested in what happens when that clarity is turned inside out. When 500 mg q8h becomes a percussive instruction. When sublingual or extended-release becomes a cue for how a timbre might decay or remain latent across pages of silence. I found these terms beautiful in their violence, elegant in their administrative coldness.

Damien Hirst's "Pharmacy London" Project

I have often admired Damien Hirst, not for the repetition, but for the audacity of his taxonomy. In his work, pharmaceuticals are flattened into color and shape, depersonalized until they become aesthetic. But I wanted to push further: to resubjectivize that aesthetic, to make the performer complicit in its effects. My scores aren't visual inventories.  They’re volatile compounds. The page might look clinical, minimal even, but it’s saturated with potential side effects.



There’s a reason I include boxed warnings in my scores. They are not performative gimmicks. They are functional constraints. When I write “Do not execute concurrently with color fields,” it’s not just instruction—it’s a reflexive device. It’s a challenge to the notion of compliance. Pharmaceutical language is inherently conditional, always hedging: may cause dizziness, may interact with other agents, not for use in patients with a history of interpretive consistency. I adopt that tone not to parody it, but to implicate it within musical practice.

Page from the score: "Bolribine" for Solo Oboe


My use of microdosing terminology such as ramp-up titrationsaturation threshold, and half-life is not mere stylistic borrowing. These are structures that replace form. Why write in movements when you can compose with pharmacokinetics? Why phrase in bars when time can be governed by absorption curves?

Page from the score: "Bolribine" for Solo Oboe

And perhaps most importantly: these scores are written to resist completion. Like a trial drug under accelerated review, they exist in a phase of perpetual testing. The performer is not a vessel of interpretation, but a clinician. They observe, they respond, they encounter the music not as narrative, but as protocol. Failure, misreading, improvisation under constraint?  None of these are bugs.

They are baked into the compound.

In Prescriptive Noise, the music is not what is heard, but what is risked.

The score is a prescription.
The performance, an off-label use.
And the silence between events?
That’s the half-life.

A Pseudocode: Nonlinear Polyrhythm: A Multiverse Fork and Merge Logic

 


Nonlinear Polyrhythm: What the Pseudocode Does and How It Works

Purpose 

The program simulates several parallel musical timelines that each run their own polyrhythms with nonlinear tempo behavior, lets those timelines fork and diverge, then merges them back into a single canonical event stream that preserves causality and rhythmic sense.

High level idea

  • Each timeline is a universe that contains tracks with tempo ratios like 5 over 4 or 7 over 6.

  • Time advances in discrete ticks while music advances in beats.

  • A smooth nonlinear field warps local tempo and a tiny microslip adds natural timing drift.

  • At any moment you can fork a new universe that changes ratios or fields.

  • Later you merge universes using a rhythmic window, conflict free rules, and a consonance lattice so the result sounds coherent.

  • Every musical event carries vector and Lamport clocks inside a DAG so ordering stays consistent.

Core data model

  • Rational tempo ratios express polyrhythms cleanly. A track with 5 over 4 runs five beats for every four base beats.

  • Clocks include a Lamport counter, a vector clock, a beat index, and a tick count. These give you partial ordering across concurrent tracks and across forks.

  • Events hold timing in seconds and in beats, a payload such as a note, and a set of parents for DAG ancestry.

  • Universe bundles tracks, the DAG, a nonlinear tempo field, a merge policy, and global scheduler settings.

Timing and emission

On every scheduler tick:

  1. Convert base BPM to beats per second.

  2. Scale by the track’s rational tempo ratio.

  3. Modulate by the nonlinear field θ that depends on time, beat, and track id.

  4. Add a small microslip from a logistic map to mimic human timing.

  5. Accumulate until one beat is crossed, then emit an Event with current beat time, update the clock, and push it onto the track queue and the DAG.

Why two time bases
Seconds drive the scheduler and physics. Beats drive musical alignment, quantization, and merge decisions.

Forking a universe

Forking makes a deep copy, assigns a fresh universe id and path id, and applies a mutation function. A typical mutation changes one track’s ratio or swaps in a different θ field for metric modulation. Vector clocks are advanced so descendants are distinguishable from their ancestors.

The merge problem

Two universes A and B contain overlapping but diverged sequences. The goal is to produce C with:

  • No cycles in the event graph.

  • Stable ordering when events are concurrent.

  • Minimal rhythmic clash across tracks.

  • Clear lineage so later tools can audit where material came from.

Merge strategy in detail

  1. Alignment grid
    Compute a beat quantum from the least common multiple of denominators across all track ratios in A and B. This creates a musically meaningful lattice that respects the polyrhythms.

  2. Windowing
    Slide a beat window across the joint beat range. For each window, collect events from A and B.

  3. Bucketing
    Quantize events into buckets keyed by the alignment grid. This reduces the search space and lets the code reason about near coincidences.

  4. Within track resolution
    When a bucket contains multiple events from the same track, fold them with a CRDT function named last writer wins with Lamport.

    • Higher Lamport time wins.

    • Ties break by stable id order.
      This choice is associative, commutative, and idempotent, which guarantees that repeated merges or out of order merges give the same result.

  5. Across track consonance
    Snap fractional beats that are within a tiny epsilon to a small set of rational positions such as 1 over 3 or 2 over 3 or 3 over 4. This creates rhythmic consonance without heavy quantization. The policy can also rank proximity to simple ratios when ties occur.

  6. Lineage and DAG
    Insert merged events into C, copy or union ancestry as configured, and add edges to parents that are present. The merged universe keeps clocks monotonic and the DAG acyclic.

Correctness checks

  • validate_dag traverses edges to ensure no cycles.

  • verify_monotonic_clocks ensures that Lamport time never decreases along edges. These checks guard against subtle ordering bugs during merge.

The driver run

  • Start A with three tracks at ratios 5 over 4, 4 over 3, and 7 over 6 at 96 BPM.

  • Advance for several virtual minutes to fill the DAG with events.

  • Fork to B and mutate the third track to 11 over 8 with a different θ warp.

  • Run A and B in parallel.

  • Merge to C.

  • Validate and export a score file ordered by beat time, track, and Lamport time.

Musical consequences

  • Nonlinear tempo produces evolving phase relationships between tracks. Polyrhythms breathe rather than staying locked to a static grid.

  • Microslip adds human feel without destroying causality or order.

  • Fork and merge lets a composer audition alternate metric futures, then reconcile them into one recording or notated score while keeping what worked in each branch.

  • Consonance lattice preserves complex relationships yet prefers small rational alignments where ears expect relief.

Why CRDTs and clocks here

Parallel musical timelines create true concurrency. CRDT folding plus Lamport and vector clocks provide deterministic results without a global lock. This matters when the same material is edited or generated in different branches and later recombined.

Parameter intuition

  • window_beats
    Larger windows absorb more divergence but risk blurring intended accents. Smaller windows keep sharp phrasing but may leave audible collisions.

  • θ field
    Slow sinusoids yield gentle drift. Piecewise ramps yield metric modulations. The field can depend on track identity to give each part a distinct life.

  • Microslip scale
    Keep it tiny. It should decorate timing, not reorder events across buckets.

  • Consonance set
    Adjust the lattice for the style. Add 5 over 7 or 7 over 8 for late modern feels, or keep only 1 over 2 and 2 over 3 for a stricter grid.

Complexity notes

  • Event emission is linear in tick count with tiny constant factors.

  • Merge sorts and buckets events within windows. With N total events the dominant cost is roughly O(N log N) due to sorting for export and local bucket orders. The LCM grid reduces cross comparisons significantly.

Extending the system

  • Swap the pitch mapper to tie pitch classes to phase or to intertrack distance.

  • Replace last writer wins with domain aware CRDTs such as max velocity or longest duration keeps.

  • Add weightings in the consonance metric for genre specific grooves.

  • Carry audio features in payloads to steer merge by timbre or density rather than beat alone.

  • Emit MIDI or MusicXML directly from the merged score to drive a DAW or a notation program.

What you get at the end

A single, causally consistent, rhythmically sensible event log that can be rendered as audio or notation, along with a full audit trail that explains which branch produced each event and how conflicts were resolved. The output reads like a notated history of multiple metric futures that briefly existed and then agreed to meet.


THE CODE:

Nonlinear Polyrhythm: A Multiverse Fork and Merge Logic


############################################################

## 0. LEXICON AND INTENT

############################################################

# Goal:

#   Simulate multiple musical universes that fork over time, each running

#   independent polyrhythmic timelines with nonlinear tempo fields, then

#   reconcile them by a merge that respects causality, rhythmic consonance,

#   and information integrity.


# Convention:

#   Time is tracked in both physical ticks and beat space.

#   Each universe carries a causal DAG of events and vector clocks.

#   Merge produces a canonical score tape with embedded lineage.


############################################################

## 1. CORE TYPES

############################################################

TYPE UID           = 128-bit identifier

TYPE UniverseID    = UID

TYPE TrackID       = UID

TYPE EventID       = UID

TYPE PathID        = UID        # lineage of forks

TYPE Rational      = {num: int, den: int}  # reduced positive rational

TYPE VecClock      = map<TrackID, int>     # vector clock

TYPE Phase         = real in [0, 1)        # phase modulo 1

TYPE BeatIndex     = real                   # fractional beats

TYPE Tick          = integer                # discrete scheduler tick

TYPE Timestamp     = real                   # seconds


STRUCT Clock:

    lamport: int

    vector: VecClock

    beat: BeatIndex

    tick: Tick


STRUCT Event:

    id: EventID

    track: TrackID

    world: UniverseID

    path: PathID

    t_physical: Timestamp

    t_beat: BeatIndex

    payload: any                 # note-on, marker, control, meta

    clock: Clock

    ancestry: set<EventID>       # immediate parents in DAG


STRUCT Edge:

    src: EventID

    dst: EventID


STRUCT DAG:

    nodes: map<EventID, Event>

    edges: set<Edge>


STRUCT TrackState:

    id: TrackID

    tempo_ratio: Rational        # beats of this track per base beat

    phase: Phase                 # local phase in [0,1)

    clock: Clock

    queue: priority_queue<Event> # time-ordered by t_beat then lamport

    accumulator: real            # sub-beat integration

    jitter_seed: int


STRUCT NonlinearField:

    # Nonlinear tempo modulation field θ(t, beat, track)

    # theta returns a scalar multiplier applied to tempo_ratio

    fn_theta: function(Timestamp, BeatIndex, TrackID) -> real

    # optional chaotic map for microtiming drift

    fn_microslip: function(real) -> real


STRUCT Universe:

    id: UniverseID

    parent: UniverseID | null

    path: PathID

    tracks: map<TrackID, TrackState>

    dag: DAG

    field: NonlinearField

    policy: MergePolicy

    now: Timestamp

    base_bpm: real               # reference tempo in beats per minute

    tick_hz: real                # scheduler frequency

    halted: bool


STRUCT MergePolicy:

    window_beats: real           # size of rhythmic reconciliation window

    prefer_older_lamport: bool

    tie_breaker: function(Event, Event) -> Event

    crdt: function(Event, Event) -> Event   # associative, commutative, idempotent

    consonance_metric: function(Event, Event) -> real  # lower is better

    lineage_keep: bool           # annotate merged events with full ancestry


############################################################

## 2. UTILITY FUNCTIONS

############################################################

FUNCTION gcd(a: int, b: int) -> int:

    WHILE b != 0:

        (a, b) := (b, a mod b)

    RETURN abs(a)


FUNCTION lcm(a: int, b: int) -> int:

    RETURN abs(a * b) / gcd(a, b)


FUNCTION reduce(r: Rational) -> Rational:

    g := gcd(r.num, r.den)

    RETURN {num: r.num / g, den: r.den / g}


FUNCTION lcm_of_tempi(R: list<Rational>) -> int:

    # LCM of denominators for alignment grid

    d := 1

    FOR r IN R:

        d := lcm(d, r.den)

    RETURN d


FUNCTION advance_clock(c: Clock, tbeats: real) -> Clock:

    c.beat  := c.beat + tbeats

    c.lamport := c.lamport + 1

    RETURN c


FUNCTION next_phase(phase: Phase, incr: real) -> Phase:

    x := phase + incr

    RETURN x - floor(x)


FUNCTION rational_mul(r: Rational, scalar: real) -> real:

    RETURN (r.num / r.den) * scalar


FUNCTION logistic(x: real, r: real) -> real:

    # chaotic microtiming map in (0,1)

    y := r * x * (1 - x)

    RETURN clamp(y, 0.0, 1.0)


############################################################

## 3. FIELD DEFINITIONS

############################################################

FUNCTION default_theta(t: Timestamp, b: BeatIndex, tr: TrackID) -> real:

    # Smooth nonlinear warp composed of a slow sine and a cubic easing

    slow := 1.0 + 0.05 * sin(2 * PI * 0.07 * t + hash(tr) * 0.001)

    curve := 1.0 + 0.03 * ((2 * frac(b * 0.125) - 1)^3)

    RETURN slow * curve


FUNCTION default_microslip(x: real) -> real:

    RETURN (logistic(x, 3.71) - 0.5) * 0.002  # small symmetric slip


############################################################

## 4. INITIALIZATION

############################################################

FUNCTION init_universe(base_bpm: real, tick_hz: real, tempos: map<TrackID, Rational>) -> Universe:

    U := new Universe

    U.id := new_uid()

    U.parent := null

    U.path := new_uid()

    U.base_bpm := base_bpm

    U.tick_hz := tick_hz

    U.now := 0.0

    U.halted := false

    U.field.fn_theta := default_theta

    U.field.fn_microslip := default_microslip

    U.policy := default_merge_policy()

    U.dag := DAG{nodes: {}, edges: {}}

    FOR tr, rat IN tempos:

        T := new TrackState

        T.id := tr

        T.tempo_ratio := reduce(rat)

        T.phase := 0.0

        T.clock := Clock{lamport: 0, vector: {}, beat: 0.0, tick: 0}

        T.queue := empty_priority_queue()

        T.accumulator := 0.0

        T.jitter_seed := hash(tr) mod 65521

        U.tracks[tr] := T

    RETURN U


FUNCTION default_merge_policy() -> MergePolicy:

    M := new MergePolicy

    M.window_beats := 8.0

    M.prefer_older_lamport := true

    M.tie_breaker := function(a, b):

        # favor event with tempo closer to small integer ratio against base

        if consonant_rank(a) < consonant_rank(b): return a else return b

    M.crdt := crdt_last_writer_wins_with_lamport

    M.consonance_metric := interval_tension

    M.lineage_keep := true

    RETURN M


FUNCTION consonant_rank(e: Event) -> int:

    # rank by proximity to ratios 1:1, 2:3, 3:4, 4:5, etc.

    target := [1.0, 2/3, 3/4, 4/5, 5/8, 7/8]

    dmin := +INF

    FOR r IN target:

        dmin := min(dmin, abs(frac(e.t_beat) - r))

    RETURN floor(dmin * 1000)


FUNCTION interval_tension(a: Event, b: Event) -> real:

    RETURN abs(frac(a.t_beat) - frac(b.t_beat))


FUNCTION crdt_last_writer_wins_with_lamport(a: Event, b: Event) -> Event:

    if a.clock.lamport < b.clock.lamport: return b

    if a.clock.lamport > b.clock.lamport: return a

    # tie on lamport, pick lower event id to keep idempotence

    if a.id < b.id: return a else return b


############################################################

## 5. SCHEDULER AND EMISSION

############################################################

FUNCTION tick(U: Universe):

    if U.halted: return

    dt := 1.0 / U.tick_hz

    U.now := U.now + dt

    FOR T IN U.tracks.values():

        base_bps := U.base_bpm / 60.0

        theta := U.field.fn_theta(U.now, T.clock.beat, T.id)

        local_bps := base_bps * rational_mul(T.tempo_ratio, 1.0) * theta

        microslip := U.field.fn_microslip((T.jitter_seed + U.now) mod 1.0)

        advance := local_bps * dt + microslip

        T.accumulator := T.accumulator + advance

        WHILE T.accumulator >= 1.0:

            T.accumulator := T.accumulator - 1.0

            T.phase := next_phase(T.phase, 1.0)

            e := emit_event(U, T)

            push(T.queue, e)


FUNCTION emit_event(U: Universe, T: TrackState) -> Event:

    E := new Event

    E.id := new_uid()

    E.track := T.id

    E.world := U.id

    E.path := U.path

    E.t_physical := U.now

    E.t_beat := T.clock.beat

    E.payload := synth_payload(T, E)

    T.clock := advance_clock(T.clock, 1.0)

    E.clock := copy(T.clock)

    E.ancestry := {}    # filled during merges

    U.dag.nodes[E.id] := E

    RETURN E


FUNCTION synth_payload(T: TrackState, E: Event) -> any:

    # Example: generate note or control with phase coded pitch

    pitch := 48 + floor(12 * frac(E.t_beat * (T.tempo_ratio.num + 1)))

    vel   := 60 + floor(40 * abs(sin(2 * PI * frac(E.t_beat))))

    return {type: "note", pitch: pitch, velocity: vel, dur_beats: 0.5}


############################################################

## 6. FORK LOGIC

############################################################

FUNCTION fork_universe(U: Universe, mutations: function(Universe) -> void) -> Universe:

    V := deep_copy(U)

    V.id := new_uid()

    V.parent := U.id

    V.path := new_uid()

    # mutate tempo fields, policies, or track sets

    mutations(V)

    # advance clocks independently after fork

    FOR T IN V.tracks.values():

        T.clock.vector[T.id] := (T.clock.vector.get(T.id, 0)) + 1

    RETURN V


# Example mutation: change one track to a new ratio and nonlinear map

FUNCTION mutate_to_polymeter(V: Universe, target_track: TrackID, new_ratio: Rational):

    V.tracks[target_track].tempo_ratio := reduce(new_ratio)

    V.field.fn_theta := function(t, b, tr):

        base := default_theta(t, b, tr)

        warp := 1.0 + 0.07 * sin(2 * PI * 0.031 * t + (tr == target_track ? 1.3 : 0.0))

        return base * warp


############################################################

## 7. MERGE PREPARATION

############################################################

FUNCTION compute_alignment_grid(A: Universe, B: Universe) -> real:

    # compute an alignment step in beats using LCM of denominators

    ra := [T.tempo_ratio for T IN A.tracks.values()]

    rb := [T.tempo_ratio for T IN B.tracks.values()]

    d := lcm_of_tempi(ra + rb)

    return 1.0 / d


FUNCTION window_events(U: Universe, center: BeatIndex, span: real) -> list<Event>:

    out := []

    FOR e IN U.dag.nodes.values():

        if abs(e.t_beat - center) <= span / 2:

            out.append(e)

    sort(out by (e.t_beat, e.clock.lamport))

    RETURN out


############################################################

## 8. MERGE ENGINE

############################################################

FUNCTION merge_universes(A: Universe, B: Universe) -> Universe:

    C := init_universe(

            base_bpm = (A.base_bpm + B.base_bpm) / 2,

            tick_hz  = max(A.tick_hz, B.tick_hz),

            tempos   = union_tempos(A.tracks, B.tracks)

         )

    C.parent := null

    C.path := new_uid()

    C.policy := select_policy(A.policy, B.policy)

    step := compute_alignment_grid(A, B)

    # iterate over overlapping beat domain

    beat_min := min(min_beat(A), min_beat(B))

    beat_max := max(max_beat(A), max_beat(B))

    center := beat_min

    WHILE center <= beat_max:

        Ea := window_events(A, center, C.policy.window_beats)

        Eb := window_events(B, center, C.policy.window_beats)

        bucket := cluster_by_quantum(Ea + Eb, step)

        FOR q IN bucket.keys():

            merged := merge_bucket(bucket[q], C.policy)

            FOR e IN merged:

                insert_merged_event(C, e)

        center := center + C.policy.window_beats

    C.halted := true

    RETURN C


FUNCTION union_tempos(TA: map<TrackID, TrackState>, TB: map<TrackID, TrackState>) -> map<TrackID, Rational>:

    out := {}

    FOR t IN TA.keys(): out[t] := TA[t].tempo_ratio

    FOR t IN TB.keys():

        if t not in out: out[t] := TB[t].tempo_ratio

        else:

            # keep the ratio with smaller denominator to favor simpler grid

            ra := out[t]; rb := TB[t].tempo_ratio

            out[t] := (ra.den <= rb.den ? ra : rb)

    RETURN out


FUNCTION select_policy(Pa: MergePolicy, Pb: MergePolicy) -> MergePolicy:

    # conservative choice

    M := Pa

    M.window_beats := min(Pa.window_beats, Pb.window_beats)

    M.prefer_older_lamport := Pa.prefer_older_lamport AND Pb.prefer_older_lamport

    RETURN M


FUNCTION min_beat(U: Universe) -> BeatIndex:

    if U.dag.nodes.is_empty(): return 0.0

    return min([e.t_beat for e IN U.dag.nodes.values()])


FUNCTION max_beat(U: Universe) -> BeatIndex:

    if U.dag.nodes.is_empty(): return 0.0

    return max([e.t_beat for e IN U.dag.nodes.values()])


FUNCTION cluster_by_quantum(E: list<Event>, q: real) -> map<int, list<Event>>:

    buckets := {}

    FOR e IN E:

        k := floor(e.t_beat / q)

        buckets[k] := buckets.get(k, []) + [e]

    RETURN buckets


FUNCTION merge_bucket(L: list<Event>, policy: MergePolicy) -> list<Event>:

    # 1) partition by track

    by_track := group_by(L, key = e.track)

    out := []

    # 2) within each track, fold by CRDT

    FOR tr, group IN by_track:

        folded := fold_crdt(group, policy.crdt)

        out.append(folded)

    # 3) cross-track alignment by consonance

    out := align_cross_track(out, policy)

    RETURN out


FUNCTION fold_crdt(group: list<Event>, crdt_fn) -> Event:

    acc := group[0]

    FOR i FROM 1 TO len(group)-1:

        acc := crdt_fn(acc, group[i])

    RETURN acc


FUNCTION align_cross_track(events: list<Event>, policy: MergePolicy) -> list<Event>:

    # adjust fractional beats to closest consonant lattice if within a small epsilon

    eps := 1e-3

    lattice := [0, 1/8, 1/6, 1/5, 1/4, 1/3, 3/8, 1/2, 5/8, 2/3, 3/4, 4/5, 5/6, 7/8]

    FOR e IN events:

        fracb := frac(e.t_beat)

        closest := argmin(lattice, lambda x: abs(x - fracb))

        if abs(closest - fracb) < eps:

            e.t_beat := floor(e.t_beat) + closest

    RETURN events


FUNCTION insert_merged_event(C: Universe, e_in: Event):

    # clone, annotate lineage, update DAG

    E := deep_copy(e_in)

    if C.policy.lineage_keep:

        E.payload.lineage := {world: e_in.world, path: e_in.path}

        E.ancestry := E.ancestry union parents_of(e_in)

    E.world := C.id

    E.path := C.path

    E.clock := advance_clock(C.tracks[E.track].clock, 0.0)

    C.dag.nodes[E.id] := E

    # add edges from known parents if present

    FOR p IN E.ancestry:

        if p in C.dag.nodes:

            C.dag.edges.add(Edge{src: p, dst: E.id})


FUNCTION parents_of(e: Event) -> set<EventID>:

    return e.ancestry


############################################################

## 9. CONSISTENCY AND VALIDATION

############################################################

FUNCTION validate_dag(U: Universe) -> bool:

    visited := {}

    stack := {}

    FUNCTION dfs(v: EventID) -> bool:

        visited[v] := true

        stack[v] := true

        FOR edge IN U.dag.edges where edge.src == v:

            w := edge.dst

            if not visited.get(w, false):

                if not dfs(w): return false

            elif stack.get(w, false):

                return false   # cycle found

        stack[v] := false

        return true

    FOR v IN U.dag.nodes.keys():

        if not visited.get(v, false):

            if not dfs(v): return false

    return true


FUNCTION verify_monotonic_clocks(U: Universe) -> bool:

    # ensure lamport does not decrease along edges

    FOR e IN U.dag.nodes.values():

        FOR ed IN U.dag.edges where ed.dst == e.id:

            p := U.dag.nodes[ed.src]

            if p.clock.lamport > e.clock.lamport:

                return false

    return true


############################################################

## 10. DRIVER EXAMPLE

############################################################

PROCEDURE main():

    # Base universe with three tracks in a 5:4:7 polyrhythm against base

    tempos := {

        T1: Rational{5,4},

        T2: Rational{4,3},

        T3: Rational{7,6}

    }

    A := init_universe(base_bpm = 96, tick_hz = 480, tempos = tempos)


    # Run base for N ticks

    FOR i IN 1..(96 * 4 * 60):     # four minutes at 96 BPM, oversampled

        tick(A)


    # Fork to B with polymeter mutation on T3

    B := fork_universe(A, function(V):

            mutate_to_polymeter(V, target_track = T3, new_ratio = Rational{11,8})

        )


    # Advance both for additional time under divergent fields

    FOR i IN 1..(96 * 2 * 60):

        tick(A)

        tick(B)


    # Merge into canonical C

    C := merge_universes(A, B)


    # Validate integrity

    if not validate_dag(C): raise "Merge produced a cyclic DAG"

    if not verify_monotonic_clocks(C): raise "Lamport violation in merged graph"


    # Export C as a score tape or event log

    export_score(C, filename = "multiverse_polyrhythm.score")


############################################################

## 11. EXPORT FORMAT (ABRIDGED)

############################################################

FUNCTION export_score(U: Universe, filename: string):

    # Each line: t_beat, track, pitch, velocity, dur_beats, lineage

    file := open(filename, "w")

    E := list(U.dag.nodes.values())

    sort(E by (e.t_beat, e.track, e.clock.lamport))

    FOR e IN E:

        if e.payload.type == "note":

            line := join_csv([

                round(e.t_beat, 6),

                e.track,

                e.payload.pitch,

                e.payload.velocity,

                e.payload.dur_beats,

                encode_lineage(e.payload.lineage)

            ])

            write(file, line)

    close(file)


FUNCTION encode_lineage(L: any) -> string:

    if L == null: return "{}"

    return "{world=" + to_string(L.world) + ";path=" + to_string(L.path) + "}"


############################################################

## 12. NOTES ON PARAMETER CHOICES

############################################################

# window_beats controls how far the merge looks for consonant alignment.

# A larger window smooths across divergent phases but risks smearing accents.

# step from compute_alignment_grid sets a quantization lattice taken from

# the LCM of denominators. This is a musically meaningful grid for polyrhythms.

# fn_theta can be replaced with any smooth field. For sharp metric modulations,

# swap the sine for piecewise linear ramps. Keep microslip small to avoid

# event reordering that breaks vector clock expectations.


END.