File: musicexp.py

package info (click to toggle)
lilypond 2.8.7-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 13,932 kB
  • ctags: 9,802
  • sloc: cpp: 57,785; lisp: 18,180; python: 11,665; sh: 3,195; yacc: 2,392; lex: 982; perl: 373; ansic: 316; makefile: 131
file content (688 lines) | stat: -rw-r--r-- 14,998 bytes parent folder | download
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
import inspect
import sys
import string
import re

from rational import Rational

class Output_stack_element:
	def __init__ (self):
		self.factor = Rational (1)
	def copy (self):
		o = Output_stack_element()
		o.factor = self.factor
		return o

class Output_printer:

	"""A class that takes care of formatting (eg.: indenting) a
	Music expression as a .ly file.
	
	"""
	## TODO: support for \relative.
	
	def __init__ (self):
		self._line = ''
		self._indent = 4
		self._nesting = 0
		self._file = sys.stdout
		self._line_len = 72
		self._output_state_stack = [Output_stack_element()]
		self._skipspace = False
		self._last_duration = None

	def set_file (self, file):
		self._file = file
		
	def dump_version (self):
		self.newline ()
		self.print_verbatim ('\\version "@TOPLEVEL_VERSION@"')
		self.newline ()
		
	def get_indent (self):
		return self._nesting * self._indent
	
	def override (self):
		last = self._output_state_stack[-1]
		self._output_state_stack.append (last.copy())
		
	def add_factor (self, factor):
		self.override()
		self._output_state_stack[-1].factor *=  factor

	def revert (self):
		del self._output_state_stack[-1]
		if not self._output_state_stack:
			raise 'empty'

	def duration_factor (self):
		return self._output_state_stack[-1].factor

	def print_verbatim (self, str):
		self._line += str

	def unformatted_output (self, str):
		self._nesting += str.count ('<') + str.count ('{')
		self._nesting -= str.count ('>') + str.count ('}')
		self.print_verbatim (str)
		
	def print_duration_string (self, str):
		if self._last_duration == str:
			return
		
		self.unformatted_output (str)
				     
	def add_word (self, str):
		if (len (str) + 1 + len (self._line) > self._line_len):
			self.newline()
			self._skipspace = True

		if not self._skipspace:
			self._line += ' '
		self.unformatted_output (str)
		self._skipspace = False
		
	def newline (self):
		self._file.write (self._line + '\n')
		self._line = ' ' * self._indent * self._nesting
		self._skipspace = True

	def skipspace (self):
		self._skipspace = True
		
	def __call__(self, arg):
		self.dump (arg)
	
	def dump (self, str):
		
		if self._skipspace:
			self._skipspace = False
			self.unformatted_output (str)
		else:
			words = string.split (str)
			for w in words:
				self.add_word (w)

class Duration:
	def __init__ (self):
		self.duration_log = 0
		self.dots = 0
		self.factor = Rational (1)
		
	def lisp_expression (self):
		return '(ly:make-duration %d %d %d %d)' % (self.duration_log,
							   self.dots,
							   self.factor.numerator (),
							   self.factor.denominator ())


	def ly_expression (self, factor = None):
		if not factor:
			factor = self.factor
			
		str = '%d%s' % (1 << self.duration_log, '.'*self.dots)

		if factor <> Rational (1,1):
			str += '*%d/%d' % (factor.numerator (), factor.denominator ())

		return str
	
	def print_ly (self, outputter):
		str = self.ly_expression (self.factor / outputter.duration_factor ())
		outputter.print_duration_string (str)
		
	def __repr__(self):
		return self.ly_expression()
		
	def copy (self):
		d = Duration ()
		d.dots = self.dots
		d.duration_log = self.duration_log
		d.factor = self.factor
		return d

	def get_length (self):
		dot_fact = Rational( (1 << (1 + self.dots))-1,
				     1 << self.dots)

		log = abs (self.duration_log)
		dur = 1 << log
		if self.duration_log < 0:
			base = Rational (dur)
		else:
			base = Rational (1, dur)

		return base * dot_fact * self.factor

	
class Pitch:
	def __init__ (self):
		self.alteration = 0
		self.step = 0
		self.octave = 0
		
	def __repr__(self):
		return self.ly_expression()

	def transposed (self, interval):
		c = self.copy ()
		c.alteration  += interval.alteration
		c.step += interval.step
		c.octave += interval.octave
		c.normalize ()
		
		target_st = self.semitones()  + interval.semitones()
		c.alteration += target_st - c.semitones()
		return c

	def normalize (c):
		while c.step < 0:
			c.step += 7
			c.octave -= 1
		c.octave += c.step / 7
		c.step = c.step  % 7

	
	def lisp_expression (self):
		return '(ly:make-pitch %d %d %d)' % (self.octave,
						     self.step,
						     self.alteration)

	def copy (self):
		p = Pitch ()
		p.alteration = self.alteration
		p.step = self.step
		p.octave = self.octave 
		return p

	def steps (self):
		return self.step + self.octave *7

	def semitones (self):
		return self.octave * 12 + [0,2,4,5,7,9,11][self.step] + self.alteration
	
	def ly_step_expression (self): 
		str = 'cdefgab'[self.step]
		if self.alteration > 0:
			str += 'is'* (self.alteration)
		elif self.alteration < 0:
			str += 'es'* (-self.alteration)

		return str.replace ('aes', 'as').replace ('ees', 'es')
	
	def ly_expression (self):
		str = self.ly_step_expression ()
		if self.octave >= 0:
			str += "'" * (self.octave + 1) 
		elif self.octave < -1:
			str += "," * (-self.octave - 1) 
			
		return str
	def print_ly (self, outputter):
		outputter (self.ly_expression())
	
class Music:
	def __init__ (self):
		self.parent = None
		self.start = Rational (0)
		self.comment = ''
		self.identifier = None
		
	def get_length(self):
		return Rational (0)
	
	def get_properties (self):
		return ''
	
	def has_children (self):
		return False
	
	def get_index (self):
		if self.parent:
			return self.parent.elements.index (self)
		else:
			return None
	def name (self):
		return self.__class__.__name__
	
	def lisp_expression (self):
		name = self.name()

		props = self.get_properties ()
#		props += 'start %f ' % self.start
		
		return "(make-music '%s %s)" % (name,  props)

	def set_start (self, start):
		self.start = start

	def find_first (self, predicate):
		if predicate (self):
			return self
		return None

	def print_comment (self, printer, text = None):
		if not text:
			text = self.comment

		if not text:
			return

			
		if text == '\n':
			printer.newline ()
			return
		lines = string.split (text, '\n')
		for l in lines:
			if l:
				printer.dump ('% ' + l)
			printer.newline ()
			

	def print_with_identifier (self, printer):
		if self.identifier: 
			printer ("\\%s" % self.identifier)
		else:
			self.print_ly (printer)

	def print_ly (self, printer):
		printer (self.ly_expression ())

class MusicWrapper (Music):
	def __init__ (self):
		Music.__init__(self)
		self.element = None
	def print_ly (self, func):
		self.element.print_ly (func)

class TimeScaledMusic (MusicWrapper):
	def print_ly (self, func):
		func ('\\times %d/%d ' %
		      (self.numerator, self.denominator))
		func.add_factor (Rational (self.numerator, self.denominator))
		MusicWrapper.print_ly (self, func)
		func.revert ()

class NestedMusic(Music):
	def __init__ (self):
		Music.__init__ (self)
		self.elements = []

	def append (self, what):
		if what:
			self.elements.append (what)
			
	def has_children (self):
		return self.elements

	def insert_around (self, succ, elt, dir):
		assert elt.parent == None
		assert succ == None or succ in self.elements

		
		idx = 0
		if succ:
			idx = self.elements.index (succ)
			if dir > 0:
				idx += 1
		else:
			if dir < 0:
				idx = 0
			elif dir > 0:
				idx = len (self.elements)

		self.elements.insert (idx, elt)
		elt.parent = self
		
	def get_properties (self):
		return ("'elements (list %s)"
			% string.join (map (lambda x: x.lisp_expression(),
					    self.elements)))

	def get_subset_properties (self, predicate):
		return ("'elements (list %s)"
			% string.join (map (lambda x: x.lisp_expression(),
					    filter ( predicate,  self.elements))))
	def get_neighbor (self, music, dir):
		assert music.parent == self
		idx = self.elements.index (music)
		idx += dir
		idx = min (idx, len (self.elements) -1)
		idx = max (idx, 0)

		return self.elements[idx]

	def delete_element (self, element):
		assert element in self.elements
		
		self.elements.remove (element)
		element.parent = None
		
	def set_start (self, start):
		self.start = start
		for e in self.elements:
			e.set_start (start)

	def find_first (self, predicate):
		r = Music.find_first (self, predicate)
		if r:
			return r
		
		for e in self.elements:
			r = e.find_first (predicate)
			if r:
				return r
		return None
		
class SequentialMusic (NestedMusic):
	def print_ly (self, printer):
		printer ('{')
		if self.comment:
			self.print_comment (printer)

		printer.newline()
		for e in self.elements:
			e.print_ly (printer)

		printer ('}')
		printer.newline()
			
	def lisp_sub_expression (self, pred):
		name = self.name()


		props = self.get_subset_properties (pred)
		
		return "(make-music '%s %s)" % (name,  props)
	
	def set_start (self, start):
		for e in self.elements:
			e.set_start (start)
			start += e.get_length()
			
class EventChord(NestedMusic):
	def get_length (self):
		l = Rational (0)
		for e in self.elements:
			l = max(l, e.get_length())
		return l
	
	def print_ly (self, printer):
		note_events = [e for e in self.elements if
			       isinstance (e, NoteEvent)]

		rest_events = [e for e in self.elements if
			       isinstance (e, RhythmicEvent)
			       and not isinstance (e, NoteEvent)]
		
		other_events = [e for e in self.elements if
				not isinstance (e, RhythmicEvent)]

		if rest_events:
			rest_events[0].print_ly (printer)
		elif len (note_events) == 1:
			note_events[0].print_ly (printer)
		elif note_events:
			pitches = [x.pitch.ly_expression () for x in note_events]
			printer ('<%s>' % string.join (pitches))
			note_events[0].duration.print_ly (printer)
		else:
			pass
		
		#	print  'huh', rest_events, note_events, other_events
 		for e in other_events:
			e.print_ly (printer)

		self.print_comment (printer)
			
class Event(Music):
	pass

class SpanEvent (Event):
	def __init__(self):
		Event.__init__ (self)
		self.span_direction = 0
	def get_properties(self):
		return "'span-direction  %d" % self.span_direction
	
class SlurEvent (SpanEvent):
	def ly_expression (self):
		return {-1: '(',
			0:'',
			1:')'}[self.span_direction]

class BeamEvent (SpanEvent):
	def ly_expression (self):
		return {-1: '[',
			0:'',
			1:']'}[self.span_direction]

class ArpeggioEvent(Event):
	def ly_expression (self):
		return ('\\arpeggio')


class TieEvent(Event):
	def ly_expression (self):
		return '~'

	
class RhythmicEvent(Event):
	def __init__ (self):
		Event.__init__ (self)
		self.duration = Duration()
		
	def get_length (self):
		return self.duration.get_length()
		
	def get_properties (self):
		return ("'duration %s"
			% self.duration.lisp_expression ())
	
class RestEvent (RhythmicEvent):
	def ly_expression (self):
		return 'r%s' % self.duration.ly_expression ()
	
	def print_ly (self, printer):
		printer('r')
		self.duration.print_ly (printer)

class SkipEvent (RhythmicEvent):
	def ly_expression (self):
		return 's%s' % self.duration.ly_expression () 

class NoteEvent(RhythmicEvent):
	def  __init__ (self):
		RhythmicEvent.__init__ (self)
		self.pitch = Pitch()
		self.cautionary = False
		self.forced_accidental = False
		
	def get_properties (self):
		return ("'pitch %s\n 'duration %s"
			% (self.pitch.lisp_expression (),
			   self.duration.lisp_expression ()))

	def pitch_mods (self):
		excl_question = ''
		if self.cautionary:
			excl_question += '?'
		if self.forced_accidental:
			excl_question += '!'

		return excl_question
	
	def ly_expression (self):
		return '%s%s%s' % (self.pitch.ly_expression (),
				   self.pitch_mods(),
				   self.duration.ly_expression ())

	def print_ly (self, printer):
		self.pitch.print_ly (printer)
		printer (self.pitch_mods ())  
		self.duration.print_ly (printer)

class KeySignatureChange (Music):
	def __init__ (self):
		Music.__init__ (self)
		self.scale = []
		self.tonic = Pitch()
		self.mode = 'major'
		
	def ly_expression (self):
		return '\\key %s \\%s' % (self.tonic.ly_step_expression (),
					  self.mode)
	
	def lisp_expression (self):
		pairs = ['(%d . %d)' % (i , self.scale[i]) for i in range (0,7)]
		scale_str = ("'(%s)" % string.join (pairs))

		return """ (make-music 'KeyChangeEvent
          'pitch-alist %s) """ % scale_str

class TimeSignatureChange (Music):
	def __init__ (self):
		Music.__init__ (self)
		self.fraction = (4,4)
	def ly_expression (self):
		return '\\time %d/%d ' % self.fraction
	
class ClefChange (Music):
	def __init__ (self):
		Music.__init__ (self)
		self.type = 'G'
		
	
	def ly_expression (self):
		return '\\clef "%s"' % self.type
	clef_dict = {
		"G": ("clefs.G", -2, -6),
		"C": ("clefs.C", 0, 0),
		"F": ("clefs.F", 2, 6),
		}
	
	def lisp_expression (self):
		(glyph, pos, c0) = self.clef_dict [self.type]
		clefsetting = """
		(make-music 'SequentialMusic
		'elements (list
      (context-spec-music
       (make-property-set 'clefGlyph "%s") 'Staff)
      (context-spec-music
       (make-property-set 'clefPosition %d) 'Staff)
      (context-spec-music
       (make-property-set 'middleCPosition %d) 'Staff)))
""" % (glyph, pos, c0)
		return clefsetting


def test_pitch ():
	bflat = Pitch()
	bflat.alteration = -1
	bflat.step =  6
	bflat.octave = -1
	fifth = Pitch()
	fifth.step = 4
	down = Pitch ()
	down.step = -4
	down.normalize ()
	
	
	print bflat.semitones()
	print bflat.transposed (fifth),  bflat.transposed (fifth).transposed (fifth)
	print bflat.transposed (fifth).transposed (fifth).transposed (fifth)

	print bflat.semitones(), 'down'
	print bflat.transposed (down)
	print bflat.transposed (down).transposed (down)
	print bflat.transposed (down).transposed (down).transposed (down)



def test_printer ():
	def make_note ():
		evc = EventChord()
		n = NoteEvent()
		evc.append (n)
		return n

	def make_tup ():
		m = SequentialMusic()
		m.append (make_note ())
		m.append (make_note ())
		m.append (make_note ())

		
		t = TimeScaledMusic ()
		t.numerator = 2
		t.denominator = 3
		t.element = m
		return t

	m = SequentialMusic ()
	m.append (make_tup ())
	m.append (make_tup ())
	m.append (make_tup ())
	
	printer = Output_printer()
	m.print_ly (printer)
	printer.newline ()
	
def test_expr ():
	m = SequentialMusic()
	l = 2  
	evc = EventChord()
	n = NoteEvent()
	n.duration.duration_log = l
	n.pitch.step = 1
	evc.insert_around (None, n, 0)
	m.insert_around (None, evc, 0)

	evc = EventChord()
	n = NoteEvent()
	n.duration.duration_log = l
	n.pitch.step = 3
	evc.insert_around (None, n, 0)
	m.insert_around (None, evc, 0)

 	evc = EventChord()
	n = NoteEvent()
	n.duration.duration_log = l
	n.pitch.step = 2 
	evc.insert_around (None, n, 0)
	m.insert_around (None, evc, 0)

 	evc = ClefChange()
	evc.type = 'treble'
	m.insert_around (None, evc, 0)

 	evc = EventChord()
	tonic = Pitch ()
	tonic.step = 2
	tonic.alteration = -2
	n = KeySignatureChange()
	n.tonic=tonic.copy()
	n.scale = [0, 0, -2, 0, 0,-2,-2]
	
	evc.insert_around (None, n, 0)
	m.insert_around (None, evc, 0)

	return m


if __name__ == '__main__':
	test_printer ()
	raise 'bla'
	test_pitch()
	
	expr = test_expr()
	expr.set_start (Rational (0))
	print expr.ly_expression()
	start = Rational (0,4)
	stop = Rational (4,2)
	def sub(x, start=start, stop=stop):
		ok = x.start >= start and x.start +x.get_length() <= stop
		return ok
	
	print expr.lisp_sub_expression(sub)