]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
increase time-performance importance.
[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         dist = self.distance()
387         
388         details = self.get_distance_details ()
389         if details:
390             details_base = os.path.splitext (self.file_names[1])[0]
391             details_base += '.details.html'
392             fn = dest_dir + '/'  + details_base
393             open_write_file (fn).write (details)
394
395             details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
396
397         cell1 = self.get_cell (0)
398         cell2 = self.get_cell (1)
399
400         name = self.name () + self.extension ()
401         file1 = self.get_file (0)
402         file2 = self.get_file (1)
403         
404         return '''<tr>
405 <td>
406 %(dist)f
407 %(details)s
408 </td>
409 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
410 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
411 </tr>''' % locals ()
412
413
414 class FileCompareLink (FileLink):
415     def __init__ (self, f1, f2):
416         FileLink.__init__ (self, f1, f2)
417         self.contents = (self.get_content (self.file_names[0]),
418                          self.get_content (self.file_names[1]))
419         
420
421     def calc_distance (self):
422         ## todo: could use import MIDI to pinpoint
423         ## what & where changed.
424
425         if self.contents[0] == self.contents[1]:
426             return 0.0
427         else:
428             return 100.0;
429         
430     def get_content (self, f):
431         print 'reading', f
432         s = open (f).read ()
433         return s
434
435
436 class GitFileCompareLink (FileCompareLink):
437     def get_cell (self, oldnew):
438         str = self.contents[oldnew]
439
440         # truncate long lines
441         str = '\n'.join ([l[:80] for l in str.split ('\n')])
442
443         
444         str = '<font size="-2"><pre>%s</pre></font>' % str
445         return str
446     
447     def calc_distance (self):
448         if self.contents[0] == self.contents[1]:
449             d = 0.0
450         else:
451             d = 1.0001 *options.threshold
452
453         return d
454         
455 class TextFileCompareLink (FileCompareLink):
456     def calc_distance (self):
457         import difflib
458         diff = difflib.unified_diff (self.contents[0].strip().split ('\n'),
459                                      self.contents[1].strip().split ('\n'),
460                                      fromfiledate = self.file_names[0],
461                                      tofiledate = self.file_names[1]
462                                      )
463         
464         self.diff_lines =  [l for l in diff]
465         self.diff_lines = self.diff_lines[2:]
466         
467         return math.sqrt (float (len ([l for l in self.diff_lines if l[0] in '-+'])))
468         
469     def get_cell (self, oldnew):
470         str = ''
471         if oldnew == 1:
472             str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
473         str = '<font size="-2"><pre>%s</pre></font>' % str
474         return str
475
476         
477 class ProfileFileLink (FileCompareLink):
478     def __init__ (self, f1, f2):
479         FileCompareLink.__init__ (self, f1, f2)
480         self.results = [{}, {}]
481     
482     def get_cell (self, oldnew):
483         str = ''
484         for k in ('time', 'cells'):
485             if oldnew==0:
486                 str += '%-8s: %d\n' %  (k, int (self.results[oldnew][k]))
487             else:
488                 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
489                                          self.get_ratio (k))
490
491         return '<pre>%s</pre>' % str
492             
493     def get_ratio (self, key):
494         (v1,v2) = (self.results[0].get (key, -1),
495                    self.results[1].get (key, -1))
496
497         if v1 <= 0 or v2 <= 0:
498             return 0.0
499
500         return (v1 - v2) / float (v1+v2)
501     
502     def calc_distance (self):
503         for oldnew in (0,1):
504             def note_info (m):
505                 self.results[oldnew][m.group(1)] = float (m.group (2))
506             
507             re.sub ('([a-z]+): ([-0-9.]+)\n',
508                     note_info, self.contents[oldnew])
509
510         dist = 0.0
511         factor = {'time': 2.0 ,
512                   'cells': 10.0,
513                   }
514         
515         for k in ('time', 'cells'):
516             dist += math.tan (self.get_ratio (k) /(0.5* math.pi)) * factor[k]  - 1
517
518         dist = min (dist, 100)
519         return dist
520
521     
522 class MidiFileLink (TextFileCompareLink):
523     def get_content (self, oldnew):
524         import midi
525         
526         data = FileCompareLink.get_content (self, oldnew)
527         midi = midi.parse (data)
528         tracks = midi[1]
529
530         str = ''
531         j = 0
532         for t in tracks:
533             str += 'track %d' % j
534             j += 1
535
536             for e in t:
537                 ev_str = repr (e)
538                 if re.search ('LilyPond [0-9.]+', ev_str):
539                     continue
540                 
541                 str += '  ev %s\n' % `e`
542         return str
543     
544
545
546 class SignatureFileLink (FileLink):
547     def __init__ (self, f1, f2 ):
548         FileLink.__init__ (self, f1, f2)
549         self.system_links = {}
550
551     def add_system_link (self, link, number):
552         self.system_links[number] = link
553
554     def calc_distance (self):
555         d = 0.0
556
557         orphan_distance = 0.0
558         for l in self.system_links.values ():
559             d = max (d, l.geometric_distance ())
560             orphan_distance += l.orphan_count ()
561             
562         return d + orphan_distance
563
564     def source_file (self):
565         for ext in ('.ly', '.ly.txt'):
566             if os.path.exists (self.base_names[1] + ext):
567                 return self.base_names[1] + ext
568         return ''
569     
570     def add_file_compare (self, f1, f2):
571         system_index = [] 
572
573         def note_system_index (m):
574             system_index.append (int (m.group (1)))
575             return ''
576         
577         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
578         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
579
580         self.base_names = (os.path.normpath (base1),
581                            os.path.normpath (base2))
582
583         def note_original (match):
584             hash_to_original_name[os.path.basename (self.base_names[1])] = match.group (1)
585             return ''
586         
587         ## ugh: drop the .ly.txt
588         for ext in ('.ly', '.ly.txt'):
589             try:
590                 re.sub (r'\\sourcefilename "([^"]+)"',
591                         note_original, open (base1 + ext).read ())
592             except IOError:
593                 pass
594                 
595         s1 = read_signature_file (f1)
596         s2 = read_signature_file (f2)
597
598         link = SystemLink (s1, s2)
599
600         self.add_system_link (link, system_index[0])
601
602     
603     def create_images (self, dest_dir):
604
605         files_created = [[], []]
606         for oldnew in (0, 1):
607             pat = self.base_names[oldnew] + '.eps'
608
609             for f in glob.glob (pat):
610                 infile = f
611                 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
612
613                 mkdir (os.path.split (outfile)[0])
614                 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
615                        ' -r101 '
616                        ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
617                        ' %(infile)s  -c quit '  % locals ())
618
619                 files_created[oldnew].append (outfile)
620                 system (cmd)
621
622         return files_created
623     
624     def link_files_for_html (self, dest_dir):
625         FileLink.link_files_for_html (self, dest_dir)
626         to_compare = [[], []]
627
628         exts = []
629         if options.create_images:
630             to_compare = self.create_images (dest_dir)
631         else:
632             exts += ['.png', '-page*png']
633         
634         for ext in exts:            
635             for oldnew in (0,1):
636                 for f in glob.glob (self.base_names[oldnew] + ext):
637                     dst = dest_dir + '/' + f
638                     link_file (f, dst)
639
640                     if f.endswith ('.png'):
641                         to_compare[oldnew].append (f)
642                         
643         if options.compare_images:                
644             for (old, new) in zip (to_compare[0], to_compare[1]):
645                 compare_png_images (old, new, dest_dir)
646
647
648     def get_cell (self, oldnew):
649         def img_cell (ly, img, name):
650             if not name:
651                 name = 'source'
652             else:
653                 name = '<tt>%s</tt>' % name
654                 
655             return '''
656 <a href="%(img)s">
657 <img src="%(img)s" style="border-style: none; max-width: 500px;">
658 </a><br>
659 ''' % locals ()
660         def multi_img_cell (ly, imgs, name):
661             if not name:
662                 name = 'source'
663             else:
664                 name = '<tt>%s</tt>' % name
665
666             imgs_str = '\n'.join (['''<a href="%s">
667 <img src="%s" style="border-style: none; max-width: 500px;">
668 </a><br>''' % (img, img) 
669                                   for img in imgs])
670
671
672             return '''
673 %(imgs_str)s
674 ''' % locals ()
675
676
677
678         def cell (base, name):
679             pat = base + '-page*.png'
680             pages = glob.glob (pat)
681
682             if pages:
683                 return multi_img_cell (base + '.ly', sorted (pages), name)
684             else:
685                 return img_cell (base + '.ly', base + '.png', name)
686
687
688
689         str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())  
690         if options.compare_images and oldnew == 1:
691             str = str.replace ('.png', '.compare.jpeg')
692             
693         return str
694
695
696     def get_distance_details (self):
697         systems = self.system_links.items ()
698         systems.sort ()
699
700         html = ""
701         for (c, link) in systems:
702             e = '<td>%d</td>' % c
703             for d in link.distance ():
704                 e += '<td>%f</td>' % d
705             
706             e = '<tr>%s</tr>' % e
707
708             html += e
709
710             e = '<td>%d</td>' % c
711             for s in (link.output_expression_details_string (),
712                       link.orphan_details_string (),
713                       link.geo_details_string ()):
714                 e += "<td>%s</td>" % s
715
716             
717             e = '<tr>%s</tr>' % e
718             html += e
719             
720         original = self.name ()
721         html = '''<html>
722 <head>
723 <title>comparison details for %(original)s</title>
724 </head>
725 <body>
726 <table border=1>
727 <tr>
728 <th>system</th>
729 <th>output</th>
730 <th>orphan</th>
731 <th>geo</th>
732 </tr>
733
734 %(html)s
735 </table>
736
737 </body>
738 </html>
739 ''' % locals ()
740         return html
741
742
743 ################################################################
744 # Files/directories
745
746 import glob
747 import re
748
749 def compare_signature_files (f1, f2):
750     s1 = read_signature_file (f1)
751     s2 = read_signature_file (f2)
752     
753     return SystemLink (s1, s2).distance ()
754
755 def paired_files (dir1, dir2, pattern):
756     """
757     Search DIR1 and DIR2 for PATTERN.
758
759     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
760
761     """
762
763     files = []
764     for d in (dir1,dir2):
765         found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
766         found = dict ((f, 1) for f in found)
767         files.append (found)
768         
769     pairs = []
770     missing = []
771     for f in files[0].keys ():
772         try:
773             files[1].pop (f)
774             pairs.append (f)
775         except KeyError:
776             missing.append (f)
777
778     return (pairs, files[1].keys (), missing)
779     
780 class ComparisonData:
781     def __init__ (self):
782         self.result_dict = {}
783         self.missing = []
784         self.added = []
785         self.file_links = {}
786
787     def compare_trees (self, dir1, dir2):
788         self.compare_directories (dir1, dir2)
789         
790         (root, dirs, files) = os.walk (dir1).next ()
791         for d in dirs:
792             d1 = os.path.join (dir1, d)
793             d2 = os.path.join (dir2, d)
794
795             if os.path.islink (d1) or os.path.islink (d2):
796                 continue
797             
798             if os.path.isdir (d2):
799                 self.compare_trees (d1, d2)
800     
801     def compare_directories (self, dir1, dir2):
802         for ext in ['signature', 'midi', 'log', 'profile', 'gittxt']:
803             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
804
805             self.missing += [(dir1, m) for m in m1] 
806             self.added += [(dir2, m) for m in m2] 
807
808             for p in paired:
809                 if (options.max_count
810                     and len (self.file_links) > options.max_count):
811                     continue
812                 
813                 f2 = dir2 +  '/' + p
814                 f1 = dir1 +  '/' + p
815                 self.compare_files (f1, f2)
816
817     def compare_files (self, f1, f2):
818         if f1.endswith ('signature'):
819             self.compare_signature_files (f1, f2)
820         else:
821             ext = os.path.splitext (f1)[1]
822             klasses = {
823                 '.midi': MidiFileLink,
824                 '.log' : TextFileCompareLink,
825                 '.profile': ProfileFileLink,
826                 '.gittxt': GitFileCompareLink, 
827                 }
828             
829             if klasses.has_key (ext):
830                 self.compare_general_files (klasses[ext], f1, f2)
831
832     def compare_general_files (self, klass, f1, f2):
833         name = os.path.split (f1)[1]
834
835         file_link = klass (f1, f2)
836         self.file_links[name] = file_link
837         
838     def compare_signature_files (self, f1, f2):
839         name = os.path.split (f1)[1]
840         name = re.sub ('-[0-9]+.signature', '', name)
841         
842         file_link = None
843         try:
844             file_link = self.file_links[name]
845         except KeyError:
846             generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
847             generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
848             file_link = SignatureFileLink (generic_f1, generic_f2)
849             self.file_links[name] = file_link
850
851         file_link.add_file_compare (f1, f2)
852
853     def write_changed (self, dest_dir, threshold):
854         (changed, below, unchanged) = self.thresholded_results (threshold)
855
856         str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
857                         for link in changed])
858         fn = dest_dir + '/changed.txt'
859         
860         open_write_file (fn).write (str)
861                 
862     def thresholded_results (self, threshold):
863         ## todo: support more scores.
864         results = [(link.distance(), link)
865                    for link in self.file_links.values ()]
866         results.sort ()
867         results.reverse ()
868
869         unchanged = [r for (d,r) in results if d == 0.0]
870         below = [r for (d,r) in results if threshold >= d > 0.0]
871         changed = [r for (d,r) in results if d > threshold]
872
873         return (changed, below, unchanged)
874                 
875     def write_text_result_page (self, filename, threshold):
876         out = None
877         if filename == '':
878             out = sys.stdout
879         else:
880             print 'writing "%s"' % filename
881             out = open_write_file (filename)
882
883         (changed, below, unchanged) = self.thresholded_results (threshold)
884
885         
886         for link in changed:
887             out.write (link.text_record_string ())
888
889         out.write ('\n\n')
890         out.write ('%d below threshold\n' % len (below))
891         out.write ('%d unchanged\n' % len (unchanged))
892         
893     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
894         self.write_text_result_page (dest_dir + '/index.txt', threshold)
895         
896     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
897         dir1 = dir1.replace ('//', '/')
898         dir2 = dir2.replace ('//', '/')
899
900         (changed, below, unchanged) = self.thresholded_results (threshold)
901
902
903         html = ''
904         old_prefix = os.path.split (dir1)[1]
905         for link in changed:
906             html += link.html_record_string (dest_dir)
907
908
909         short_dir1 = shorten_string (dir1)
910         short_dir2 = shorten_string (dir2)
911         html = '''<html>
912 <table rules="rows" border bordercolor="blue">
913 <tr>
914 <th>distance</th>
915 <th>%(short_dir1)s</th>
916 <th>%(short_dir2)s</th>
917 </tr>
918 %(html)s
919 </table>
920 </html>''' % locals()
921
922         html += ('<p>')
923         below_count = len (below)
924
925         if below_count:
926             html += ('<p>%d below threshold</p>' % below_count)
927             
928         html += ('<p>%d unchanged</p>' % len (unchanged))
929
930         dest_file = dest_dir + '/index.html'
931         open_write_file (dest_file).write (html)
932
933
934         for link in changed:
935             link.link_files_for_html (dest_dir)
936         
937
938     def print_results (self, threshold):
939         self.write_text_result_page ('', threshold)
940
941 def compare_trees (dir1, dir2, dest_dir, threshold):
942     data = ComparisonData ()
943     data.compare_trees (dir1, dir2)
944     data.print_results (threshold)
945
946     if os.path.isdir (dest_dir):
947         system ('rm -rf %s '% dest_dir)
948
949     data.write_changed (dest_dir, threshold)
950     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
951     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
952     
953 ################################################################
954 # TESTING
955
956 def mkdir (x):
957     if not os.path.isdir (x):
958         print 'mkdir', x
959         os.makedirs (x)
960
961 def link_file (x, y):
962     mkdir (os.path.split (y)[0])
963     try:
964         print x, '->', y
965         os.link (x, y)
966     except OSError, z:
967         print 'OSError', x, y, z
968         raise OSError
969     
970 def open_write_file (x):
971     d = os.path.split (x)[0]
972     mkdir (d)
973     return open (x, 'w')
974
975
976 def system (x):
977     
978     print 'invoking', x
979     stat = os.system (x)
980     assert stat == 0
981
982
983 def test_paired_files ():
984     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
985                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
986                   
987     
988 def test_compare_trees ():
989     system ('rm -rf dir1 dir2')
990     system ('mkdir dir1 dir2')
991     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
992     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
993     system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
994     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
995     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
996     system ('cp 19-1.signature 19.sub-1.signature')
997     system ('cp 19.ly 19.sub.ly')
998     system ('cp 19.profile 19.sub.profile')
999     system ('cp 19.log 19.sub.log')
1000     system ('cp 19.png 19.sub.png')
1001     system ('cp 19.eps 19.sub.eps')
1002
1003     system ('cp 20multipage* dir1')
1004     system ('cp 20multipage* dir2')
1005     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
1006
1007     
1008     system ('mkdir -p dir1/subdir/ dir2/subdir/')
1009     system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
1010     system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
1011     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1012     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1013     system ('echo HEAD is 1 > dir1/tree.gittxt')
1014     system ('echo HEAD is 2 > dir2/tree.gittxt')
1015
1016     ## introduce differences
1017     system ('cp 19-1.signature dir2/20-1.signature')
1018     system ('cp 19.profile dir2/20.profile')
1019     system ('cp 19.png dir2/20.png')
1020     system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1021     system ('cp 20-1.signature dir2/subdir/19.sub-1.signature')
1022     system ('cp 20.png dir2/subdir/19.sub.png')
1023     system ("sed 's/: /: 1/g'  20.profile > dir2/subdir/19.sub.profile")
1024
1025     ## radical diffs.
1026     system ('cp 19-1.signature dir2/20grob-1.signature')
1027     system ('cp 19-1.signature dir2/20grob-2.signature')
1028     system ('cp 19multipage.midi dir1/midi-differ.midi')
1029     system ('cp 20multipage.midi dir2/midi-differ.midi')
1030     system ('cp 19multipage.log dir1/log-differ.log')
1031     system ('cp 19multipage.log dir2/log-differ.log &&  echo different >> dir2/log-differ.log &&  echo different >> dir2/log-differ.log')
1032
1033     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', options.threshold)
1034
1035
1036 def test_basic_compare ():
1037     ly_template = r"""
1038
1039 \version "2.10.0"
1040 #(define default-toplevel-book-handler
1041   print-book-with-defaults-as-systems )
1042
1043 #(ly:set-option (quote no-point-and-click))
1044
1045 \sourcefilename "my-source.ly"
1046  
1047 %(papermod)s
1048 \header { tagline = ##f }
1049 \score {
1050 <<
1051 \new Staff \relative c {
1052   c4^"%(userstring)s" %(extragrob)s
1053   }
1054 \new Staff \relative c {
1055   c4^"%(userstring)s" %(extragrob)s
1056   }
1057 >>
1058 \layout{}
1059 }
1060
1061 """
1062
1063     dicts = [{ 'papermod' : '',
1064                'name' : '20',
1065                'extragrob': '',
1066                'userstring': 'test' },
1067              { 'papermod' : '#(set-global-staff-size 19.5)',
1068                'name' : '19',
1069                'extragrob': '',
1070                'userstring': 'test' },
1071              { 'papermod' : '',
1072                'name' : '20expr',
1073                'extragrob': '',
1074                'userstring': 'blabla' },
1075              { 'papermod' : '',
1076                'name' : '20grob',
1077                'extragrob': 'r2. \\break c1',
1078                'userstring': 'test' },
1079              ]
1080
1081     for d in dicts:
1082         open (d['name'] + '.ly','w').write (ly_template % d)
1083         
1084     names = [d['name'] for d in dicts]
1085
1086     system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1087     
1088
1089     multipage_str = r'''
1090     #(set-default-paper-size "a6")
1091     \score {
1092       \relative {c1 \pageBreak c1 }
1093       \layout {}
1094       \midi {}
1095     }
1096     '''
1097
1098     open ('20multipage.ly', 'w').write (multipage_str.replace ('c1', 'd1'))
1099     open ('19multipage.ly', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1100     system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1101  
1102     test_compare_signatures (names)
1103     
1104 def test_compare_signatures (names, timing=False):
1105
1106     import time
1107
1108     times = 1
1109     if timing:
1110         times = 100
1111
1112     t0 = time.clock ()
1113
1114     count = 0
1115     for t in range (0, times):
1116         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1117         count += 1
1118
1119     if timing:
1120         print 'elapsed', (time.clock() - t0)/count
1121
1122
1123     t0 = time.clock ()
1124     count = 0
1125     combinations = {}
1126     for (n1, s1) in sigs.items():
1127         for (n2, s2) in sigs.items():
1128             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1129             count += 1
1130
1131     if timing:
1132         print 'elapsed', (time.clock() - t0)/count
1133
1134     results = combinations.items ()
1135     results.sort ()
1136     for k,v in results:
1137         print '%-20s' % k, v
1138
1139     assert combinations['20-20'] == (0.0,0.0,0.0)
1140     assert combinations['20-20expr'][0] > 0.0
1141     assert combinations['20-19'][2] < 10.0
1142     assert combinations['20-19'][2] > 0.0
1143
1144
1145 def run_tests ():
1146     dir = 'test-output-distance'
1147
1148     do_clean = not os.path.exists (dir)
1149
1150     print 'test results in ', dir
1151     if do_clean:
1152         system ('rm -rf ' + dir)
1153         system ('mkdir ' + dir)
1154         
1155     os.chdir (dir)
1156     if do_clean:
1157         test_basic_compare ()
1158         
1159     test_compare_trees ()
1160     
1161 ################################################################
1162 #
1163
1164 def main ():
1165     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1166     p.usage = 'output-distance.py [options] tree1 tree2'
1167     
1168     p.add_option ('', '--test-self',
1169                   dest="run_test",
1170                   action="store_true",
1171                   help='run test method')
1172     
1173     p.add_option ('--max-count',
1174                   dest="max_count",
1175                   metavar="COUNT",
1176                   type="int",
1177                   default=0, 
1178                   action="store",
1179                   help='only analyze COUNT signature pairs')
1180
1181     p.add_option ('', '--threshold',
1182                   dest="threshold",
1183                   default=0.3,
1184                   action="store",
1185                   type="float",
1186                   help='threshold for geometric distance')
1187
1188     p.add_option ('--no-compare-images',
1189                   dest="compare_images",
1190                   default=True,
1191                   action="store_false",
1192                   help="Don't run graphical comparisons")
1193
1194     p.add_option ('--create-images',
1195                   dest="create_images",
1196                   default=False,
1197                   action="store_true",
1198                   help="Create PNGs from EPSes")
1199
1200     p.add_option ('-o', '--output-dir',
1201                   dest="output_dir",
1202                   default=None,
1203                   action="store",
1204                   type="string",
1205                   help='where to put the test results [tree2/compare-tree1tree2]')
1206
1207     global options
1208     (options, a) = p.parse_args ()
1209
1210     if options.run_test:
1211         run_tests ()
1212         sys.exit (0)
1213
1214     if len (a) != 2:
1215         p.print_usage()
1216         sys.exit (2)
1217
1218     name = options.output_dir
1219     if not name:
1220         name = a[0].replace ('/', '')
1221         name = os.path.join (a[1], 'compare-' + shorten_string (name))
1222     
1223     compare_trees (a[0], a[1], name, options.threshold)
1224
1225 if __name__ == '__main__':
1226     main()
1227