]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
Merge branch 'master-git.sv.gnu.org-lilypond.git' of /home/lilydev/vc/gub/downloads...
[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 get_midi (self, f):
336         s = open (f).read ()
337         s = re.sub ('LilyPond [0-9.]+', '', s)
338         return s
339     
340     def __init__ (self, f1, f2):
341         self.files = (f1, f2)
342
343         s1 = self.get_midi (self.files[0])
344         s2 = self.get_midi (self.files[1])
345         
346         self.same = (s1 == s2)
347         
348     def name (self):
349         name = os.path.split (self.files[0])[1]
350         name = re.sub ('.midi', '', name)
351         return name
352         
353     def distance (self):
354         ## todo: could use import MIDI to pinpoint
355         ## what & where changed.
356         if self.same:
357             return 0
358         else:
359             return 100;
360     def html_record_string (self, d1, d2):
361         return '''<tr>
362 <td>
363 %f
364 </td>
365 <td><tt>%s</tt></td>
366 <td><tt>%s</tt></td>
367 </tr>''' % ((self.distance(),) + self.files)
368
369 class SignatureFileLink (FileLink):
370     def __init__ (self):
371         self.original_name = ''
372         self.base_names = ('','')
373         self.system_links = {}
374         self._distance = None
375     def name (self):
376         return self.original_name
377     
378     def add_system_link (self, link, number):
379         self.system_links[number] = link
380
381     def calc_distance (self):
382         d = 0.0
383
384         orphan_distance = 0.0
385         for l in self.system_links.values ():
386             d = max (d, l.geometric_distance ())
387             orphan_distance += l.orphan_count ()
388             
389         return d + orphan_distance
390
391     def distance (self):
392         if type (self._distance) != type (0.0):
393             return self.calc_distance ()
394         
395         return self._distance
396
397     def source_file (self):
398         for ext in ('.ly', '.ly.txt'):
399             if os.path.exists (self.base_names[1] + ext):
400                 return self.base_names[1] + ext
401         return ''
402     
403     def add_file_compare (self, f1, f2):
404         system_index = [] 
405
406         def note_system_index (m):
407             system_index.append (int (m.group (1)))
408             return ''
409         
410         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
411         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
412
413         self.base_names = (os.path.normpath (base1),
414                            os.path.normpath (base2))
415
416         def note_original (match):
417             self.original_name = match.group (1)
418             return ''
419         
420         if not self.original_name:
421             self.original_name = os.path.split (base1)[1]
422
423             ## ugh: drop the .ly.txt
424             for ext in ('.ly', '.ly.txt'):
425                 try:
426                     re.sub (r'\\sourcefilename "([^"]+)"',
427                             note_original, open (base1 + ext).read ())
428                 except IOError:
429                     pass
430                 
431         s1 = read_signature_file (f1)
432         s2 = read_signature_file (f2)
433
434         link = SystemLink (s1, s2)
435
436         self.add_system_link (link, system_index[0])
437
438     
439     def create_images (self, old_dir, new_dir, dest_dir):
440
441         files_created = [[], []]
442         for oldnew in (0, 1):
443             pat = self.base_names[oldnew] + '.eps'
444
445             for f in glob.glob (pat):
446                 infile = f
447                 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
448
449                 mkdir (os.path.split (outfile)[0])
450                 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
451                        ' -r101 '
452                        ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
453                        ' %(infile)s  -c quit '  % locals ())
454
455                 files_created[oldnew].append (outfile)
456                 system (cmd)
457
458         return files_created
459     
460     def link_files_for_html (self, old_dir, new_dir, dest_dir):
461         to_compare = [[], []]
462
463         exts = ['.ly']
464         if options.create_images:
465             to_compare = self.create_images (old_dir, new_dir, dest_dir)
466         else:
467             exts += ['.png', '-page*png']
468         
469         for ext in exts:            
470             for oldnew in (0,1):
471                 for f in glob.glob (self.base_names[oldnew] + ext):
472                     dst = dest_dir + '/' + f
473                     link_file (f, dst)
474
475                     if f.endswith ('.png'):
476                         to_compare[oldnew].append (f)
477                         
478         if options.compare_images:                
479             for (old, new) in zip (to_compare[0], to_compare[1]):
480                 compare_png_images (old, new, dest_dir)
481
482                 
483     def html_record_string (self,  old_dir, new_dir):
484         def img_cell (ly, img, name):
485             if not name:
486                 name = 'source'
487             else:
488                 name = '<tt>%s</tt>' % name
489                 
490             return '''
491 <td align="center">
492 <a href="%(img)s">
493 <img src="%(img)s" style="border-style: none; max-width: 500px;">
494 </a><br>
495 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
496 </font>
497 </td>
498 ''' % locals ()
499         def multi_img_cell (ly, imgs, name):
500             if not name:
501                 name = 'source'
502             else:
503                 name = '<tt>%s</tt>' % name
504
505             imgs_str = '\n'.join (['''<a href="%s">
506 <img src="%s" style="border-style: none; max-width: 500px;">
507 </a><br>''' % (img, img) 
508                                   for img in imgs])
509
510
511             return '''
512 <td align="center">
513 %(imgs_str)s
514 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
515 </font>
516 </td>
517 ''' % locals ()
518
519
520
521         def cell (base, name):
522             pat = base + '-page*.png'
523             pages = glob.glob (pat)
524
525             if pages:
526                 return multi_img_cell (base + '.ly', sorted (pages), name)
527             else:
528                 return img_cell (base + '.ly', base + '.png', name)
529             
530
531         html_2  = self.base_names[1] + '.html'
532         name = self.original_name
533
534         cell_1 = cell (self.base_names[0], name)
535         cell_2 = cell (self.base_names[1], name)
536         if options.compare_images:
537             cell_2 = cell_2.replace ('.png', '.compare.jpeg')
538         
539         html_entry = '''
540 <tr>
541 <td>
542 %f<br>
543 (<a href="%s">details</a>)
544 </td>
545
546 %s
547 %s
548 </tr>
549 ''' % (self.distance (), html_2, cell_1, cell_2)
550
551         return html_entry
552
553
554     def html_system_details_string (self):
555         systems = self.system_links.items ()
556         systems.sort ()
557
558         html = ""
559         for (c, link) in systems:
560             e = '<td>%d</td>' % c
561             for d in link.distance ():
562                 e += '<td>%f</td>' % d
563             
564             e = '<tr>%s</tr>' % e
565
566             html += e
567
568             e = '<td>%d</td>' % c
569             for s in (link.output_expression_details_string (),
570                       link.orphan_details_string (),
571                       link.geo_details_string ()):
572                 e += "<td>%s</td>" % s
573
574             
575             e = '<tr>%s</tr>' % e
576             html += e
577             
578         original = self.original_name
579         html = '''<html>
580 <head>
581 <title>comparison details for %(original)s</title>
582 </head>
583 <body>
584 <table border=1>
585 <tr>
586 <th>system</th>
587 <th>output</th>
588 <th>orphan</th>
589 <th>geo</th>
590 </tr>
591
592 %(html)s
593 </table>
594
595 </body>
596 </html>
597 ''' % locals ()
598         return html
599
600     def write_html_system_details (self, dir1, dir2, dest_dir):
601         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
602
603         details = open_write_file (dest_file)
604         details.write (self.html_system_details_string ())
605
606 ################################################################
607 # Files/directories
608
609 import glob
610 import re
611
612
613
614 def compare_signature_files (f1, f2):
615     s1 = read_signature_file (f1)
616     s2 = read_signature_file (f2)
617     
618     return SystemLink (s1, s2).distance ()
619
620 def paired_files (dir1, dir2, pattern):
621     """
622     Search DIR1 and DIR2 for PATTERN.
623
624     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
625
626     """
627     
628     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
629     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
630
631     pairs = []
632     missing = []
633     for f in files1.keys ():
634         try:
635             files2.pop (f)
636             pairs.append (f)
637         except KeyError:
638             missing.append (f)
639
640     return (pairs, files2.keys (), missing)
641     
642 class ComparisonData:
643     def __init__ (self):
644         self.result_dict = {}
645         self.missing = []
646         self.added = []
647         self.file_links = {}
648
649     def compare_trees (self, dir1, dir2):
650         self.compare_directories (dir1, dir2)
651         
652         (root, dirs, files) = os.walk (dir1).next ()
653         for d in dirs:
654             d1 = os.path.join (dir1, d)
655             d2 = os.path.join (dir2, d)
656
657             if os.path.islink (d1) or os.path.islink (d2):
658                 continue
659             
660             if os.path.isdir (d2):
661                 self.compare_trees (d1, d2)
662     
663     def compare_directories (self, dir1, dir2):
664         for ext in ['signature', 'midi']:
665             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
666
667             self.missing += [(dir1, m) for m in m1] 
668             self.added += [(dir2, m) for m in m2] 
669
670             for p in paired:
671                 if (options.max_count
672                     and len (self.file_links) > options.max_count):
673                     
674                     continue
675                 
676                 f2 = dir2 +  '/' + p
677                 f1 = dir1 +  '/' + p
678                 self.compare_files (f1, f2)
679
680     def compare_files (self, f1, f2):
681         if f1.endswith ('signature'):
682             self.compare_signature_files (f1, f2)
683         elif f1.endswith ('midi'):
684             self.compare_midi_files (f1, f2)
685             
686     def compare_midi_files (self, f1, f2):
687         name = os.path.split (f1)[1]
688
689         file_link = MidiFileLink (f1, f2)
690         self.file_links[name] = file_link
691         
692     def compare_signature_files (self, f1, f2):
693         name = os.path.split (f1)[1]
694         name = re.sub ('-[0-9]+.signature', '', name)
695         
696         file_link = None
697         try:
698             file_link = self.file_links[name]
699         except KeyError:
700             file_link = SignatureFileLink ()
701             self.file_links[name] = file_link
702
703         file_link.add_file_compare (f1, f2)
704
705     def write_text_result_page (self, filename, threshold):
706         out = None
707         if filename == '':
708             out = sys.stdout
709         else:
710             print 'writing "%s"' % filename
711             out = open_write_file (filename)
712
713         ## todo: support more scores.
714         results = [(link.distance(), link)
715                    for link in self.file_links.values ()]
716         results.sort ()
717         results.reverse ()
718
719         
720         for (score, link) in results:
721             if score > threshold:
722                 out.write (link.text_record_string ())
723
724         out.write ('\n\n')
725         out.write ('%d below threshold\n' % len ([1 for s,l  in results
726                                                     if threshold >=  s > 0.0]))
727         out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
728         
729     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
730         self.write_text_result_page (dest_dir + '/index.txt', threshold)
731         
732     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
733         dir1 = dir1.replace ('//', '/')
734         dir2 = dir2.replace ('//', '/')
735         
736         results = [(link.distance(), link)
737                    for link in self.file_links.values ()]
738         results.sort ()
739         results.reverse ()
740
741         html = ''
742         old_prefix = os.path.split (dir1)[1]
743         for (score, link) in results:
744             if score <= threshold:
745                 continue
746
747             link.link_files_for_html (dir1, dir2, dest_dir) 
748             link.write_html_system_details (dir1, dir2, dest_dir)
749             
750             html += link.html_record_string (dir1, dir2)
751
752
753         short_dir1 = shorten_string (dir1)
754         short_dir2 = shorten_string (dir2)
755         html = '''<html>
756 <table rules="rows" border bordercolor="blue">
757 <tr>
758 <th>distance</th>
759 <th>%(short_dir1)s</th>
760 <th>%(short_dir2)s</th>
761 </tr>
762 %(html)s
763 </table>
764 </html>''' % locals()
765
766         html += ('<p>')
767         below_count  =len ([1 for s,l  in results
768                             if threshold >=  s > 0.0])
769
770         if below_count:
771             html += ('<p>%d below threshold</p>' % below_count)
772
773         html += ('<p>%d unchanged</p>'
774                  % len ([1 for (s,l) in results if s == 0.0]))
775
776
777         dest_file = dest_dir + '/index.html'
778         open_write_file (dest_file).write (html)
779         
780     def print_results (self, threshold):
781         self.write_text_result_page ('', threshold)
782
783 def compare_trees (dir1, dir2, dest_dir, threshold):
784     data = ComparisonData ()
785     data.compare_trees (dir1, dir2)
786     data.print_results (threshold)
787
788     if os.path.isdir (dest_dir):
789         system ('rm -rf %s '% dest_dir)
790
791     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
792     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
793     
794 ################################################################
795 # TESTING
796
797 def mkdir (x):
798     if not os.path.isdir (x):
799         print 'mkdir', x
800         os.makedirs (x)
801
802 def link_file (x, y):
803     mkdir (os.path.split (y)[0])
804     try:
805         os.link (x, y)
806     except OSError, z:
807         print 'OSError', x, y, z
808         raise OSError
809     
810 def open_write_file (x):
811     d = os.path.split (x)[0]
812     mkdir (d)
813     return open (x, 'w')
814
815
816 def system (x):
817     
818     print 'invoking', x
819     stat = os.system (x)
820     assert stat == 0
821
822
823 def test_paired_files ():
824     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
825                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
826                   
827     
828 def test_compare_trees ():
829     system ('rm -rf dir1 dir2')
830     system ('mkdir dir1 dir2')
831     system ('cp 20{-*.signature,.ly,.png,.eps} dir1')
832     system ('cp 20{-*.signature,.ly,.png,.eps} dir2')
833     system ('cp 20expr{-*.signature,.ly,.png,.eps} dir1')
834     system ('cp 19{-*.signature,.ly,.png,.eps} dir2/')
835     system ('cp 19{-*.signature,.ly,.png,.eps} dir1/')
836     system ('cp 19-1.signature 19-sub-1.signature')
837     system ('cp 19.ly 19-sub.ly')
838     system ('cp 19.png 19-sub.png')
839     system ('cp 19.eps 19-sub.eps')
840
841     system ('cp 20multipage* dir1')
842     system ('cp 20multipage* dir2')
843     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
844
845     
846     system ('mkdir -p dir1/subdir/ dir2/subdir/')
847     system ('cp 19-sub{-*.signature,.ly,.png,.eps} dir1/subdir/')
848     system ('cp 19-sub{-*.signature,.ly,.png,.eps} dir2/subdir/')
849     system ('cp 20grob{-*.signature,.ly,.png,.eps} dir2/')
850     system ('cp 20grob{-*.signature,.ly,.png,.eps} dir1/')
851
852     ## introduce differences
853     system ('cp 19-1.signature dir2/20-1.signature')
854     system ('cp 19.png dir2/20.png')
855     system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
856     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
857     system ('cp 20.png dir2/subdir/19-sub.png')
858
859     ## radical diffs.
860     system ('cp 19-1.signature dir2/20grob-1.signature')
861     system ('cp 19-1.signature dir2/20grob-2.signature')
862     system ('cp 19multipage.midi dir1/midi-differ.midi')
863     system ('cp 20multipage.midi dir2/midi-differ.midi')
864
865     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
866
867
868 def test_basic_compare ():
869     ly_template = r"""
870
871 \version "2.10.0"
872 #(set! toplevel-score-handler print-score-with-defaults)
873  #(set! toplevel-music-handler
874   (lambda (p m)
875   (if (not (eq? (ly:music-property m 'void) #t))
876      (print-score-with-defaults
877      p (scorify-music m p)))))
878
879 \sourcefilename "my-source.ly"
880  
881 %(papermod)s
882 \header { tagline = ##f }
883 \score {
884 <<
885 \new Staff \relative c {
886   c4^"%(userstring)s" %(extragrob)s
887   }
888 \new Staff \relative c {
889   c4^"%(userstring)s" %(extragrob)s
890   }
891 >>
892 \layout{}
893 }
894
895 """
896
897     dicts = [{ 'papermod' : '',
898                'name' : '20',
899                'extragrob': '',
900                'userstring': 'test' },
901              { 'papermod' : '#(set-global-staff-size 19.5)',
902                'name' : '19',
903                'extragrob': '',
904                'userstring': 'test' },
905              { 'papermod' : '',
906                'name' : '20expr',
907                'extragrob': '',
908                'userstring': 'blabla' },
909              { 'papermod' : '',
910                'name' : '20grob',
911                'extragrob': 'r2. \\break c1',
912                'userstring': 'test' },
913              ]
914
915     for d in dicts:
916         open (d['name'] + '.ly','w').write (ly_template % d)
917         
918     names = [d['name'] for d in dicts]
919     
920     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
921     
922
923     multipage_str = r'''
924     #(set-default-paper-size "a6")
925     \score {
926       \relative {c1 \pageBreak c1 }
927       \layout {}
928       \midi {}
929     }
930     '''
931
932     open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
933     open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
934     system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
935  
936     test_compare_signatures (names)
937     
938 def test_compare_signatures (names, timing=False):
939
940     import time
941
942     times = 1
943     if timing:
944         times = 100
945
946     t0 = time.clock ()
947
948     count = 0
949     for t in range (0, times):
950         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
951         count += 1
952
953     if timing:
954         print 'elapsed', (time.clock() - t0)/count
955
956
957     t0 = time.clock ()
958     count = 0
959     combinations = {}
960     for (n1, s1) in sigs.items():
961         for (n2, s2) in sigs.items():
962             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
963             count += 1
964
965     if timing:
966         print 'elapsed', (time.clock() - t0)/count
967
968     results = combinations.items ()
969     results.sort ()
970     for k,v in results:
971         print '%-20s' % k, v
972
973     assert combinations['20-20'] == (0.0,0.0,0.0)
974     assert combinations['20-20expr'][0] > 0.0
975     assert combinations['20-19'][2] < 10.0
976     assert combinations['20-19'][2] > 0.0
977
978
979 def run_tests ():
980     dir = 'test-output-distance'
981
982     do_clean = not os.path.exists (dir)
983
984     print 'test results in ', dir
985     if do_clean:
986         system ('rm -rf ' + dir)
987         system ('mkdir ' + dir)
988         
989     os.chdir (dir)
990     if do_clean:
991         test_basic_compare ()
992         
993     test_compare_trees ()
994     
995 ################################################################
996 #
997
998 def main ():
999     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1000     p.usage = 'output-distance.py [options] tree1 tree2'
1001     
1002     p.add_option ('', '--test-self',
1003                   dest="run_test",
1004                   action="store_true",
1005                   help='run test method')
1006     
1007     p.add_option ('--max-count',
1008                   dest="max_count",
1009                   metavar="COUNT",
1010                   type="int",
1011                   default=0, 
1012                   action="store",
1013                   help='only analyze COUNT signature pairs')
1014
1015     p.add_option ('', '--threshold',
1016                   dest="threshold",
1017                   default=0.3,
1018                   action="store",
1019                   type="float",
1020                   help='threshold for geometric distance')
1021
1022     p.add_option ('--no-compare-images',
1023                   dest="compare_images",
1024                   default=True,
1025                   action="store_false",
1026                   help="Don't run graphical comparisons")
1027
1028     p.add_option ('--create-images',
1029                   dest="create_images",
1030                   default=False,
1031                   action="store_true",
1032                   help="Create PNGs from EPSes")
1033
1034     p.add_option ('-o', '--output-dir',
1035                   dest="output_dir",
1036                   default=None,
1037                   action="store",
1038                   type="string",
1039                   help='where to put the test results [tree2/compare-tree1tree2]')
1040
1041     global options
1042     (options, a) = p.parse_args ()
1043
1044     if options.run_test:
1045         run_tests ()
1046         sys.exit (0)
1047
1048     if len (a) != 2:
1049         p.print_usage()
1050         sys.exit (2)
1051
1052     name = options.output_dir
1053     if not name:
1054         name = a[0].replace ('/', '')
1055         name = os.path.join (a[1], 'compare-' + shorten_string (name))
1056     
1057     compare_trees (a[0], a[1], name, options.threshold)
1058
1059 if __name__ == '__main__':
1060     main()
1061