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