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