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