Skip to content

Polychron MIDI patch enables inclusivity of diverse and marginalized time signatures. Take back time from the establishment chronophobes. Other dynamics enhancements include: unrestricted polyphony, ultra-fine note granularity, custom note scaling and randomization, (and more!), all while maintaining accurate adherence to an absolute time grid.

Notifications You must be signed in to change notification settings

PolychronMidi/Polychron

Repository files navigation

Polychron

1/22 23:41:06 - Latest Status

  • Tests 1343/1343 - 100%
  • Lint 0 errors / 0 warnings
  • Type-check 0 errors / 0 warnings
  • Coverage 76.5% (Statements: 76% Lines: 76.5% Branches: 58.2% Functions: 74.5%)

Recent additions ✅

  • Docs index auto-generated: docs/README.md now includes an AUTO-GENERATED header and can be regenerated with node scripts/docs.js index or npm run docs:fix.
  • Testing & onboarding: Added docs/test.md (Testing Guide), scripts/onboard.js (onboarding helper), and the am-i-done TODO validator (scripts/am-i-done.js).
  • CI & coverage helpers: Added scripts/annotate-failure.js, scripts/check-coverage-threshold.js, and .coverage-baseline.json to support CI checks and clearer failure reporting.
  • Global test helpers: Global test helpers were added for writer, time, and venue to support test setups.

Polychron is an advanced MIDI composition system that breaks free from traditional MIDI limitations, particularly in the realm of time signatures (meters). The core innovation lies in its ability to work with any musical meter through a process called "meter spoofing" while supporting standard MIDI playback systems.

Key Features

  • Unrestricted Meter Support: Any musical meter (time signature) including complex and non-standard ratios
  • Polyrhythm Capability: Simultaneous dual-meter composition with perfect timing alignment
  • Multi-Layer Architecture: CSVBuffer and LayerManager enable transparent context switching between layers
  • Absolute Timing Accuracy: Dual-context architecture ensures phrase boundaries align perfectly in absolute time
  • Advanced Music Theory: Integration with Tonal.js for scales, chords, modes, and music theory operations
  • Binaural Beat Effects: Alpha range (8-12Hz) binaural beats with headphone spatialization
  • Extreme Granularity: Support for subdivisions beyond traditional 128th notes
  • Dynamic Composition: Weighted random selection, algorithmic rhythm generation, and adaptive musical intelligence
  • Voice Leading & Counterpoint: Cost function optimization for smooth melodic motion and voice management

Complete Module Documentation

All Polychron source files are comprehensively documented in the /docs directory. Here's an organized guide to navigate the documentation:

📚 Quick Navigation

Core Orchestration & Rendering

  1. play.ts - Main composition engine orchestrating the entire generation pipeline
  2. playNotes.ts - Note rendering and transformation for output
  3. stage.ts - Audio processing (binaural beats, stutter effects, MIDI events)
  4. writer.ts - MIDI output and CSVBuffer management

Timing & Rhythm System

  1. time.ts - Timing engine wrapper with meter spoofing technology
  2. TimingTree.ts - Hierarchical timing state management
  3. time/LayerManager.ts - Multi-layer coordination
  4. time/TimingCalculator.ts - Meter conversion and MIDI timing math
  5. time/TimingContext.ts - Per-layer timing state container
  6. rhythm.ts - Rhythmic pattern generation and drum mapping

Musical Intelligence & Composition

  1. composers.ts - Composer registry and base classes
  2. GenericComposer.ts - Foundation for custom composers
  3. MeasureComposer.ts - Meter and division generation
  4. ScaleComposer.ts - Scale-based note generation
  5. ModeComposer.ts - Mode-based composition with roots
  6. ChordComposer.ts - Chord progression composition
  7. PentatonicComposer.ts - Pentatonic scale composer
  8. ProgressionGenerator.ts - Advanced progression generation

Music Theory & Voice Leading

  1. venue.ts - MIDI data, music theory data, and validation
  2. voiceLeading.ts - Voice leading wrapper and optimization
  3. voiceLeading/VoiceLeadingScore.ts - Cost function optimization
  4. motifs.ts - Motif transformation and application

Configuration & Infrastructure

  1. sheet.ts - Configuration system and musical parameters
  2. structure.ts - Section profiles and hierarchy
  3. backstage.ts - Global utilities and state management
  4. PolychronError.ts - Error handling and reporting

Dependency Injection & Effects

  1. DIContainer.ts - Dependency injection container
  2. fxManager.ts - Effect management system

Context & State Management

  1. CompositionContext.ts - Composition state container
  2. CompositionState.ts - Musical state tracking
  3. CompositionProgress.ts - Progress tracking
  4. ComposerRegistry.ts - Composer type registration

Initialization & Lifecycle

  1. PolychronInit.ts - Initialization pipeline
  2. ModuleInitializer.ts - Module setup and configuration
  3. PolychronConfig.ts - Configuration interface
  4. PolychronContext.ts - Context configuration
  5. CancellationToken.ts - Cancellation support

Event System

  1. EventBus.ts - Event publishing and subscription

Utilities

  1. utils.ts - General utility functions

Module Index


Testing Philosophy

[See docs/test.md for comprehensive testing documentation. Polychron uses real implementations throughout its test suite—no mocks duplicating logic. This approach creates a safe sandbox for experimental music composition, enabling rapid iteration with confidence. All 1200+ tests validate actual function behavior across 50+ test files, supporting the project's mission to explore novel algorithmic composition techniques.

Technical Innovations

Multi-Layer Architecture

  • CSVBuffer Class (writer.js (code) (doc)): Each layer (primary, poly) has its own CSVBuffer instance encapsulating MIDI event array
  • LayerManager (LM) (time.js (code) (doc)): Context switching object managing per-layer timing state
  • Global State Pattern: Shared variables (phraseStart, tpMeasure, etc.) switched between layer contexts
  • Transparent Integration: p(c) syntax allows code to work with active layer's buffer automatically
  • Independent Timing: Each layer maintains separate timing state via LM.layers[name].state
  • Automatic Restoration: LM.activate() switches global variables to target layer's preserved values

Dual-Context Timing Architecture

  • Primary Context: Main meter with full timing calculation
  • Poly Context: Independent timing recalculation for polyrhythm
  • Shared Timestamps: Both contexts use accumulated phraseStartTime (absolute seconds)
  • Independent Tick Rates: Each meter has its own tpSec (ticks/second)
  • Perfect Alignment: Phrase boundaries match in absolute time despite different tick counts
  • Cascading Calculations: Formula pattern: currentStart = parentStart + currentIndex × currentDuration
  • Timing Hierarchy: Section → Phrase → Measure → Beat → Division → Subdivision → Subsubdivision (7 levels)

Meter Spoofing Technology

  1. Actual Meter: Any ratio (e.g., 7/9 = 0.777...)
  2. MIDI Meter: Nearest power-of-2 denominator (e.g., 7/8 = 0.875)
  3. Sync Factor: midiMeterRatio / meterRatio (e.g., 0.875/0.777 = 1.126)
  4. Tempo Adjustment: midiBPM = BPM * syncFactor
  5. Duration Preservation: MIDI plays at adjusted tempo to match actual meter duration

Polyrhythm Calculation

  • Mathematical Alignment: Finds where measure boundaries align between meters
  • Optimal Solutions: Tests combinations to find tightest polyrhythms
  • Tolerance Validation: Ensures alignment within 0.00000001 precision
  • Complexity Management: Limits to reasonable measure counts (1-5)
  • Musical Context: Preserves musical relationships between meters

Voice Leading Optimization

  • Cost Function Approach: Weighted penalties for voice leading violations
  • Smooth Voice Motion: Stepwise motion preferred over large leaps
  • Register Management: Soprano/alto/tenor/bass boundaries enforced
  • Leap Recovery Rule: Enforces classical counterpoint leap-then-step recovery
  • Voice Crossing Prevention: Prevents melodic line collision in multi-voice texture
  • Optional Integration: Composers can enable voice leading when needed
  • Customizable Preferences: Adjust weights for different compositional styles

Advanced Randomization

  • Weighted Selection: Probability distributions for all parameters
  • Dual-Range Support: Simultaneous selection from multiple ranges
  • Limited Change: Constrained variation for smooth changes
  • Context-Aware: Adapts based on current musical context
  • Variation Systems: Random variation with frequency control

Binaural Beat System

  • Alpha Range: 8-12Hz frequency offsets
  • Pitch Bend Calculation: Converts frequency to MIDI pitch bend values
  • Channel Mapping: Left/right channel assignments for spatial effects
  • Volume Crossfades: Smooth changes between binaural states
  • Instrument Variation: Random program changes for diversity

Stutter Effects Engine

  • Three Effect Types: Fade (volume), Pan (stereo), FX (parameter)
  • Adaptive Parameters: Number of stutters, duration, decay factors
  • Channel Tracking: Avoids repetition with usage tracking
  • Dynamic Application: Randomized application with probability control
  • Musical Integration: Synchronized with rhythmic structure

Performance Characteristics

Timing Accuracy

  • Absolute Precision: Phrase alignment within 0.001 seconds
  • Dual-Context Sync: Verified timing synchronization between meters
  • Hierarchical Consistency: Perfect nesting of timing hierarchies

System Complexity

  • Musical Dimensions: 7 levels of rhythmic hierarchy
  • Parameter Space: 100+ configurable parameters
  • Compositional Depth: Unlimited polyrhythmic complexity
  • Data Density: Supports extreme note granularity

Voice Leading Performance

  • Real-Time Suitable: O(n) cost calculation per note selection
  • Memory Efficient: ~1KB per scorer instance
  • Scalable: Handles complex multi-voice textures

Resource Utilization

  • Memory Efficient: Clean minimal code philosophy
  • CPU Optimization: Efficient algorithms and caching
  • Scalability: Handles complex compositions without performance degradation

Future Development

Planned Enhancements

  • Machine Learning: Adaptive composition based on musical analysis
  • Real-time Processing: Live performance capabilities
  • Visualization: Graphical representation of complex rhythms

Research Directions

  • Microtonal Support: Beyond 12-tone equal temperament
  • Temporal Modulation: Dynamic tempo changes within phrases
  • Spatial Audio: 3D positioning and ambisonics
  • Cross-Modal Integration: Audio-visual synchronization
  • Cognitive Studies: Perception of complex polyrhythms
  • Algorithmic Composition: Advanced generative algorithms

Community & Resources

License

Polychron is open source software designed for musical innovation and research. The system represents a significant advancement in algorithmic composition, particularly in the domain of complex rhythmic structures, polyrhythmic composition, and voice leading.


Note: This comprehensive review covers all JavaScript files in the Polychron system, highlighting the sophisticated architecture, innovative technologies, and advanced musical capabilities. The system demonstrates exceptional technical depth while maintaining clean, minimal code organization.

Installation & Usage

Quick Start

Install dependencies (requires Node.js):

npm install

NPM Scripts

Polychron provides convenient npm scripts for development and composition:

npm run lint

Runs ESLint to check code quality and enforce style standards across all source files.

npm run lint

npm run test

Runs the full test suite with Vitest (620 tests across 10 test files). Automatically runs npm run lint first as a pretest.

npm run test

npm run playMain Command

Generates a complete MIDI composition and converts it to playable format.

This is the primary workflow command that:

  1. Runs node src/play - Executes the composition engine, generates MIDI events as CSV
  2. Runs py c2m.py - Converts the CSV output to standard MIDI .mid files
npm run play

This creates output files in the output/ directory:

  • output1.csv / output1.mid - Primary meter layer
  • output2.csv / output2.mid - Polyrhythmic layer

Python Conversion

The c2m.py script requires Python and the csv_maestro library. If running components separately:

# Generate composition as CSV
node src/play

# Convert CSV to MIDI (requires Python)
py c2m.py

Project Structure

polychron/
├── src/                    # Source code (10 JavaScript modules)
├── docs/                   # Detailed module documentation
├── test/                   # Test suite (620 tests, 10 test files)
├── csv_maestro/            # Python MIDI CSV converter
├── output/                 # Generated compositions
└── package.json            # Project configuration & scripts

Playing Generated MIDI Files

You'll need a MIDI player with a soundfont installed to play generated MIDI files. Standard MIDI players may experience playback issues due to extreme data density. The following players have been tested and work well:

Recommended MIDI Players:

Audio Rendering (for MP3/WAV/FLAC conversion):

Utilities:

Note: Accurate MIDI playback may not be possible on some devices due to extreme data density. In this case, render the MIDI files as audio using Virtual MIDI Synth.

Music Resources

Inspiration and related projects:

About

Polychron MIDI patch enables inclusivity of diverse and marginalized time signatures. Take back time from the establishment chronophobes. Other dynamics enhancements include: unrestricted polyphony, ultra-fine note granularity, custom note scaling and randomization, (and more!), all while maintaining accurate adherence to an absolute time grid.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published