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