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