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 maintaining compatibility with standard MIDI playback systems.
- 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
Polychron consists of 11 specialized JavaScript modules following a clean minimal code philosophy:
- Orchestrates the entire composition process
- Implements dual-context architecture for primary and poly meters
- Manages phrase-level timing synchronization
- Coordinates all modules to generate complete MIDI compositions
- Handles section/phrase/measure hierarchy with perfect timing alignment
- MeasureComposer: Base class for meter and division generation
- ScaleComposer: Generates notes from specific scales with octave ranges
- RandomScaleComposer: Random scale selection from all available scales
- ChordComposer: Chord progression-based composition with validation
- RandomChordComposer: Generates random chord progressions (2-5 chords)
- ModeComposer: Mode-based composition with root note support
- RandomModeComposer: Random mode selection from all available modes
- Advanced music theory integration with Tonal.js
- Logarithmic ratio validation for smooth meter transitions
- Weighted random selection for all musical parameters
- Optional voice leading integration for smoother compositions
- Drum Mapping: 25+ drum instruments with velocity ranges
- Drummer Function: Advanced drum pattern generation with stutter effects
- Rhythm Patterns: Binary, hex, onsets, random, Euclidean, rotate, morph
- Algorithmic Generation: Weighted selection from rhythm library
- Context-Aware Programming: Different patterns for primary vs poly meters
- Tonal.js Integration: Uses @tonaljs/rhythm-pattern for core algorithms
- Dynamic Adaptation: Rhythm complexity adjusts based on meter and tempo
- Core Innovation: "Meter spoofing" technology for any meter support
- Dual-Context Architecture: Independent timing for primary and poly meters
- Polyrhythm Calculation: Finds optimal measure alignments between meters
- Absolute Timing: Phrase boundaries align perfectly in seconds
- Hierarchical Timing: Section → Phrase → Measure → Beat → Division → Subdivision → Subsubdivision
- MIDI Compatibility: Converts any denominator to nearest power-of-2
- Tempo Synchronization: Adjusts BPM to preserve actual meter durations
- Comprehensive Logging: Timing markers with context awareness
- Binaural Beat Generation: Alpha range (8-12Hz) with pitch bend effects
- Stutter Effects: Three types (fade, pan, FX) with adaptive parameters
- Spatial Audio: Left/right balance variation and channel mapping
- Instrument Management: Program changes, pitch bend, volume control
- MIDI Event Creation: Comprehensive note on/off and control change events
- Channel Tracking: Avoids repetition with last-used channel tracking
- Dynamic FX Processing: Randomized effect parameters with constraints
- Cost Function Optimizer: Weighted penalty system for voice leading rules
- Smooth Motion: Prefers stepwise motion (1-2 semitones) over large leaps
- Voice Range: Enforces soprano/alto/tenor/bass register boundaries
- Leap Recovery: Enforces leap-then-step recovery in opposite direction
- Voice Crossing: Prevents soprano from crossing below alto in multi-voice contexts
- Parallel Motion: Soft constraint avoiding repeated directional motion
- Composer Integration: Optional enablement on any MeasureComposer subclass
- Quality Analysis: Post-hoc validation of note sequences
- Customizable Weights: Tunable preferences for different compositional styles
- Interval Motifs: Ordered
{ note, duration }sequences - Transformations: transpose, invert, augment/diminish, reverse, develop chain
- Application:
applyToNotes()imprints motif offsets onto generated notes (used by stage) - Integration: Section types can seed
activeMotifper section via play.js (code) (doc)
- Mathematical Utilities: 15+ clamping functions (regular, mod, soft, step, log, exp)
- Randomization Systems: Weighted, dual-range, limited-change random functions
- Global State Management: Timing contexts for primary and poly meters
- MIDI Infrastructure: Channel definitions, instrument mappings, constants
- Data Structures: CSV row management, array utilities
- MIDI Helper Functions:
allNotesOff()andmuteAll()for channel cleanup - Performance Optimization: Efficient state tracking and memory management
- CSVBuffer Class: Encapsulates MIDI event arrays with layer metadata (rows, name properties)
- pushMultiple (p): Efficient batch MIDI event insertion with validation
- Timing Markers: Context-aware logUnit() for debugging and analysis
- File Generation: grandFinale() converts CSVBuffer to MIDI .mid files
- Filesystem Operations: Wrapped fs module with error handling and logging
- Integration Utilities: Seamless connection between composition and output
- Performance Optimization: Efficient CSV-to-MIDI conversion via csv_maestro
- Complete MIDI Reference: All 128 program change instruments
- MIDI Control Changes: Full CC mapping with descriptions
- Tonal.js Integration: Music theory databases (scales, chords, modes)
- Enharmonic Normalization: Standardized note naming
- Lookup Functions: MIDI value retrieval by name
- Global Exports: Music theory data exposed for testing
- Validation Systems: Chord and scale validation
- Musical Parameters: BPM, PPQ, tuning frequency (432Hz)
- Weighted Distributions: Numerators, denominators, octaves, voices
- Structural Parameters: Sections, phrases per section, divisions (plus weighted SECTION_TYPES profiles)
- Instrument Settings: Primary, secondary, bass instruments
- Binaural Configuration: Frequency ranges and effects
- Logging Controls: Timing marker granularity
- Composer Configuration: Available composer types and weights
[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 628 tests validate actual function behavior across 12 test files, supporting the project's mission to explore novel algorithmic composition techniques.
- 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
- 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)
- Actual Meter: Any ratio (e.g., 7/9 = 0.777...)
- MIDI Meter: Nearest power-of-2 denominator (e.g., 7/8 = 0.875)
- Sync Factor:
midiMeterRatio / meterRatio(e.g., 0.875/0.777 = 1.126) - Tempo Adjustment:
midiBPM = BPM * syncFactor - Duration Preservation: MIDI plays at adjusted tempo to match actual meter duration
- 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
- 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
- Weighted Selection: Probability distributions for all parameters
- Dual-Range Support: Simultaneous selection from multiple ranges
- Limited Change: Constrained variation for smooth transitions
- Context-Aware: Adapts based on current musical context
- Variation Systems: Random variation with frequency control
- 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 transitions between binaural states
- Instrument Variation: Random program changes for diversity
- 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
- Absolute Precision: Phrase alignment within 0.001 seconds
- Dual-Context Sync: Verified timing synchronization between meters
- Hierarchical Consistency: Perfect nesting of timing hierarchies
- Musical Dimensions: 7 levels of rhythmic hierarchy
- Parameter Space: 100+ configurable parameters
- Compositional Depth: Unlimited polyrhythmic complexity
- Data Density: Supports extreme note granularity
- Real-Time Suitable: O(n) cost calculation per note selection
- Memory Efficient: ~1KB per scorer instance
- Scalable: Handles complex multi-voice textures
- Memory Efficient: Clean minimal code philosophy
- CPU Optimization: Efficient algorithms and caching
- Scalability: Handles complex compositions without performance degradation
- Machine Learning: Adaptive composition based on musical analysis
- Real-time Processing: Live performance capabilities
- Visualization: Graphical representation of complex rhythms
- 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
- Tonal.js: Music theory library
- CSV Maestro: Custom MIDI CSV converter
- Soundfont MIDI Player: Recommended player
- Virtual MIDI Synth: Audio rendering
- LibreOffice: CSV file editing
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.
Install dependencies (requires Node.js):
npm installPolychron provides convenient npm scripts for development and composition:
Runs ESLint to check code quality and enforce style standards across all source files.
npm run lintRuns the full test suite with Vitest (620 tests across 10 test files). Automatically runs npm run lint first as a pretest.
npm run testGenerates a complete MIDI composition and converts it to playable format.
This is the primary workflow command that:
- Runs
node src/play- Executes the composition engine, generates MIDI events as CSV - Runs
py c2m.py- Converts the CSV output to standard MIDI .mid files
npm run playThis creates output files in the output/ directory:
output1.csv/output1.mid- Primary meter layeroutput2.csv/output2.mid- Polyrhythmic layer
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.pypolychron/
├── 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
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:
- Soundfont MIDI Player ⭐ Lightweight, reliable
- MIDI Editor - Full-featured editor
Audio Rendering (for MP3/WAV/FLAC conversion):
- Virtual MIDI Synth - Professional rendering
Utilities:
- LibreOffice - CSV file viewing and editing
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.
Inspiration and related projects:
- Tonal.js - Music theory library (used in Polychron)
- CSV Maestro - MIDI CSV converter
- GenJam by Al Biles - Genetic algorithm music generation
- Music Repos Collection - Curated music projects