]> git.donarmstrong.com Git - lilypond.git/blob - scripts/build/output-distance.py
Regtest script: When filtering through js, don't filter out header rows.
[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, 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 -dissimilarity-threshold 1 %(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 -compose atop -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 (b1[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 (b1[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 scheme_float (s) :
319     if 'nan' not in s :
320         return float(s)
321     return float(s.split('.')[0])
322
323 def read_signature_file (name):
324     print 'reading', name
325
326     entries = open (name).read ().split ('\n')
327     def string_to_tup (s):
328         return tuple (map (scheme_float, s.split (' ')))
329
330     def string_to_entry (s):
331         fields = s.split('@')
332         fields[2] = string_to_tup (fields[2])
333         fields[3] = string_to_tup (fields[3])
334
335         return tuple (fields)
336
337     entries = [string_to_entry (e) for e in entries
338                if e and not e.startswith ('#')]
339
340     grob_sigs = [GrobSignature (e) for e in entries]
341     sig = SystemSignature (grob_sigs)
342     return sig
343
344
345 ################################################################
346 # different systems of a .ly file.
347
348 hash_to_original_name = {}
349
350 class FileLink:
351     def __init__ (self, f1, f2):
352         self._distance = None
353         self.file_names = (f1, f2)
354
355     def text_record_string (self):
356         return '%-30f %-20s\n' % (self.distance (),
357                                   self.name ()
358                                   + os.path.splitext (self.file_names[1])[1]
359                                   )
360
361     def calc_distance (self):
362         return 0.0
363
364     def distance (self):
365         if self._distance == None:
366            self._distance = self.calc_distance ()
367
368         return self._distance
369
370     def source_file (self):
371         for ext in ('.ly', '.ly.txt'):
372             base = os.path.splitext (self.file_names[1])[0]
373             f = base + ext
374             if os.path.exists (f):
375                 return f
376
377         return ''
378
379     def name (self):
380         base = os.path.basename (self.file_names[1])
381         base = os.path.splitext (base)[0]
382         base = hash_to_original_name.get (base, base)
383         base = os.path.splitext (base)[0]
384         return base
385
386     def extension (self):
387         return os.path.splitext (self.file_names[1])[1]
388
389     def link_files_for_html (self, dest_dir):
390         for f in self.file_names:
391             link_file (f, os.path.join (dest_dir, f))
392
393     def get_distance_details (self):
394         return ''
395
396     def get_cell (self, oldnew):
397         return ''
398
399     def get_file (self, oldnew):
400         return self.file_names[oldnew]
401
402     def html_record_string (self, dest_dir):
403         dist = self.distance()
404
405         details = self.get_distance_details ()
406         if details:
407             details_base = os.path.splitext (self.file_names[1])[0]
408             details_base += '.details.html'
409             fn = dest_dir + '/'  + details_base
410             open_write_file (fn).write (details)
411
412             details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
413
414         cell1 = self.get_cell (0)
415         cell2 = self.get_cell (1)
416
417         name = self.name () + self.extension ()
418         file1 = self.get_file (0)
419         file2 = self.get_file (1)
420
421         return '''<tr>
422 <td>
423 %(dist)f
424 %(details)s
425 </td>
426 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
427 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
428 </tr>''' % locals ()
429
430
431 class FileCompareLink (FileLink):
432     def __init__ (self, f1, f2):
433         FileLink.__init__ (self, f1, f2)
434         self.contents = (self.get_content (self.file_names[0]),
435                          self.get_content (self.file_names[1]))
436
437
438     def calc_distance (self):
439         ## todo: could use import MIDI to pinpoint
440         ## what & where changed.
441
442         if self.contents[0] == self.contents[1]:
443             return 0.0
444         else:
445             return 100.0;
446
447     def get_content (self, f):
448         print 'reading', f
449         s = open (f).read ()
450         return s
451
452
453 class GitFileCompareLink (FileCompareLink):
454     def get_cell (self, oldnew):
455         str = self.contents[oldnew]
456
457         # truncate long lines
458         str = '\n'.join ([l[:80] for l in str.split ('\n')])
459
460
461         str = '<font size="-2"><pre>%s</pre></font>' % cgi.escape (str)
462         return str
463
464     def calc_distance (self):
465         if self.contents[0] == self.contents[1]:
466             d = 0.0
467         else:
468             d = 1.0001 *options.threshold
469
470         return d
471
472
473 snippet_fn_re = re.compile (r"`\./([0-9a-f]{2}/lily-[0-9a-f]{8}).eps'");
474 class TextFileCompareLink (FileCompareLink):
475     def calc_distance (self):
476         import difflib
477         # Extract the old and the new hashed snippet names from the log file
478         # and replace the old by the new, so file name changes don't show
479         # up as log differences...
480         cont0 = self.contents[0].strip();
481         cont1 = self.contents[1].strip();
482         m0 = re.search (snippet_fn_re, cont0);
483         m1 = re.search (snippet_fn_re, cont1);
484         if (m0 and m1 and (m0.group(1) != m1.group(1))):
485             cont0 = cont0.replace (m0.group(1), m1.group(1));
486
487         diff = difflib.unified_diff (cont0.split ('\n'),
488                                      cont1.split ('\n'),
489                                      fromfiledate = self.file_names[0],
490                                      tofiledate = self.file_names[1]
491                                      )
492
493         self.diff_lines =  [l for l in diff]
494         self.diff_lines = self.diff_lines[2:]
495
496         return math.sqrt (float (len ([l for l in self.diff_lines if l[0] in '-+'])))
497
498     def get_cell (self, oldnew):
499         str = ''
500         if oldnew == 1:
501             str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
502         str = '<font size="-2"><pre>%s</pre></font>' % str
503         return str
504
505 class LogFileCompareLink (TextFileCompareLink):
506   def get_content (self, f):
507       c = TextFileCompareLink.get_content (self, f)
508       c = re.sub ("\nProcessing `[^\n]+'\n", '', c)
509       return c
510
511 class ProfileFileLink (FileCompareLink):
512     def __init__ (self, f1, f2):
513         FileCompareLink.__init__ (self, f1, f2)
514         self.results = [{}, {}]
515
516     def get_cell (self, oldnew):
517         str = ''
518         for k in ('time', 'cells'):
519             if oldnew==0:
520                 str += '%-8s: %d\n' %  (k, int (self.results[oldnew][k]))
521             else:
522                 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
523                                                 self.get_ratio (k))
524
525         return '<pre>%s</pre>' % str
526
527     def get_ratio (self, key):
528         (v1,v2) = (self.results[0].get (key, -1),
529                    self.results[1].get (key, -1))
530
531         if v1 <= 0 or v2 <= 0:
532             return 0.0
533
534         return (v1 - v2) / float (v1+v2)
535
536     def calc_distance (self):
537         for oldnew in (0,1):
538             def note_info (m):
539                 self.results[oldnew][m.group(1)] = float (m.group (2))
540
541             re.sub ('([a-z]+): ([-0-9.]+)\n',
542                     note_info, self.contents[oldnew])
543
544         dist = 0.0
545         factor = {
546             'time': 0.1,
547             'cells': 5.0,
548             }
549
550         for k in ('time', 'cells'):
551             real_val = math.tan (self.get_ratio (k) * 0.5 * math.pi)
552             dist += math.exp (math.fabs (real_val) * factor[k])  - 1
553
554         dist = min (dist, 100)
555         return dist
556
557
558 class MidiFileLink (TextFileCompareLink):
559     def get_content (self, oldnew):
560         import midi
561
562         data = FileCompareLink.get_content (self, oldnew)
563         midi = midi.parse (data)
564         tracks = midi[1]
565
566         str = ''
567         j = 0
568         for t in tracks:
569             str += 'track %d' % j
570             j += 1
571
572             for e in t:
573                 ev_str = repr (e)
574                 if re.search ('LilyPond [0-9.]+', ev_str):
575                     continue
576
577                 str += '  ev %s\n' % `e`
578         return str
579
580
581
582 class SignatureFileLink (FileLink):
583     def __init__ (self, f1, f2 ):
584         FileLink.__init__ (self, f1, f2)
585         self.system_links = {}
586
587     def add_system_link (self, link, number):
588         self.system_links[number] = link
589
590     def calc_distance (self):
591         d = 0.0
592
593         orphan_distance = 0.0
594         for l in self.system_links.values ():
595             d = max (d, l.geometric_distance ())
596             orphan_distance += l.orphan_count ()
597
598         return d + orphan_distance
599
600     def add_file_compare (self, f1, f2):
601         system_index = []
602
603         def note_system_index (m):
604             system_index.append (int (m.group (1)))
605             return ''
606
607         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
608         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
609
610         self.base_names = (os.path.normpath (base1),
611                            os.path.normpath (base2))
612
613         s1 = read_signature_file (f1)
614         s2 = read_signature_file (f2)
615
616         link = SystemLink (s1, s2)
617
618         self.add_system_link (link, system_index[0])
619
620
621     def create_images (self, dest_dir):
622
623         files_created = [[], []]
624         for oldnew in (0, 1):
625             pat = self.base_names[oldnew] + '.eps'
626
627             for f in glob.glob (pat):
628                 infile = f
629                 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
630                 data_option = ''
631                 if options.local_data_dir:
632                     data_option = ('-slilypond-datadir=%s/share/lilypond/current '
633                                    % os.path.dirname(infile))
634
635                 mkdir (os.path.split (outfile)[0])
636                 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
637                        ' %(data_option)s '
638                        ' -r101 '
639                        ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
640                        ' %(infile)s  -c quit ') % locals ()
641
642                 files_created[oldnew].append (outfile)
643                 system (cmd)
644
645         return files_created
646
647     def link_files_for_html (self, dest_dir):
648         FileLink.link_files_for_html (self, dest_dir)
649         to_compare = [[], []]
650
651         exts = []
652         if options.create_images:
653             to_compare = self.create_images (dest_dir)
654         else:
655             exts += ['.png', '-page*png']
656
657         for ext in exts:
658             for oldnew in (0,1):
659                 for f in glob.glob (self.base_names[oldnew] + ext):
660                     dst = dest_dir + '/' + f
661                     link_file (f, dst)
662
663                     if f.endswith ('.png'):
664                         to_compare[oldnew].append (f)
665
666         if options.compare_images:
667             for (old, new) in zip (to_compare[0], to_compare[1]):
668                 compare_png_images (old, new, dest_dir)
669
670
671     def get_cell (self, oldnew):
672         def img_cell (ly, img, name):
673             if not name:
674                 name = 'source'
675             else:
676                 name = '<tt>%s</tt>' % name
677
678             return '''
679 <a href="%(img)s">
680 <img src="%(img)s" style="border-style: none; max-width: 500px;">
681 </a><br>
682 ''' % locals ()
683         def multi_img_cell (ly, imgs, name):
684             if not name:
685                 name = 'source'
686             else:
687                 name = '<tt>%s</tt>' % name
688
689             imgs_str = '\n'.join (['''<a href="%s">
690 <img src="%s" style="border-style: none; max-width: 500px;">
691 </a><br>''' % (img, img)
692                                   for img in imgs])
693
694
695             return '''
696 %(imgs_str)s
697 ''' % locals ()
698
699
700
701         def cell (base, name):
702             pat = base + '-page*.png'
703             pages = glob.glob (pat)
704
705             if pages:
706                 return multi_img_cell (base + '.ly', sorted (pages), name)
707             else:
708                 return img_cell (base + '.ly', base + '.png', name)
709
710
711
712         str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())
713         if options.compare_images and oldnew == 1:
714             str = str.replace ('.png', '.compare.jpeg')
715
716         return str
717
718
719     def get_distance_details (self):
720         systems = self.system_links.items ()
721         systems.sort ()
722
723         html = ""
724         for (c, link) in systems:
725             e = '<td>%d</td>' % c
726             for d in link.distance ():
727                 e += '<td>%f</td>' % d
728
729             e = '<tr>%s</tr>' % e
730
731             html += e
732
733             e = '<td>%d</td>' % c
734             for s in (link.output_expression_details_string (),
735                       link.orphan_details_string (),
736                       link.geo_details_string ()):
737                 e += "<td>%s</td>" % s
738
739
740             e = '<tr>%s</tr>' % e
741             html += e
742
743         original = self.name ()
744         html = '''<html>
745 <head>
746 <title>comparison details for %(original)s</title>
747 </head>
748 <body>
749 <table border=1>
750 <tr>
751 <th>system</th>
752 <th>output</th>
753 <th>orphan</th>
754 <th>geo</th>
755 </tr>
756
757 %(html)s
758 </table>
759
760 </body>
761 </html>
762 ''' % locals ()
763         return html
764
765
766 ################################################################
767 # Files/directories
768
769 import glob
770
771 def compare_signature_files (f1, f2):
772     s1 = read_signature_file (f1)
773     s2 = read_signature_file (f2)
774
775     return SystemLink (s1, s2).distance ()
776
777 def paired_files (dir1, dir2, pattern):
778     """
779     Search DIR1 and DIR2 for PATTERN.
780
781     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
782
783     """
784
785     files = []
786     for d in (dir1,dir2):
787         found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
788         found = dict ((f, 1) for f in found)
789         files.append (found)
790
791     pairs = []
792     missing = []
793     for f in files[0]:
794         try:
795             files[1].pop (f)
796             pairs.append (f)
797         except KeyError:
798             missing.append (f)
799
800     return (pairs, files[1].keys (), missing)
801
802 class ComparisonData:
803     def __init__ (self):
804         self.result_dict = {}
805         self.missing = []
806         self.added = []
807         self.file_links = {}
808
809     def read_sources (self):
810
811         ## ugh: drop the .ly.txt
812         for (key, val) in self.file_links.items ():
813
814             def note_original (match, ln=val):
815                 key = ln.name ()
816                 hash_to_original_name[key] = match.group (1)
817                 return ''
818
819             sf = val.source_file ()
820             if sf:
821                 re.sub (r'\\sourcefilename "([^"]+)"',
822                         note_original, open (sf).read ())
823             else:
824                 print 'no source for', val
825
826     def compare_trees (self, dir1, dir2):
827         self.compare_directories (dir1, dir2)
828
829         try:
830             (root, dirs, files) = os.walk (dir1).next ()
831         except StopIteration:
832             if dir1.endswith("-baseline"):
833                 sys.stderr.write("Failed to walk through %s. This can be caused by forgetting to run make test-baseline.\n" % dir1)
834             else:
835                 sys.stderr.write("Failed to walk through %s; please check it exists.\n" % dir1)
836             sys.exit(1)
837
838         for d in dirs:
839             d1 = os.path.join (dir1, d)
840             d2 = os.path.join (dir2, d)
841
842             if os.path.islink (d1) or os.path.islink (d2):
843                 continue
844
845             if os.path.isdir (d2):
846                 self.compare_trees (d1, d2)
847
848     def compare_directories (self, dir1, dir2):
849         for ext in ['signature',
850                     'midi',
851                     'log',
852                     'profile',
853                     'gittxt']:
854             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
855
856             self.missing += [(dir1, m) for m in m1]
857             self.added += [(dir2, m) for m in m2]
858
859             for p in paired:
860                 if (options.max_count
861                     and len (self.file_links) > options.max_count):
862                     continue
863
864                 f2 = dir2 +  '/' + p
865                 f1 = dir1 +  '/' + p
866                 self.compare_files (f1, f2)
867
868     def compare_files (self, f1, f2):
869         if f1.endswith ('signature'):
870             self.compare_signature_files (f1, f2)
871         else:
872             ext = os.path.splitext (f1)[1]
873             klasses = {
874                 '.midi': MidiFileLink,
875                 '.log' : LogFileCompareLink,
876                 '.profile': ProfileFileLink,
877                 '.gittxt': GitFileCompareLink,
878                 }
879
880             if klasses.has_key (ext):
881                 self.compare_general_files (klasses[ext], f1, f2)
882
883     def compare_general_files (self, klass, f1, f2):
884         name = os.path.split (f1)[1]
885
886         file_link = klass (f1, f2)
887         self.file_links[name] = file_link
888
889     def compare_signature_files (self, f1, f2):
890         name = os.path.split (f1)[1]
891         name = re.sub ('-[0-9]+.signature', '', name)
892
893         file_link = None
894         try:
895             file_link = self.file_links[name]
896         except KeyError:
897             generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
898             generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
899             file_link = SignatureFileLink (generic_f1, generic_f2)
900             self.file_links[name] = file_link
901
902         file_link.add_file_compare (f1, f2)
903
904     def write_changed (self, dest_dir, threshold):
905         (changed, below, unchanged) = self.thresholded_results (threshold)
906
907         str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
908                         for link in changed])
909         fn = dest_dir + '/changed.txt'
910
911         open_write_file (fn).write (str)
912
913     def thresholded_results (self, threshold):
914         ## todo: support more scores.
915         results = [(link.distance(), link)
916                    for link in self.file_links.values ()]
917         results.sort ()
918         results.reverse ()
919
920         unchanged = [r for (d,r) in results if d == 0.0]
921         below = [r for (d,r) in results if threshold >= d > 0.0]
922         changed = [r for (d,r) in results if d > threshold]
923
924         return (changed, below, unchanged)
925
926     def write_text_result_page (self, filename, threshold):
927         out = None
928         if filename == '':
929             out = sys.stdout
930         else:
931             print 'writing "%s"' % filename
932             out = open_write_file (filename)
933
934         (changed, below, unchanged) = self.thresholded_results (threshold)
935
936
937         for link in changed:
938             out.write (link.text_record_string ())
939
940         out.write ('\n\n')
941         out.write ('%d below threshold\n' % len (below))
942         out.write ('%d unchanged\n' % len (unchanged))
943
944     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
945         self.write_text_result_page (dest_dir + '/index.txt', threshold)
946
947     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
948         dir1 = dir1.replace ('//', '/')
949         dir2 = dir2.replace ('//', '/')
950
951         (changed, below, unchanged) = self.thresholded_results (threshold)
952
953
954         table_rows = ''
955         old_prefix = os.path.split (dir1)[1]
956         for link in changed:
957             table_rows += link.html_record_string (dest_dir)
958
959
960         short_dir1 = shorten_string (dir1)
961         short_dir2 = shorten_string (dir2)
962
963         summary = ''
964         below_count = len (below)
965
966         if below_count:
967             summary += '<p>%d below threshold</p>' % below_count
968
969         summary += '<p>%d unchanged</p>' % len (unchanged)
970
971         html = '''<html>
972 <head>
973 <title>LilyPond regression test results</title>
974 <script language="javascript" type="text/javascript">
975 // <![CDATA[
976     var rows = document.getElementsByTagName("tr");
977     function showOnlyMatchingRows(substring) {
978         var rowcount = rows.length;
979         for (var i = 0; i < rowcount; i++) {
980             row = rows[i];
981             html = row.innerHTML;
982             row.style.display =
983                 ((html.indexOf('>distance<') != -1) ||
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