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