1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
|
# morphology-img
Convert morphology data structures to SVG visualizations using LilyPond.
## Prerequisites
This library requires LilyPond to be installed and available in your system PATH.
## Overview
The `morphology-img` crate transforms meta-affine sequences from the `morphology` crate into musical notation rendered as SVG images. It uses LilyPond's typesetting engine to generate high-quality visualizations.
The crate provides two levels of API:
1. **Markup conversion**: Convert sequences to LilyPond markup strings
2. **Complete rendering**: Generate SVG files from sequences
## API
### Rendering Sequences to SVG Files
The primary API renders sequences directly to SVG files:
```rust
use morphology::{Sequence, Value};
use morphology_img::{render_sequences, RenderConfig};
// Create sequences
let sequences = vec![
Sequence::new(vec![
Value::new(1, 0),
Value::new(-1, 1),
Value::new(-1, 0),
Value::new(0, 0),
]),
Sequence::new(vec![
Value::origin(),
Value::new(1, 0),
]),
];
// Configure rendering
let config = RenderConfig::new("output");
// Render to SVGs
let svg_paths = render_sequences(&sequences, &config)?;
// SVG files are created at output/sequence-0.svg, output/sequence-1.svg, etc.
for path in svg_paths {
println!("Created: {}", path.display());
}
```
### RenderConfig
Configure rendering behavior using the builder pattern:
```rust
use morphology_img::RenderConfig;
let config = RenderConfig::new("output")
.keep_temp_files(true) // Keep .ly files for debugging
.lilypond_binary("/usr/local/bin/lilypond") // Custom LilyPond path
.max_batch_size(50); // Process sequences in chunks
```
**Methods:**
- `new(output_dir)` - Create config with output directory
- `keep_temp_files(bool)` - Preserve temporary .ly files (default: false)
- `lilypond_binary(path)` - Set path to LilyPond binary (default: "lilypond")
- `max_batch_size(usize)` - Set maximum sequences per batch (default: unlimited)
### Converting Sequences to Markup
For lower-level control, convert sequences to LilyPond markup strings:
```rust
use morphology::{Sequence, Value};
use morphology_img::sequence_to_markup;
let seq = Sequence::new(vec![
Value::new(1, 0),
Value::new(-1, 1),
Value::new(-1, 0),
Value::new(0, 0),
]);
let markup = sequence_to_markup(&seq);
assert_eq!(markup, "f'4 f4 e4 b4");
```
### Error Handling
The `RenderError` enum captures all rendering failures:
```rust
use morphology_img::{render_sequences, RenderConfig, RenderError};
match render_sequences(&sequences, &config) {
Ok(paths) => println!("Rendered {} SVGs", paths.len()),
Err(RenderError::LilyPondNotFound(msg)) => {
eprintln!("LilyPond not installed: {}", msg);
}
Err(RenderError::LilyPondExecution(msg)) => {
eprintln!("LilyPond failed: {}", msg);
}
Err(e) => eprintln!("Error: {}", e),
}
```
**Error variants:**
- `LilyPondNotFound` - LilyPond binary not found in PATH
- `LilyPondExecution` - LilyPond failed during rendering
- `Template` - Template processing error
- `FileIO` - File system operation failed
- `InvalidSequence` - Invalid sequence data
## Batch Processing
For large datasets, use batch processing to avoid overwhelming the filesystem:
```rust
use morphology_img::RenderConfig;
// Process 1000 sequences in chunks of 50
let config = RenderConfig::new("output")
.max_batch_size(50);
let svg_paths = render_sequences(&sequences, &config)?;
```
Batch processing creates separate temporary directories for each chunk and invokes LilyPond once per batch for optimal performance.
## Testing
Run unit tests:
```bash
cargo test -p morphology-img
```
Run integration tests (requires LilyPond):
```bash
cargo test -p morphology-img -- --ignored
```
Run all tests:
```bash
cargo test -p morphology-img -- --include-ignored
```
## Useful Commands
Build the crate:
```bash
cargo build -p morphology-img
```
Generate documentation:
```bash
cargo doc -p morphology-img --open
```
Check for errors:
```bash
cargo check -p morphology-img
```
## Architecture
The crate follows a clean separation of concerns:
- **Public API**: Only exports `render_sequences`, `sequence_to_markup`, `RenderConfig`, and `RenderError`
- **Hidden implementation**: All LilyPond-specific types (pitches, notes, durations) are internal
- **Input types**: Only accepts types from the `morphology` crate (`Sequence`, `Value`)
- **Output types**: Returns standard library types (`String`, `PathBuf`, `Result`)
### Module Structure
```
morphology-img/src/
├── lib.rs // Public API, re-exports
├── error.rs // Error types using thiserror
├── note.rs // Integer → LilyPond pitch conversion
├── template.rs // Template handling & substitution
├── file_gen.rs // .ly file generation & temp dirs
└── render.rs // LilyPond CLI invocation
```
### Transformation Pipeline
1. **Sequence → Notes**: Convert `(outer, inner)` pairs to LilyPond pitch names
2. **Notes → Markup**: Serialize notes to space-separated string
3. **Markup → .ly File**: Substitute markup into template
4. **.ly File → SVG**: Invoke LilyPond to render SVG
5. **Cleanup**: Remove temporary files (unless configured to keep)
## Troubleshooting
### "LilyPond not found"
Ensure LilyPond is installed and in your PATH:
```bash
lilypond --version
```
If installed but not found, specify the full path:
```rust
let config = RenderConfig::new("output")
.lilypond_binary("/usr/local/bin/lilypond");
```
### "LilyPond execution failed"
Debug by keeping temporary files:
```rust
let config = RenderConfig::new("output")
.keep_temp_files(true);
```
Then inspect the generated .ly files and run LilyPond manually:
```bash
lilypond --svg path/to/sequence-0.ly
```
### Permission errors
Ensure the output directory is writable:
```bash
mkdir -p output
chmod 755 output
```
### Large batch processing
For very large batches, enable chunking:
```rust
let config = RenderConfig::new("output")
.max_batch_size(100); // Process 100 sequences at a time
```
|