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