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