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