]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
* buildscripts/output-distance.py
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4 import os
5
6 ## so we can call directly as buildscripts/output-distance.py
7 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
8 sys.path.insert (0, me_path + '/../python/')
9
10
11 import safeeval
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 THRESHOLD = 1.0
21 inspect_max_count = 0
22
23 def max_distance (x1, x2):
24     dist = 0.0
25
26     for (p,q) in zip (x1, x2):
27         dist = max (abs (p-q), dist)
28         
29     return dist
30
31
32 empty_interval = (INFTY, -INFTY)
33 empty_bbox = (empty_interval, empty_interval)
34
35 def interval_is_empty (i):
36     return i[0] > i[1]
37
38 def interval_length (i):
39     return max (i[1]-i[0], 0) 
40     
41 def interval_union (i1, i2):
42     return (min (i1[0], i2[0]),
43             max (i1[1], i2[1]))
44
45 def interval_intersect (i1, i2):
46     return (max (i1[0], i2[0]),
47             min (i1[1], i2[1]))
48
49 def bbox_is_empty (b):
50     return (interval_is_empty (b[0])
51             or interval_is_empty (b[1]))
52
53 def bbox_union (b1, b2):
54     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
55             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
56             
57 def bbox_intersection (b1, b2):
58     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
59             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
60
61 def bbox_area (b):
62     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
63
64 def bbox_diameter (b):
65     return max (interval_length (b[X_AXIS]),
66                 interval_length (b[Y_AXIS]))
67                 
68
69 def difference_area (a, b):
70     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
71
72 class GrobSignature:
73     def __init__ (self, exp_list):
74         (self.name, self.origin, bbox_x,
75          bbox_y, self.output_expression) = tuple (exp_list)
76         
77         self.bbox = (bbox_x, bbox_y)
78         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
79
80     def __repr__ (self):
81         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
82                                                    self.bbox[0][0],
83                                                    self.bbox[0][1],
84                                                    self.bbox[1][0],
85                                                    self.bbox[1][1])
86                                                  
87     def axis_centroid (self, axis):
88         return apply (sum, self.bbox[axis])  / 2 
89     
90     def centroid_distance (self, other, scale):
91         return max_distance (self.centroid, other.centroid) / scale 
92         
93     def bbox_distance (self, other):
94         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
95
96         if divisor:
97             return (difference_area (self.bbox, other.bbox) +
98                     difference_area (other.bbox, self.bbox)) / divisor
99         else:
100             return 0.0
101         
102     def expression_distance (self, other):
103         if self.output_expression == other.output_expression:
104             return 0
105         else:
106             return 1
107
108 ################################################################
109 # single System.
110
111 class SystemSignature:
112     def __init__ (self, grob_sigs):
113         d = {}
114         for g in grob_sigs:
115             val = d.setdefault (g.name, [])
116             val += [g]
117
118         self.grob_dict = d
119         self.set_all_bbox (grob_sigs)
120
121     def set_all_bbox (self, grobs):
122         self.bbox = empty_bbox
123         for g in grobs:
124             self.bbox = bbox_union (g.bbox, self.bbox)
125
126     def closest (self, grob_name, centroid):
127         min_d = INFTY
128         min_g = None
129         try:
130             grobs = self.grob_dict[grob_name]
131
132             for g in grobs:
133                 d = max_distance (g.centroid, centroid)
134                 if d < min_d:
135                     min_d = d
136                     min_g = g
137
138
139             return min_g
140
141         except KeyError:
142             return None
143     def grobs (self):
144         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
145
146 ################################################################
147 ## comparison of systems.
148
149 class SystemLink:
150     def __init__ (self, system1, system2):
151         self.system1 = system1
152         self.system2 = system2
153         
154         self.link_list_dict = {}
155         self.back_link_dict = {}
156
157
158         ## pairs
159         self.orphans = []
160
161         ## pair -> distance
162         self.geo_distances = {}
163
164         ## pairs
165         self.expression_changed = []
166
167         self._geometric_distance = None
168         self._expression_change_count = None
169         self._orphan_count = None
170         
171         for g in system1.grobs ():
172
173             ## skip empty bboxes.
174             if bbox_is_empty (g.bbox):
175                 continue
176             
177             closest = system2.closest (g.name, g.centroid)
178             
179             self.link_list_dict.setdefault (closest, [])
180             self.link_list_dict[closest].append (g)
181             self.back_link_dict[g] = closest
182
183
184     def calc_geometric_distance (self):
185         total = 0.0
186         for (g1,g2) in self.back_link_dict.items ():
187             if g2:
188                 d = g1.bbox_distance (g2)
189                 if d:
190                     self.geo_distances[(g1,g2)] = d
191
192                 total += d
193
194         self._geometric_distance = total
195     
196     def calc_orphan_count (self):
197         count = 0
198         for (g1, g2) in self.back_link_dict.items ():
199             if g2 == None:
200                 self.orphans.append ((g1, None))
201                 
202                 count += 1
203
204         self._orphan_count = count
205     
206     def calc_output_exp_distance (self):
207         d = 0
208         for (g1,g2) in self.back_link_dict.items ():
209             if g2:
210                 d += g1.expression_distance (g2)
211
212         self._expression_change_count = d
213
214     def output_expression_details_string (self):
215         return ', '.join ([g1.name for g1 in self.expression_changed])
216     
217     def geo_details_string (self):
218         results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
219         results.sort ()
220         results.reverse ()
221         
222         return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
223
224     def orphan_details_string (self):
225         return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
226
227     def geometric_distance (self):
228         if self._geometric_distance == None:
229             self.calc_geometric_distance ()
230         return self._geometric_distance
231     
232     def orphan_count (self):
233         if self._orphan_count == None:
234             self.calc_orphan_count ()
235             
236         return self._orphan_count
237     
238     def output_expression_change_count (self):
239         if self._expression_change_count == None:
240             self.calc_output_exp_distance ()
241         return self._expression_change_count
242         
243     def distance (self):
244         return (self.output_expression_change_count (),
245                 self.orphan_count (),
246                 self.geometric_distance ())
247     
248 def read_signature_file (name):
249     print 'reading', name
250     exp_str = ("[%s]" % open (name).read ())
251     entries = safeeval.safe_eval (exp_str)
252
253     grob_sigs = [GrobSignature (e) for e in entries]
254     sig = SystemSignature (grob_sigs)
255     return sig
256
257
258 ################################################################
259 # different systems of a .ly file.
260
261 class FileLink:
262     def __init__ (self):
263         self.original_name = ''
264         self.base_names = ('','')
265         self.system_links = {}
266         self._distance = None
267         
268     def add_system_link (self, link, number):
269         self.system_links[number] = link
270
271     def calc_distance (self):
272         d = 0.0
273         for l in self.system_links.values ():
274             d = max (d, l.geometric_distance ())
275         return d
276
277     def distance (self):
278         if type (self._distance) != type (0.0):
279             return self.calc_distance ()
280         
281         return self._distance
282
283     def text_record_string (self):
284         return '%-30f %-20s\n' % (self.distance (),
285                              self.original_name)
286
287     def source_file (self):
288         for ext in ('.ly', '.ly.txt'):
289             if os.path.exists (self.base_names[1] + ext):
290                 return self.base_names[1] + ext
291         return ''
292     
293     def add_file_compare (self, f1, f2):
294         system_index = [] 
295
296         def note_system_index (m):
297             system_index.append (int (m.group (1)))
298             return ''
299         
300         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
301         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
302
303         self.base_names = (os.path.normpath (base1),
304                            os.path.normpath (base2))
305
306         def note_original (match):
307             self.original_name = match.group (1)
308             return ''
309         
310         if not self.original_name:
311             self.original_name = os.path.split (base1)[1]
312
313             ## ugh: drop the .ly.txt
314             for ext in ('.ly', '.ly.txt'):
315                 try:
316                     re.sub (r'\\sourcefilename "([^"]+)"',
317                             note_original, open (base1 + ext).read ())
318                 except IOError:
319                     pass
320                 
321         s1 = read_signature_file (f1)
322         s2 = read_signature_file (f2)
323
324         link = SystemLink (s1, s2)
325
326         self.add_system_link (link, system_index[0])
327
328     def link_files_for_html (self, old_dir, new_dir, dest_dir):
329         for ext in ('.png', '.ly'):
330             for oldnew in (0,1):
331                 link_file (self.base_names[oldnew] + ext, 
332                            dest_dir + '/' + self.base_names[oldnew] + ext)
333
334     def html_record_string (self,  old_dir, new_dir):
335         def img_cell (ly, img, name):
336             if not name:
337                 name = 'source'
338             else:
339                 name = '<tt>%s</tt>' % name
340                 
341             return '''
342 <td align="center">
343 <a href="%(img)s">
344 <img src="%(img)s" style="border-style: none; max-width: 500px;">
345 </a><br>
346 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
347 </font>
348 </td>
349 ''' % locals ()
350         
351
352         img_1  = self.base_names[0] + '.png'
353         ly_1  = self.base_names[0] + '.ly'
354         img_2  = self.base_names[1] + '.png'
355         ly_2  = self.base_names[1] + '.ly'
356         html_2  = self.base_names[1] + '.html'
357         name = self.original_name
358         
359         html_entry = '''
360 <tr>
361 <td>
362 %f<br>
363 (<a href="%s">details</a>)
364 </td>
365
366 %s
367 %s
368 </tr>
369 ''' % (self.distance (), html_2,
370        img_cell (ly_1, img_1, name), img_cell (ly_2, img_2, name))
371
372
373         return html_entry
374
375
376     def html_system_details_string (self):
377         systems = self.system_links.items ()
378         systems.sort ()
379
380         html = ""
381         for (c, link) in systems:
382             e = '<td>%d</td>' % c
383             for d in link.distance ():
384                 e += '<td>%f</td>' % d
385             
386             e = '<tr>%s</tr>' % e
387
388             html += e
389
390             e = '<td>%d</td>' % c
391             for s in (link.output_expression_details_string (),
392                       link.orphan_details_string (),
393                       link.geo_details_string ()):
394                 e += "<td>%s</td>" % s
395
396             
397             e = '<tr>%s</tr>' % e
398             html += e
399             
400         original = self.original_name
401         html = '''<html>
402 <head>
403 <title>comparison details for %(original)s</title>
404 </head>
405 <body>
406 <table border=1>
407 <tr>
408 <th>system</th>
409 <th>output</th>
410 <th>orphan</th>
411 <th>geo</th>
412 </tr>
413
414 %(html)s
415 </table>
416
417 </body>
418 </html>
419 ''' % locals ()
420         return html
421
422     def write_html_system_details (self, dir1, dir2, dest_dir):
423         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
424
425         details = open_write_file (dest_file)
426         details.write (self.html_system_details_string ())
427
428 ################################################################
429 # Files/directories
430
431 import glob
432 import re
433
434
435
436 def compare_signature_files (f1, f2):
437     s1 = read_signature_file (f1)
438     s2 = read_signature_file (f2)
439     
440     return SystemLink (s1, s2).distance ()
441
442 def paired_files (dir1, dir2, pattern):
443     """
444     Search DIR1 and DIR2 for PATTERN.
445
446     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
447
448     """
449     
450     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
451     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
452
453     pairs = []
454     missing = []
455     for f in files1.keys ():
456         try:
457             files2.pop (f)
458             pairs.append (f)
459         except KeyError:
460             missing.append (f)
461
462     return (pairs, files2.keys (), missing)
463     
464 class ComparisonData:
465     def __init__ (self):
466         self.result_dict = {}
467         self.missing = []
468         self.added = []
469         self.file_links = {}
470     def compare_trees (self, dir1, dir2):
471         self.compare_directories (dir1, dir2)
472         
473         (root, dirs, files) = os.walk (dir1).next ()
474         for d in dirs:
475             d1 = os.path.join (dir1, d)
476             d2 = os.path.join (dir2, d)
477
478             if os.path.islink (d1) or os.path.islink (d2):
479                 continue
480             
481             if os.path.isdir (d2):
482                 self.compare_trees (d1, d2)
483     
484     def compare_directories (self, dir1, dir2):
485
486         (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
487
488         self.missing += [(dir1, m) for m in m1] 
489         self.added += [(dir2, m) for m in m2] 
490
491         for p in paired:
492             if (inspect_max_count
493                 and len (self.file_links) > inspect_max_count):
494                 
495                 continue
496             
497             f2 = dir2 +  '/' + p
498             f1 = dir1 +  '/' + p
499             self.compare_files (f1, f2)
500
501     def compare_files (self, f1, f2):
502         name = os.path.split (f1)[1]
503         name = re.sub ('-[0-9]+.signature', '', name)
504         
505         file_link = None
506         try:
507             file_link = self.file_links[name]
508         except KeyError:
509             file_link = FileLink ()
510             self.file_links[name] = file_link
511
512         file_link.add_file_compare (f1,f2)
513
514     def write_text_result_page (self, filename):
515         print 'writing "%s"' % filename
516         out = None
517         if filename == '':
518             out = sys.stdout
519         else:
520             out = open_write_file (filename)
521
522         ## todo: support more scores.
523         results = [(link.distance(), link)
524                    for link in self.file_links.values ()]
525         results.sort ()
526         results.reverse ()
527
528         
529         for (score, link) in results:
530             if score > THRESHOLD:
531                 out.write (link.text_record_string ())
532
533         out.write ('\n\n')
534         out.write ('%d below threshold\n' % len ([1 for s,l  in results
535                                                     if THRESHOLD >=  s > 0.0]))
536         out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
537         
538     def create_text_result_page (self, dir1, dir2, dest_dir):
539         self.write_text_result_page (dest_dir + '/index.txt')
540         
541     def create_html_result_page (self, dir1, dir2, dest_dir):
542         dir1 = dir1.replace ('//', '/')
543         dir2 = dir2.replace ('//', '/')
544         
545         results = [(link.distance(), link)
546                    for link in self.file_links.values ()]
547         results.sort ()
548         results.reverse ()
549
550         html = ''
551         old_prefix = os.path.split (dir1)[1]
552         for (score, link) in results:
553             if score <= THRESHOLD:
554                 continue
555
556             link.write_html_system_details (dir1, dir2, dest_dir)
557             link.link_files_for_html (dir1, dir2, dest_dir) 
558             html += link.html_record_string (dir1, dir2)
559
560
561         html = '''<html>
562 <table rules="rows" border bordercolor="blue">
563 <tr>
564 <th>distance</th>
565 <th>old</th>
566 <th>new</th>
567 </tr>
568 %(html)s
569 </table>
570 </html>''' % locals()
571
572         html += ('<p>')
573         below_count  =len ([1 for s,l  in results
574                          if THRESHOLD >=  s > 0.0])
575
576         if below_count:
577             html += ('<p>%d below threshold</p>' % below_count)
578
579         html += ('<p>%d unchanged</p>'
580                  % len ([1 for (s,l) in results if s == 0.0]))
581
582
583         dest_file = dest_dir + '/index.html'
584         open_write_file (dest_file).write (html)
585         
586     def print_results (self):
587         self.write_text_result_page ('')
588         
589
590 def compare_trees (dir1, dir2, dest_dir):
591     data = ComparisonData ()
592     data.compare_trees (dir1, dir2)
593     data.print_results ()
594
595     if os.path.isdir (dest_dir):
596         system ('rm -rf %s '% dest_dir)
597
598     data.create_html_result_page (dir1, dir2, dest_dir)
599     data.create_text_result_page (dir1, dir2, dest_dir)
600     
601 ################################################################
602 # TESTING
603
604 def mkdir (x):
605     if not os.path.isdir (x):
606         print 'mkdir', x
607         os.makedirs (x)
608
609 def link_file (x, y):
610     mkdir (os.path.split (y)[0])
611     os.link (x, y)
612     
613 def open_write_file (x):
614     d = os.path.split (x)[0]
615     mkdir (d)
616     return open (x, 'w')
617
618
619 def system (x):
620     
621     print 'invoking', x
622     stat = os.system (x)
623     assert stat == 0
624
625
626 def test_paired_files ():
627     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
628                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
629                   
630     
631 def test_compare_trees ():
632     system ('rm -rf dir1 dir2')
633     system ('mkdir dir1 dir2')
634     system ('cp 20{-*.signature,.ly,.png} dir1')
635     system ('cp 20{-*.signature,.ly,.png} dir2')
636     system ('cp 20expr{-*.signature,.ly,.png} dir1')
637     system ('cp 19{-*.signature,.ly,.png} dir2/')
638     system ('cp 19{-*.signature,.ly,.png} dir1/')
639     system ('cp 19-1.signature 19-sub-1.signature')
640     system ('cp 19.ly 19-sub.ly')
641     system ('cp 19.png 19-sub.png')
642     
643     system ('mkdir -p dir1/subdir/ dir2/subdir/')
644     system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
645     system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
646     system ('cp 20grob{-*.signature,.ly,.png} dir2/')
647     system ('cp 20grob{-*.signature,.ly,.png} dir1/')
648
649     ## introduce differences
650     system ('cp 19-1.signature dir2/20-1.signature')
651     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
652
653     ## radical diffs.
654     system ('cp 19-1.signature dir2/20grob-1.signature')
655     system ('cp 19-1.signature dir2/20grob-2.signature')
656
657     compare_trees ('dir1', 'dir2', 'compare-dir1dir2')
658
659
660 def test_basic_compare ():
661     ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
662 #(set! toplevel-music-handler
663  (lambda (p m)
664  (if (not (eq? (ly:music-property m 'void) #t))
665     (print-score-with-defaults
666     p (scorify-music m p)))))
667
668 \sourcefilename "my-source.ly"
669
670 %(papermod)s
671 <<
672 \new Staff \relative c {
673   c4^"%(userstring)s" %(extragrob)s
674   }
675 \new Staff \relative c {
676   c4^"%(userstring)s" %(extragrob)s
677   }
678 >>
679 """
680
681     dicts = [{ 'papermod' : '',
682                'name' : '20',
683                'extragrob': '',
684                'userstring': 'test' },
685              { 'papermod' : '#(set-global-staff-size 19.5)',
686                'name' : '19',
687                'extragrob': '',
688                'userstring': 'test' },
689              { 'papermod' : '',
690                'name' : '20expr',
691                'extragrob': '',
692                'userstring': 'blabla' },
693              { 'papermod' : '',
694                'name' : '20grob',
695                'extragrob': 'r2. \\break c1',
696                'userstring': 'test' }
697
698              ]
699
700     for d in dicts:
701         open (d['name'] + '.ly','w').write (ly_template % d)
702         
703     names = [d['name'] for d in dicts]
704     
705     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
706     
707     sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
708     combinations = {}
709     for (n1, s1) in sigs.items():
710         for (n2, s2) in sigs.items():
711             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
712
713     results = combinations.items ()
714     results.sort ()
715     for k,v in results:
716         print '%-20s' % k, v
717
718     assert combinations['20-20'] == (0.0,0.0,0.0)
719     assert combinations['20-20expr'][0] > 0.0
720     assert combinations['20-19'][2] < 10.0
721     assert combinations['20-19'][2] > 0.0
722
723
724 def run_tests ():
725     dir = 'output-distance-test'
726
727     do_clean = not os.path.exists (dir)
728
729     print 'test results in ', dir
730     if do_clean:
731         system ('rm -rf ' + dir)
732         system ('mkdir ' + dir)
733         
734     os.chdir (dir)
735     if do_clean:
736         test_basic_compare ()
737         
738     test_compare_trees ()
739     
740 ################################################################
741 #
742
743 def main ():
744     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
745     p.usage = 'output-distance.py [options] tree1 tree2'
746     
747     p.add_option ('', '--test',
748                   dest="run_test",
749                   action="store_true",
750                   help='run test method')
751     p.add_option ('--max-count',
752                   dest="max_count",
753                   metavar="COUNT",
754                   type="int",
755                   default=0, 
756                   action="store",
757                   help='only analyze COUNT signature pairs')
758  
759     (o,a) = p.parse_args ()
760
761     if o.run_test:
762         run_tests ()
763         sys.exit (0)
764
765     if len (a) != 2:
766         p.print_usage()
767         sys.exit (2)
768
769     global inspect_max_count
770     inspect_max_count = o.max_count
771
772     compare_trees (a[0], a[1], a[1] + '/' +  a[0])
773
774 if __name__ == '__main__':
775     main()
776