]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
(ComparisonData.create_html_result_page): new routine: summarise
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4
5 import safeeval
6
7
8 X_AXIS = 0
9 Y_AXIS = 1
10 INFTY = 1e6
11
12 OUTPUT_EXPRESSION_PENALTY = 100
13 ORPHAN_GROB_PENALTY = 1000
14
15 def max_distance (x1, x2):
16     dist = 0.0
17
18     for (p,q) in zip (x1, x2):
19         dist = max (abs (p-q), dist)
20         
21     return dist
22
23
24 empty_interval = (INFTY, -INFTY)
25 empty_bbox = (empty_interval, empty_interval)
26
27 def interval_length (i):
28     return max (i[1]-i[0], 0) 
29     
30 def interval_union (i1, i2):
31     return (min (i1[0], i2[0]),
32             max (i1[1], i2[1]))
33
34 def interval_intersect (i1, i2):
35     return (max (i1[0], i2[0]),
36             min (i1[1], i2[1]))
37
38 def bbox_union (b1, b2):
39     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
40             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
41             
42 def bbox_intersection (b1, b2):
43     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
44             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
45
46 def bbox_area (b):
47     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
48
49 def bbox_diameter (b):
50     return max (interval_length (b[X_AXIS]),
51                 interval_length (b[Y_AXIS]))
52                 
53
54 def difference_area (a, b):
55     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
56
57 class GrobSignature:
58     def __init__ (self, exp_list):
59         (self.name, self.origin, bbox_x,
60          bbox_y, self.output_expression) = tuple (exp_list)
61         
62         self.bbox = (bbox_x, bbox_y)
63         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
64
65     def __repr__ (self):
66         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
67                                                  self.bbox[0][0],
68                                                  self.bbox[0][1],
69                                                  self.bbox[1][0],
70                                                  self.bbox[1][1])
71                                                  
72     def axis_centroid (self, axis):
73         return apply (sum, self.bbox[axis])  / 2 
74     
75     def centroid_distance (self, other, scale):
76         return max_distance (self.centroid, other.centroid) / scale 
77         
78     def bbox_distance (self, other):
79         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
80
81         if divisor:
82             return (difference_area (self.bbox, other.bbox) +
83                     difference_area (other.bbox, self.bbox)) / divisor
84         else:
85             return 0.0
86         
87     def expression_distance (self, other):
88         if self.output_expression == other.output_expression:
89             return 0.0
90         else:
91             return OUTPUT_EXPRESSION_PENALTY
92
93     def distance(self, other, max_distance):
94         return (self.expression_distance (other)
95                 + self.centroid_distance (other, max_distance)
96                 + self.bbox_distance (other))
97             
98 class SystemSignature:
99     def __init__ (self, grob_sigs):
100         d = {}
101         for g in grob_sigs:
102             val = d.setdefault (g.name, [])
103             val += [g]
104
105         self.grob_dict = d
106         self.set_all_bbox (grob_sigs)
107
108     def set_all_bbox (self, grobs):
109         self.bbox = empty_bbox
110         for g in grobs:
111             self.bbox = bbox_union (g.bbox, self.bbox)
112
113     def closest (self, grob_name, centroid):
114         min_d = INFTY
115         min_g = None
116         try:
117             grobs = self.grob_dict[grob_name]
118
119             for g in grobs:
120                 d = max_distance (g.centroid, centroid)
121                 if d < min_d:
122                     min_d = d
123                     min_g = g
124
125
126             return min_g
127
128         except KeyError:
129             return None
130     def grobs (self):
131         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
132
133 class SystemLink:
134     def __init__ (self, system1, system2):
135         self.system1 = system1
136         self.system2 = system2
137         
138         self.link_list_dict = {}
139         self.back_link_dict = {}
140
141         for g in system1.grobs ():
142             closest = system2.closest (g.name, g.centroid)
143             
144             self.link_list_dict.setdefault (closest, [])
145             self.link_list_dict[closest].append (g)
146             self.back_link_dict[g] = closest
147
148     def distance (self):
149         d = 0.0
150
151         scale = max (bbox_diameter (self.system1.bbox),
152                      bbox_diameter (self.system2.bbox))
153                                       
154         for (g1,g2) in self.back_link_dict.items ():
155             if g2 == None:
156                 d += ORPHAN_GROB_PENALTY
157             else:
158                 d += g1.distance (g2, scale)
159
160         for (g1,g2s) in self.link_list_dict.items ():
161             if len (g2s) != 1:
162                 d += ORPHAN_GROB_PENALTY
163
164         return d
165
166 ################################################################
167 # Files/directories
168
169 import glob
170 import shutil
171 import re
172
173 def read_signature_file (name):
174     print 'reading', name
175     exp_str = ("[%s]" % open (name).read ())
176     entries = safeeval.safe_eval (exp_str)
177
178     grob_sigs = [GrobSignature (e) for e in entries]
179     sig = SystemSignature (grob_sigs)
180     return sig
181
182
183 def compare_signature_files (f1, f2):
184     s1 = read_signature_file (f1)
185     s2 = read_signature_file (f2)
186     
187     return SystemLink (s1, s2).distance ()
188     
189     
190
191 def paired_files (dir1, dir2, pattern):
192     """
193     Search DIR1 and DIR2 for PATTERN.
194
195     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
196
197     """
198     
199     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
200     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
201
202     pairs = []
203     missing = []
204     for f in files1.keys ():
205         try:
206             files2.pop (f)
207             pairs.append (f)
208         except KeyError:
209             missing.append (f)
210
211     return (pairs, files2.keys (), missing)
212     
213 class ComparisonData:
214     def __init__ (self):
215         self.result_dict = {}
216         self.missing = []
217         self.added = []
218         
219     def compare_trees (self, dir1, dir2):
220         self.compare_directories (dir1, dir2)
221         
222         (root, files, dirs) = os.walk (dir1).next ()
223         for d in dirs:
224             d1 = os.path.join (dir1, d)
225             d2 = os.path.join (dir2, d)
226             
227             if os.path.isdir (d2):
228                 self.compare_trees (d1, d2)
229     
230     def compare_directories (self, dir1, dir2):
231         
232         (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
233
234         self.missing += [(dir1, m) for m in m1] 
235         self.added += [(dir2, m) for m in m2] 
236
237         for p in paired:
238             f2 = dir2 +  '/' + p
239             f1 = dir1 +  '/' + p
240             distance = compare_signature_files (f1, f2)
241             self.result_dict[f2] = (distance, f1)
242     
243     def print_results (self):
244         results = [(score, oldfile, file) for (file, (score, oldfile)) in self.result_dict.items ()]  
245         results.sort ()
246         results.reverse ()
247
248         for (s, oldfile, f) in results:
249             print '%30s %6f' % (f,s)
250
251         for (dir, file) in self.missing:
252             print '%-20s %s' % ('missing',os.path.join (dir, file))
253         for (dir, file) in self.added:
254             print '%10s%-10s %s' % ('','added', os.path.join (dir, file))
255         
256     def create_html_result_page (self, dir1, dir2):
257         dir1 = dir1.replace ('//', '/')
258         dir2 = dir2.replace ('//', '/')
259         
260         threshold = 1.0
261         
262         results = [(score, oldfile, file) for (file, (score, oldfile)) in self.result_dict.items ()
263                    if score > threshold]
264
265         results.sort ()
266         results.reverse ()
267
268         html = ''
269         old_prefix = os.path.split (dir1)[1]
270         os.mkdir (dir2 + '/' + old_prefix)
271         for (score, oldfile, newfile) in  results:
272             old_base = re.sub ("-[0-9]+.signature", '', os.path.split (oldfile)[1])
273             new_base = re.sub ("-[0-9]+.signature", '', newfile)
274             
275             for ext in 'png', 'ly':
276                 shutil.copy2 (old_base + '.' + ext, dir2 + '/' + old_prefix)
277
278             img_1 = os.path.join (old_prefix, old_base + '.png')
279             ly_1 = os.path.join (old_prefix, old_base + '.ly')
280
281             img_2 = new_base.replace (dir2, '') + '.png'
282             img_2 = re.sub ("^/*", '', img_2)
283
284             ly_2 = img_2.replace ('.png','.ly')
285
286             def img_cell (ly, img):
287                 return '''
288 <td align="center">
289 <a href="%(img)s">
290 <img src="%(img)s" style="border-style: none; max-width: 500px;">
291 </a><br>
292 <font size="-2">(<a href="%(ly)s">source</a>)
293 </font>
294 </td>
295 ''' % locals ()
296             
297             html_entry = '''
298 <tr>
299 <td>
300 %f
301 </td>
302
303 %s
304 %s
305 </tr>
306 ''' % (score, img_cell (ly_1, img_1), img_cell (ly_2, img_2))
307
308
309             html += html_entry
310
311         html = '''<html>
312 <table>
313 <tr>
314 <th>distance</th>
315 <th>old</th>
316 <th>new</th>
317 </tr>
318 %(html)s
319 </table>
320 </html>''' % locals()
321             
322         open (os.path.join (dir2, old_prefix) + '.html', 'w').write (html)
323         
324         
325
326 def compare_trees (dir1, dir2):
327     data =  ComparisonData ()
328     data.compare_trees (dir1, dir2)
329     data.print_results ()
330     data.create_html_result_page (dir1, dir2)
331     
332 ################################################################
333 # TESTING
334
335 import os
336 def system (x):
337     
338     print 'invoking', x
339     stat = os.system (x)
340     assert stat == 0
341
342 def test_paired_files ():
343     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
344                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
345                   
346     
347 def test_compare_trees ():
348     system ('rm -rf dir1 dir2')
349     system ('mkdir dir1 dir2')
350     system ('cp 20{-0.signature,.ly,.png} dir1')
351     system ('cp 20{-0.signature,.ly,.png} dir2')
352     system ('cp 20expr{-0.signature,.ly,.png} dir1')
353     system ('cp 19{-0.signature,.ly,.png} dir2/')
354     system ('cp 19{-0.signature,.ly,.png} dir1/')
355     system ('cp 20grob{-0.signature,.ly,.png} dir2/')
356
357     ## introduce difference
358     system ('cp 19-0.signature dir2/20-0.signature')
359
360     compare_trees ('dir1', 'dir2')
361     
362 def test_basic_compare ():
363     ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
364 #(set! toplevel-music-handler
365  (lambda (p m)
366  (if (not (eq? (ly:music-property m 'void) #t))
367     (print-score-with-defaults
368     p (scorify-music m p)))))
369
370 %(papermod)s
371
372 \relative c {
373   c^"%(userstring)s" %(extragrob)s
374   }
375 """
376
377     dicts = [{ 'papermod' : '',
378                'name' : '20',
379                'extragrob': '',
380                'userstring': 'test' },
381              { 'papermod' : '#(set-global-staff-size 19.5)',
382                'name' : '19',
383                'extragrob': '',
384                'userstring': 'test' },
385              { 'papermod' : '',
386                'name' : '20expr',
387                'extragrob': '',
388                'userstring': 'blabla' },
389              { 'papermod' : '',
390                'name' : '20grob',
391                'extragrob': 'c4',
392                'userstring': 'test' }]
393
394
395     for d in dicts:
396         open (d['name'] + '.ly','w').write (ly_template % d)
397         
398     names = [d['name'] for d in dicts]
399     
400     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
401     
402     sigs = dict ((n, read_signature_file ('%s-0.signature' % n)) for n in names)
403
404     combinations = {}
405     for (n1, s1) in sigs.items():
406         for (n2, s2) in sigs.items():
407             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
408             
409
410     results = combinations.items ()
411     results.sort ()
412     for k,v in results:
413         print '%-20s' % k, v
414
415     assert combinations['20-20'] == 0.0
416     assert combinations['20-20expr'] > 50.0
417     assert combinations['20-19'] < 10.0
418
419 def test_sigs (a,b):
420     sa = read_signature_file (a)
421     sb = read_signature_file (b)
422     link = SystemLink (sa, sb)
423     print link.distance()
424
425
426 def run_tests ():
427     do_clean = 1
428     dir = 'output-distance-test'
429
430     print 'test results in ', dir
431     if do_clean:
432         system ('rm -rf ' + dir)
433         system ('mkdir ' + dir)
434         
435     os.chdir (dir)
436
437     test_basic_compare ()
438     test_compare_trees ()
439     
440 ################################################################
441 #
442
443 def main ():
444     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
445     p.usage = 'output-distance.py [options] tree1 tree2'
446     
447     p.add_option ('', '--test',
448                   dest="run_test",
449                   action="store_true",
450                   help='run test method')
451
452     (o,a) = p.parse_args ()
453
454     if o.run_test:
455         run_tests ()
456         sys.exit (0)
457
458     if len (a) != 2:
459         p.print_usage()
460         sys.exit (2)
461
462     compare_trees (a[0], a[1])
463
464 if __name__ == '__main__':
465     main()
466