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%)
- Docs index auto-generated:
docs/README.mdnow includes an AUTO-GENERATED header and can be regenerated withnode scripts/docs.js indexornpm run docs:fix. - Testing & onboarding: Added
docs/test.md(Testing Guide),scripts/onboard.js(onboarding helper), and theam-i-doneTODO validator (scripts/am-i-done.js). - CI & coverage helpers: Added
scripts/annotate-failure.js,scripts/check-coverage-threshold.js, and.coverage-baseline.jsonto support CI checks and clearer failure reporting. - Global test helpers: Global test helpers were added for
writer,time, andvenueto 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.
- 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
All Polychron source files are comprehensively documented in the /docs directory. Here's an organized guide to navigate the documentation:
- All Docs Index - Full documentation directory
- Testing Guide - Comprehensive test documentation
- Run Validation - Execution pipeline documentation
- play.ts - Main composition engine orchestrating the entire generation pipeline
- playNotes.ts - Note rendering and transformation for output
- stage.ts - Audio processing (binaural beats, stutter effects, MIDI events)
- writer.ts - MIDI output and CSVBuffer management
- time.ts - Timing engine wrapper with meter spoofing technology
- TimingTree.ts - Hierarchical timing state management
- time/LayerManager.ts - Multi-layer coordination
- time/TimingCalculator.ts - Meter conversion and MIDI timing math
- time/TimingContext.ts - Per-layer timing state container
- rhythm.ts - Rhythmic pattern generation and drum mapping
- composers.ts - Composer registry and base classes
- GenericComposer.ts - Foundation for custom composers
- MeasureComposer.ts - Meter and division generation
- ScaleComposer.ts - Scale-based note generation
- ModeComposer.ts - Mode-based composition with roots
- ChordComposer.ts - Chord progression composition
- PentatonicComposer.ts - Pentatonic scale composer
- ProgressionGenerator.ts - Advanced progression generation
- venue.ts - MIDI data, music theory data, and validation
- voiceLeading.ts - Voice leading wrapper and optimization
- voiceLeading/VoiceLeadingScore.ts - Cost function optimization
- motifs.ts - Motif transformation and application
- sheet.ts - Configuration system and musical parameters
- structure.ts - Section profiles and hierarchy
- backstage.ts - Global utilities and state management
- PolychronError.ts - Error handling and reporting
- DIContainer.ts - Dependency injection container
- fxManager.ts - Effect management system
- CompositionContext.ts - Composition state container
- CompositionState.ts - Musical state tracking
- CompositionProgress.ts - Progress tracking
- ComposerRegistry.ts - Composer type registration
- PolychronInit.ts - Initialization pipeline
- ModuleInitializer.ts - Module setup and configuration
- PolychronConfig.ts - Configuration interface
- PolychronContext.ts - Context configuration
- CancellationToken.ts - Cancellation support
- EventBus.ts - Event publishing and subscription
- utils.ts - General utility functions
- time/index.md - Timing subsystem overview
- voiceLeading/index.md - Voice leading subsystem overview
- validators.md - Validation utilities and schemas
[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.
- 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 changes
- 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 changes 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