]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
output-distance: no-compare-images
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4 import os
5
6 ## so we can call directly as buildscripts/output-distance.py
7 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
8 sys.path.insert (0, me_path + '/../python/')
9
10
11 import safeeval
12
13
14 X_AXIS = 0
15 Y_AXIS = 1
16 INFTY = 1e6
17
18 OUTPUT_EXPRESSION_PENALTY = 1
19 ORPHAN_GROB_PENALTY = 1
20 options = None
21
22 def shorten_string (s):
23     threshold = 15 
24     if len (s) > 2*threshold:
25         s = s[:threshold] + '..' + s[-threshold:]
26     return s
27
28 def max_distance (x1, x2):
29     dist = 0.0
30
31     for (p,q) in zip (x1, x2):
32         dist = max (abs (p-q), dist)
33         
34     return dist
35
36
37 empty_interval = (INFTY, -INFTY)
38 empty_bbox = (empty_interval, empty_interval)
39
40 def interval_is_empty (i):
41     return i[0] > i[1]
42
43 def interval_length (i):
44     return max (i[1]-i[0], 0) 
45     
46 def interval_union (i1, i2):
47     return (min (i1[0], i2[0]),
48             max (i1[1], i2[1]))
49
50 def interval_intersect (i1, i2):
51     return (max (i1[0], i2[0]),
52             min (i1[1], i2[1]))
53
54 def bbox_is_empty (b):
55     return (interval_is_empty (b[0])
56             or interval_is_empty (b[1]))
57
58 def bbox_union (b1, b2):
59     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
60             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
61             
62 def bbox_intersection (b1, b2):
63     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
64             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
65
66 def bbox_area (b):
67     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
68
69 def bbox_diameter (b):
70     return max (interval_length (b[X_AXIS]),
71                 interval_length (b[Y_AXIS]))
72                 
73
74 def difference_area (a, b):
75     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
76
77 class GrobSignature:
78     def __init__ (self, exp_list):
79         (self.name, self.origin, bbox_x,
80          bbox_y, self.output_expression) = tuple (exp_list)
81         
82         self.bbox = (bbox_x, bbox_y)
83         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
84
85     def __repr__ (self):
86         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
87                                                    self.bbox[0][0],
88                                                    self.bbox[0][1],
89                                                    self.bbox[1][0],
90                                                    self.bbox[1][1])
91                                                  
92     def axis_centroid (self, axis):
93         return apply (sum, self.bbox[axis])  / 2 
94     
95     def centroid_distance (self, other, scale):
96         return max_distance (self.centroid, other.centroid) / scale 
97         
98     def bbox_distance (self, other):
99         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
100
101         if divisor:
102             return (difference_area (self.bbox, other.bbox) +
103                     difference_area (other.bbox, self.bbox)) / divisor
104         else:
105             return 0.0
106         
107     def expression_distance (self, other):
108         if self.output_expression == other.output_expression:
109             return 0
110         else:
111             return 1
112
113 ################################################################
114 # single System.
115
116 class SystemSignature:
117     def __init__ (self, grob_sigs):
118         d = {}
119         for g in grob_sigs:
120             val = d.setdefault (g.name, [])
121             val += [g]
122
123         self.grob_dict = d
124         self.set_all_bbox (grob_sigs)
125
126     def set_all_bbox (self, grobs):
127         self.bbox = empty_bbox
128         for g in grobs:
129             self.bbox = bbox_union (g.bbox, self.bbox)
130
131     def closest (self, grob_name, centroid):
132         min_d = INFTY
133         min_g = None
134         try:
135             grobs = self.grob_dict[grob_name]
136
137             for g in grobs:
138                 d = max_distance (g.centroid, centroid)
139                 if d < min_d:
140                     min_d = d
141                     min_g = g
142
143
144             return min_g
145
146         except KeyError:
147             return None
148     def grobs (self):
149         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
150
151 ################################################################
152 ## comparison of systems.
153
154 class SystemLink:
155     def __init__ (self, system1, system2):
156         self.system1 = system1
157         self.system2 = system2
158         
159         self.link_list_dict = {}
160         self.back_link_dict = {}
161
162
163         ## pairs
164         self.orphans = []
165
166         ## pair -> distance
167         self.geo_distances = {}
168
169         ## pairs
170         self.expression_changed = []
171
172         self._geometric_distance = None
173         self._expression_change_count = None
174         self._orphan_count = None
175         
176         for g in system1.grobs ():
177
178             ## skip empty bboxes.
179             if bbox_is_empty (g.bbox):
180                 continue
181             
182             closest = system2.closest (g.name, g.centroid)
183             
184             self.link_list_dict.setdefault (closest, [])
185             self.link_list_dict[closest].append (g)
186             self.back_link_dict[g] = closest
187
188
189     def calc_geometric_distance (self):
190         total = 0.0
191         for (g1,g2) in self.back_link_dict.items ():
192             if g2:
193                 d = g1.bbox_distance (g2)
194                 if d:
195                     self.geo_distances[(g1,g2)] = d
196
197                 total += d
198
199         self._geometric_distance = total
200     
201     def calc_orphan_count (self):
202         count = 0
203         for (g1, g2) in self.back_link_dict.items ():
204             if g2 == None:
205                 self.orphans.append ((g1, None))
206                 
207                 count += 1
208
209         self._orphan_count = count
210     
211     def calc_output_exp_distance (self):
212         d = 0
213         for (g1,g2) in self.back_link_dict.items ():
214             if g2:
215                 d += g1.expression_distance (g2)
216
217         self._expression_change_count = d
218
219     def output_expression_details_string (self):
220         return ', '.join ([g1.name for g1 in self.expression_changed])
221     
222     def geo_details_string (self):
223         results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
224         results.sort ()
225         results.reverse ()
226         
227         return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
228
229     def orphan_details_string (self):
230         return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
231
232     def geometric_distance (self):
233         if self._geometric_distance == None:
234             self.calc_geometric_distance ()
235         return self._geometric_distance
236     
237     def orphan_count (self):
238         if self._orphan_count == None:
239             self.calc_orphan_count ()
240             
241         return self._orphan_count
242     
243     def output_expression_change_count (self):
244         if self._expression_change_count == None:
245             self.calc_output_exp_distance ()
246         return self._expression_change_count
247         
248     def distance (self):
249         return (self.output_expression_change_count (),
250                 self.orphan_count (),
251                 self.geometric_distance ())
252     
253 def read_signature_file (name):
254     print 'reading', name
255     
256     entries = open (name).read ().split ('\n')
257     def string_to_tup (s):
258         return tuple (map (float, s.split (' '))) 
259
260     def string_to_entry (s):
261         fields = s.split('@')
262         fields[2] = string_to_tup (fields[2])
263         fields[3] = string_to_tup (fields[3])
264
265         return tuple (fields)
266     
267     entries = [string_to_entry (e) for e in entries
268                if e and not e.startswith ('#')]
269
270     grob_sigs = [GrobSignature (e) for e in entries]
271     sig = SystemSignature (grob_sigs)
272     return sig
273
274
275 ################################################################
276 # different systems of a .ly file.
277 def read_pipe (c):
278     print 'pipe' , c
279     return os.popen (c).read ()
280
281 def system (c):
282     print 'system' , c
283     s = os.system (c)
284     if s :
285         raise Exception ("failed")
286     return
287
288 def compare_png_images (old, new, dir):
289     def png_dims (f):
290         m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
291         
292         return tuple (map (int, m.groups ()))
293
294     dest = os.path.join (dir, new.replace ('.png', '.compare.jpeg'))
295     try:
296         dims1 = png_dims (old)
297         dims2 = png_dims (new)
298     except AttributeError:
299         ## hmmm. what to do?
300         system ('touch %(dest)s' % locals ())
301         return
302     
303     dims = (min (dims1[0], dims2[0]),
304             min (dims1[1], dims2[1]))
305
306     system ('convert -depth 8 -crop %dx%d+0+0 %s crop1.png' % (dims + (old,)))
307     system ('convert -depth 8 -crop %dx%d+0+0 %s crop2.png' % (dims + (new,)))
308
309     system ('compare -depth 8 crop1.png crop2.png diff.png')
310
311     system ("convert  -depth 8 diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity'    matte.png")
312
313     system ("composite -quality 65 matte.png %(new)s %(dest)s" % locals ())
314
315 class FileLink:
316     def text_record_string (self):
317         return '%-30f %-20s\n' % (self.distance (),
318                                   self.name ())
319     def distance (self):
320         return 0.0
321
322     def name (self):
323         return ''
324     
325     def link_files_for_html (self, old_dir, new_dir, dest_dir):
326         pass
327
328     def write_html_system_details (self, dir1, dir2, dest_dir):
329         pass
330         
331     def html_record_string (self,  old_dir, new_dir):
332         return ''
333
334 class MidiFileLink (FileLink):
335     def __init__ (self, f1, f2):
336         self.files = (f1, f2)
337
338         print 'reading', f1
339         s1 = open (self.files[0]).read ()
340         print 'reading', f2
341         s2 = open (self.files[1]).read ()
342
343         self.same = (s1 == s2)
344         
345     def name (self):
346         name = os.path.split (self.files[0])[1]
347         name = re.sub ('.midi', '', name)
348         return name
349         
350     def distance (self):
351         ## todo: could use import MIDI to pinpoint
352         ## what & where changed.
353         if self.same:
354             return 0
355         else:
356             return 100;
357     def html_record_string (self, d1, d2):
358         return '''<tr>
359 <td>
360 %f
361 </td>
362 <td><tt>%s</tt></td>
363 <td><tt>%s</tt></td>
364 </tr>''' % ((self.distance(),) + self.files)
365
366 class SignatureFileLink (FileLink):
367     def __init__ (self):
368         self.original_name = ''
369         self.base_names = ('','')
370         self.system_links = {}
371         self._distance = None
372     def name (self):
373         return self.original_name
374     
375     def add_system_link (self, link, number):
376         self.system_links[number] = link
377
378     def calc_distance (self):
379         d = 0.0
380
381         orphan_distance = 0.0
382         for l in self.system_links.values ():
383             d = max (d, l.geometric_distance ())
384             orphan_distance += l.orphan_count ()
385             
386         return d + orphan_distance
387
388     def distance (self):
389         if type (self._distance) != type (0.0):
390             return self.calc_distance ()
391         
392         return self._distance
393
394     def source_file (self):
395         for ext in ('.ly', '.ly.txt'):
396             if os.path.exists (self.base_names[1] + ext):
397                 return self.base_names[1] + ext
398         return ''
399     
400     def add_file_compare (self, f1, f2):
401         system_index = [] 
402
403         def note_system_index (m):
404             system_index.append (int (m.group (1)))
405             return ''
406         
407         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
408         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
409
410         self.base_names = (os.path.normpath (base1),
411                            os.path.normpath (base2))
412
413         def note_original (match):
414             self.original_name = match.group (1)
415             return ''
416         
417         if not self.original_name:
418             self.original_name = os.path.split (base1)[1]
419
420             ## ugh: drop the .ly.txt
421             for ext in ('.ly', '.ly.txt'):
422                 try:
423                     re.sub (r'\\sourcefilename "([^"]+)"',
424                             note_original, open (base1 + ext).read ())
425                 except IOError:
426                     pass
427                 
428         s1 = read_signature_file (f1)
429         s2 = read_signature_file (f2)
430
431         link = SystemLink (s1, s2)
432
433         self.add_system_link (link, system_index[0])
434
435     def link_files_for_html (self, old_dir, new_dir, dest_dir):
436         png_linked = [[], []]
437         for ext in ('.png', '.ly', '-page*png'):
438             
439             for oldnew in (0,1):
440                 for f in glob.glob (self.base_names[oldnew] + ext):
441                     dst = dest_dir + '/' + f
442                     link_file (f, dst)
443
444                     if f.endswith ('.png'):
445                         png_linked[oldnew].append (f)
446                         
447         if options.compare_images:                
448             for (old,new) in zip (png_linked[0], png_linked[1]):
449                 compare_png_images (old, new, dest_dir)
450                 
451     def html_record_string (self,  old_dir, new_dir):
452         def img_cell (ly, img, name):
453             if not name:
454                 name = 'source'
455             else:
456                 name = '<tt>%s</tt>' % name
457                 
458             return '''
459 <td align="center">
460 <a href="%(img)s">
461 <img src="%(img)s" style="border-style: none; max-width: 500px;">
462 </a><br>
463 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
464 </font>
465 </td>
466 ''' % locals ()
467
468         def multi_img_cell (ly, imgs, name):
469             if not name:
470                 name = 'source'
471             else:
472                 name = '<tt>%s</tt>' % name
473
474             imgs_str = '\n'.join (['''<a href="%s">
475 <img src="%s" style="border-style: none; max-width: 500px;">
476 </a><br>''' % (img, img) 
477                                   for img in imgs])
478
479
480             return '''
481 <td align="center">
482 %(imgs_str)s
483 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
484 </font>
485 </td>
486 ''' % locals ()
487
488
489
490         def cell (base, name):
491             pat = base + '-page*.png'
492             pages = glob.glob (pat)
493
494             if pages:
495                 return multi_img_cell (base + '.ly', sorted (pages), name)
496             else:
497                 return img_cell (base + '.ly', base + '.png', name)
498             
499
500         html_2  = self.base_names[1] + '.html'
501         name = self.original_name
502
503         cell_1 = cell (self.base_names[0], name)
504         cell_2 = cell (self.base_names[1], name)
505         if options.compare_images:
506             cell_2 = cell_2.replace ('.png', '.compare.jpeg')
507         
508         html_entry = '''
509 <tr>
510 <td>
511 %f<br>
512 (<a href="%s">details</a>)
513 </td>
514
515 %s
516 %s
517 </tr>
518 ''' % (self.distance (), html_2, cell_1, cell_2)
519
520         return html_entry
521
522
523     def html_system_details_string (self):
524         systems = self.system_links.items ()
525         systems.sort ()
526
527         html = ""
528         for (c, link) in systems:
529             e = '<td>%d</td>' % c
530             for d in link.distance ():
531                 e += '<td>%f</td>' % d
532             
533             e = '<tr>%s</tr>' % e
534
535             html += e
536
537             e = '<td>%d</td>' % c
538             for s in (link.output_expression_details_string (),
539                       link.orphan_details_string (),
540                       link.geo_details_string ()):
541                 e += "<td>%s</td>" % s
542
543             
544             e = '<tr>%s</tr>' % e
545             html += e
546             
547         original = self.original_name
548         html = '''<html>
549 <head>
550 <title>comparison details for %(original)s</title>
551 </head>
552 <body>
553 <table border=1>
554 <tr>
555 <th>system</th>
556 <th>output</th>
557 <th>orphan</th>
558 <th>geo</th>
559 </tr>
560
561 %(html)s
562 </table>
563
564 </body>
565 </html>
566 ''' % locals ()
567         return html
568
569     def write_html_system_details (self, dir1, dir2, dest_dir):
570         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
571
572         details = open_write_file (dest_file)
573         details.write (self.html_system_details_string ())
574
575 ################################################################
576 # Files/directories
577
578 import glob
579 import re
580
581
582
583 def compare_signature_files (f1, f2):
584     s1 = read_signature_file (f1)
585     s2 = read_signature_file (f2)
586     
587     return SystemLink (s1, s2).distance ()
588
589 def paired_files (dir1, dir2, pattern):
590     """
591     Search DIR1 and DIR2 for PATTERN.
592
593     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
594
595     """
596     
597     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
598     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
599
600     pairs = []
601     missing = []
602     for f in files1.keys ():
603         try:
604             files2.pop (f)
605             pairs.append (f)
606         except KeyError:
607             missing.append (f)
608
609     return (pairs, files2.keys (), missing)
610     
611 class ComparisonData:
612     def __init__ (self):
613         self.result_dict = {}
614         self.missing = []
615         self.added = []
616         self.file_links = {}
617
618     def compare_trees (self, dir1, dir2):
619         self.compare_directories (dir1, dir2)
620         
621         (root, dirs, files) = os.walk (dir1).next ()
622         for d in dirs:
623             d1 = os.path.join (dir1, d)
624             d2 = os.path.join (dir2, d)
625
626             if os.path.islink (d1) or os.path.islink (d2):
627                 continue
628             
629             if os.path.isdir (d2):
630                 self.compare_trees (d1, d2)
631     
632     def compare_directories (self, dir1, dir2):
633         for ext in ['signature', 'midi']:
634             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
635
636             self.missing += [(dir1, m) for m in m1] 
637             self.added += [(dir2, m) for m in m2] 
638
639             for p in paired:
640                 if (options.max_count
641                     and len (self.file_links) > options.max_count):
642                     
643                     continue
644                 
645                 f2 = dir2 +  '/' + p
646                 f1 = dir1 +  '/' + p
647                 self.compare_files (f1, f2)
648
649     def compare_files (self, f1, f2):
650         if f1.endswith ('signature'):
651             self.compare_signature_files (f1, f2)
652         elif f1.endswith ('midi'):
653             self.compare_midi_files (f1, f2)
654             
655     def compare_midi_files (self, f1, f2):
656         name = os.path.split (f1)[1]
657
658         file_link = MidiFileLink (f1, f2)
659         self.file_links[name] = file_link
660         
661     def compare_signature_files (self, f1, f2):
662         name = os.path.split (f1)[1]
663         name = re.sub ('-[0-9]+.signature', '', name)
664         
665         file_link = None
666         try:
667             file_link = self.file_links[name]
668         except KeyError:
669             file_link = SignatureFileLink ()
670             self.file_links[name] = file_link
671
672         file_link.add_file_compare (f1, f2)
673
674     def write_text_result_page (self, filename, threshold):
675         out = None
676         if filename == '':
677             out = sys.stdout
678         else:
679             print 'writing "%s"' % filename
680             out = open_write_file (filename)
681
682         ## todo: support more scores.
683         results = [(link.distance(), link)
684                    for link in self.file_links.values ()]
685         results.sort ()
686         results.reverse ()
687
688         
689         for (score, link) in results:
690             if score > threshold:
691                 out.write (link.text_record_string ())
692
693         out.write ('\n\n')
694         out.write ('%d below threshold\n' % len ([1 for s,l  in results
695                                                     if threshold >=  s > 0.0]))
696         out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
697         
698     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
699         self.write_text_result_page (dest_dir + '/index.txt', threshold)
700         
701     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
702         dir1 = dir1.replace ('//', '/')
703         dir2 = dir2.replace ('//', '/')
704         
705         results = [(link.distance(), link)
706                    for link in self.file_links.values ()]
707         results.sort ()
708         results.reverse ()
709
710         html = ''
711         old_prefix = os.path.split (dir1)[1]
712         for (score, link) in results:
713             if score <= threshold:
714                 continue
715
716             link.link_files_for_html (dir1, dir2, dest_dir) 
717             link.write_html_system_details (dir1, dir2, dest_dir)
718             
719             html += link.html_record_string (dir1, dir2)
720
721
722         short_dir1 = shorten_string (dir1)
723         short_dir2 = shorten_string (dir2)
724         html = '''<html>
725 <table rules="rows" border bordercolor="blue">
726 <tr>
727 <th>distance</th>
728 <th>%(short_dir1)s</th>
729 <th>%(short_dir2)s</th>
730 </tr>
731 %(html)s
732 </table>
733 </html>''' % locals()
734
735         html += ('<p>')
736         below_count  =len ([1 for s,l  in results
737                             if threshold >=  s > 0.0])
738
739         if below_count:
740             html += ('<p>%d below threshold</p>' % below_count)
741
742         html += ('<p>%d unchanged</p>'
743                  % len ([1 for (s,l) in results if s == 0.0]))
744
745
746         dest_file = dest_dir + '/index.html'
747         open_write_file (dest_file).write (html)
748         
749     def print_results (self, threshold):
750         self.write_text_result_page ('', threshold)
751
752 def compare_trees (dir1, dir2, dest_dir, threshold):
753     data = ComparisonData ()
754     data.compare_trees (dir1, dir2)
755     data.print_results (threshold)
756
757     if os.path.isdir (dest_dir):
758         system ('rm -rf %s '% dest_dir)
759
760     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
761     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
762     
763 ################################################################
764 # TESTING
765
766 def mkdir (x):
767     if not os.path.isdir (x):
768         print 'mkdir', x
769         os.makedirs (x)
770
771 def link_file (x, y):
772     mkdir (os.path.split (y)[0])
773     try:
774         os.link (x, y)
775     except OSError, z:
776         print 'OSError', x, y, z
777         raise OSError
778     
779 def open_write_file (x):
780     d = os.path.split (x)[0]
781     mkdir (d)
782     return open (x, 'w')
783
784
785 def system (x):
786     
787     print 'invoking', x
788     stat = os.system (x)
789     assert stat == 0
790
791
792 def test_paired_files ():
793     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
794                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
795                   
796     
797 def test_compare_trees ():
798     system ('rm -rf dir1 dir2')
799     system ('mkdir dir1 dir2')
800     system ('cp 20{-*.signature,.ly,.png} dir1')
801     system ('cp 20{-*.signature,.ly,.png} dir2')
802     system ('cp 20expr{-*.signature,.ly,.png} dir1')
803     system ('cp 19{-*.signature,.ly,.png} dir2/')
804     system ('cp 19{-*.signature,.ly,.png} dir1/')
805     system ('cp 19-1.signature 19-sub-1.signature')
806     system ('cp 19.ly 19-sub.ly')
807     system ('cp 19.png 19-sub.png')
808
809     system ('cp 20multipage* dir1')
810     system ('cp 20multipage* dir2')
811     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
812
813     
814     system ('mkdir -p dir1/subdir/ dir2/subdir/')
815     system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
816     system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
817     system ('cp 20grob{-*.signature,.ly,.png} dir2/')
818     system ('cp 20grob{-*.signature,.ly,.png} dir1/')
819
820     ## introduce differences
821     system ('cp 19-1.signature dir2/20-1.signature')
822     system ('cp 19.png dir2/20.png')
823     system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
824     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
825     system ('cp 20.png dir2/subdir/19-sub.png')
826
827     ## radical diffs.
828     system ('cp 19-1.signature dir2/20grob-1.signature')
829     system ('cp 19-1.signature dir2/20grob-2.signature')
830     system ('cp 19multipage.midi dir1/midi-differ.midi')
831     system ('cp 20multipage.midi dir2/midi-differ.midi')
832
833     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
834
835
836 def test_basic_compare ():
837     ly_template = r"""
838
839 \version "2.10.0"
840 #(set! toplevel-score-handler print-score-with-defaults)
841  #(set! toplevel-music-handler
842   (lambda (p m)
843   (if (not (eq? (ly:music-property m 'void) #t))
844      (print-score-with-defaults
845      p (scorify-music m p)))))
846
847 \sourcefilename "my-source.ly"
848  
849 %(papermod)s
850 \header { tagline = ##f }
851 \score {
852 <<
853 \new Staff \relative c {
854   c4^"%(userstring)s" %(extragrob)s
855   }
856 \new Staff \relative c {
857   c4^"%(userstring)s" %(extragrob)s
858   }
859 >>
860 \layout{}
861 }
862
863 """
864
865     dicts = [{ 'papermod' : '',
866                'name' : '20',
867                'extragrob': '',
868                'userstring': 'test' },
869              { 'papermod' : '#(set-global-staff-size 19.5)',
870                'name' : '19',
871                'extragrob': '',
872                'userstring': 'test' },
873              { 'papermod' : '',
874                'name' : '20expr',
875                'extragrob': '',
876                'userstring': 'blabla' },
877              { 'papermod' : '',
878                'name' : '20grob',
879                'extragrob': 'r2. \\break c1',
880                'userstring': 'test' },
881              ]
882
883     for d in dicts:
884         open (d['name'] + '.ly','w').write (ly_template % d)
885         
886     names = [d['name'] for d in dicts]
887     
888     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
889     
890
891     multipage_str = r'''
892     #(set-default-paper-size "a6")
893     \score {
894       \relative {c1 \pageBreak c1 }
895       \layout {}
896       \midi {}
897     }
898     '''
899
900     open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
901     open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
902     system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
903  
904     test_compare_signatures (names)
905     
906 def test_compare_signatures (names, timing=False):
907
908     import time
909
910     times = 1
911     if timing:
912         times = 100
913
914     t0 = time.clock ()
915
916     count = 0
917     for t in range (0, times):
918         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
919         count += 1
920
921     if timing:
922         print 'elapsed', (time.clock() - t0)/count
923
924
925     t0 = time.clock ()
926     count = 0
927     combinations = {}
928     for (n1, s1) in sigs.items():
929         for (n2, s2) in sigs.items():
930             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
931             count += 1
932
933     if timing:
934         print 'elapsed', (time.clock() - t0)/count
935
936     results = combinations.items ()
937     results.sort ()
938     for k,v in results:
939         print '%-20s' % k, v
940
941     assert combinations['20-20'] == (0.0,0.0,0.0)
942     assert combinations['20-20expr'][0] > 0.0
943     assert combinations['20-19'][2] < 10.0
944     assert combinations['20-19'][2] > 0.0
945
946
947 def run_tests ():
948     dir = 'test-output-distance'
949
950     do_clean = not os.path.exists (dir)
951
952     print 'test results in ', dir
953     if do_clean:
954         system ('rm -rf ' + dir)
955         system ('mkdir ' + dir)
956         
957     os.chdir (dir)
958     if do_clean:
959         test_basic_compare ()
960         
961     test_compare_trees ()
962     
963 ################################################################
964 #
965
966 def main ():
967     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
968     p.usage = 'output-distance.py [options] tree1 tree2'
969     
970     p.add_option ('', '--test-self',
971                   dest="run_test",
972                   action="store_true",
973                   help='run test method')
974     
975     p.add_option ('--max-count',
976                   dest="max_count",
977                   metavar="COUNT",
978                   type="int",
979                   default=0, 
980                   action="store",
981                   help='only analyze COUNT signature pairs')
982
983     p.add_option ('', '--threshold',
984                   dest="threshold",
985                   default=0.3,
986                   action="store",
987                   type="float",
988                   help='threshold for geometric distance')
989
990     p.add_option ('--no-compare-images',
991                   dest="compare_images",
992                   default=True,
993                   action="store_false",
994                   help="Don't run graphical comparisons")
995
996     p.add_option ('-o', '--output-dir',
997                   dest="output_dir",
998                   default=None,
999                   action="store",
1000                   type="string",
1001                   help='where to put the test results [tree2/compare-tree1tree2]')
1002
1003     global options
1004     (options, a) = p.parse_args ()
1005
1006     if options.run_test:
1007         run_tests ()
1008         sys.exit (0)
1009
1010     if len (a) != 2:
1011         p.print_usage()
1012         sys.exit (2)
1013
1014     name = options.output_dir
1015     if not name:
1016         name = a[0].replace ('/', '')
1017         name = os.path.join (a[1], 'compare-' + shorten_string (name))
1018     
1019     compare_trees (a[0], a[1], name, options.threshold)
1020
1021 if __name__ == '__main__':
1022     main()
1023