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/')
18 OUTPUT_EXPRESSION_PENALTY = 1
19 ORPHAN_GROB_PENALTY = 1
22 def shorten_string (s):
24 if len (s) > 2*threshold:
25 s = s[:threshold] + '..' + s[-threshold:]
28 def max_distance (x1, x2):
31 for (p,q) in zip (x1, x2):
32 dist = max (abs (p-q), dist)
37 empty_interval = (INFTY, -INFTY)
38 empty_bbox = (empty_interval, empty_interval)
40 def interval_is_empty (i):
43 def interval_length (i):
44 return max (i[1]-i[0], 0)
46 def interval_union (i1, i2):
47 return (min (i1[0], i2[0]),
50 def interval_intersect (i1, i2):
51 return (max (i1[0], i2[0]),
54 def bbox_is_empty (b):
55 return (interval_is_empty (b[0])
56 or interval_is_empty (b[1]))
58 def bbox_union (b1, b2):
59 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
60 interval_union (b2[Y_AXIS], b2[Y_AXIS]))
62 def bbox_intersection (b1, b2):
63 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
64 interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
67 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
69 def bbox_diameter (b):
70 return max (interval_length (b[X_AXIS]),
71 interval_length (b[Y_AXIS]))
74 def difference_area (a, b):
75 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
78 def __init__ (self, exp_list):
79 (self.name, self.origin, bbox_x,
80 bbox_y, self.output_expression) = tuple (exp_list)
82 self.bbox = (bbox_x, bbox_y)
83 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
86 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
92 def axis_centroid (self, axis):
93 return apply (sum, self.bbox[axis]) / 2
95 def centroid_distance (self, other, scale):
96 return max_distance (self.centroid, other.centroid) / scale
98 def bbox_distance (self, other):
99 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
102 return (difference_area (self.bbox, other.bbox) +
103 difference_area (other.bbox, self.bbox)) / divisor
107 def expression_distance (self, other):
108 if self.output_expression == other.output_expression:
113 ################################################################
116 class SystemSignature:
117 def __init__ (self, grob_sigs):
120 val = d.setdefault (g.name, [])
124 self.set_all_bbox (grob_sigs)
126 def set_all_bbox (self, grobs):
127 self.bbox = empty_bbox
129 self.bbox = bbox_union (g.bbox, self.bbox)
131 def closest (self, grob_name, centroid):
135 grobs = self.grob_dict[grob_name]
138 d = max_distance (g.centroid, centroid)
149 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
151 ################################################################
152 ## comparison of systems.
155 def __init__ (self, system1, system2):
156 self.system1 = system1
157 self.system2 = system2
159 self.link_list_dict = {}
160 self.back_link_dict = {}
167 self.geo_distances = {}
170 self.expression_changed = []
172 self._geometric_distance = None
173 self._expression_change_count = None
174 self._orphan_count = None
176 for g in system1.grobs ():
178 ## skip empty bboxes.
179 if bbox_is_empty (g.bbox):
182 closest = system2.closest (g.name, g.centroid)
184 self.link_list_dict.setdefault (closest, [])
185 self.link_list_dict[closest].append (g)
186 self.back_link_dict[g] = closest
189 def calc_geometric_distance (self):
191 for (g1,g2) in self.back_link_dict.items ():
193 d = g1.bbox_distance (g2)
195 self.geo_distances[(g1,g2)] = d
199 self._geometric_distance = total
201 def calc_orphan_count (self):
203 for (g1, g2) in self.back_link_dict.items ():
205 self.orphans.append ((g1, None))
209 self._orphan_count = count
211 def calc_output_exp_distance (self):
213 for (g1,g2) in self.back_link_dict.items ():
215 d += g1.expression_distance (g2)
217 self._expression_change_count = d
219 def output_expression_details_string (self):
220 return ', '.join ([g1.name for g1 in self.expression_changed])
222 def geo_details_string (self):
223 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
227 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
229 def orphan_details_string (self):
230 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
232 def geometric_distance (self):
233 if self._geometric_distance == None:
234 self.calc_geometric_distance ()
235 return self._geometric_distance
237 def orphan_count (self):
238 if self._orphan_count == None:
239 self.calc_orphan_count ()
241 return self._orphan_count
243 def output_expression_change_count (self):
244 if self._expression_change_count == None:
245 self.calc_output_exp_distance ()
246 return self._expression_change_count
249 return (self.output_expression_change_count (),
250 self.orphan_count (),
251 self.geometric_distance ())
253 def read_signature_file (name):
254 print 'reading', name
256 entries = open (name).read ().split ('\n')
257 def string_to_tup (s):
258 return tuple (map (float, s.split (' ')))
260 def string_to_entry (s):
261 fields = s.split('@')
262 fields[2] = string_to_tup (fields[2])
263 fields[3] = string_to_tup (fields[3])
265 return tuple (fields)
267 entries = [string_to_entry (e) for e in entries
268 if e and not e.startswith ('#')]
270 grob_sigs = [GrobSignature (e) for e in entries]
271 sig = SystemSignature (grob_sigs)
275 ################################################################
276 # different systems of a .ly file.
279 return os.popen (c).read ()
285 raise Exception ("failed")
288 def compare_png_images (old, new, dir):
290 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
292 return tuple (map (int, m.groups ()))
294 dest = os.path.join (dir, new.replace ('.png', '.compare.jpeg'))
296 dims1 = png_dims (old)
297 dims2 = png_dims (new)
298 except AttributeError:
300 system ('touch %(dest)s' % locals ())
303 dims = (min (dims1[0], dims2[0]),
304 min (dims1[1], dims2[1]))
306 system ('convert -depth 8 -crop %dx%d+0+0 %s crop1.png' % (dims + (old,)))
307 system ('convert -depth 8 -crop %dx%d+0+0 %s crop2.png' % (dims + (new,)))
309 system ('compare -depth 8 crop1.png crop2.png diff.png')
311 system ("convert -depth 8 diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' matte.png")
313 system ("composite -quality 65 matte.png %(new)s %(dest)s" % locals ())
316 def text_record_string (self):
317 return '%-30f %-20s\n' % (self.distance (),
325 def link_files_for_html (self, old_dir, new_dir, dest_dir):
328 def write_html_system_details (self, dir1, dir2, dest_dir):
331 def html_record_string (self, old_dir, new_dir):
334 class MidiFileLink (FileLink):
335 def get_midi (self, f):
337 s = re.sub ('LilyPond [0-9.]+', '', s)
340 def __init__ (self, f1, f2):
341 self.files = (f1, f2)
343 s1 = self.get_midi (self.files[0])
344 s2 = self.get_midi (self.files[1])
346 self.same = (s1 == s2)
349 name = os.path.split (self.files[0])[1]
350 name = re.sub ('.midi', '', name)
354 ## todo: could use import MIDI to pinpoint
355 ## what & where changed.
360 def html_record_string (self, d1, d2):
367 </tr>''' % ((self.distance(),) + self.files)
369 class SignatureFileLink (FileLink):
371 self.original_name = ''
372 self.base_names = ('','')
373 self.system_links = {}
374 self._distance = None
376 return self.original_name
378 def add_system_link (self, link, number):
379 self.system_links[number] = link
381 def calc_distance (self):
384 orphan_distance = 0.0
385 for l in self.system_links.values ():
386 d = max (d, l.geometric_distance ())
387 orphan_distance += l.orphan_count ()
389 return d + orphan_distance
392 if type (self._distance) != type (0.0):
393 return self.calc_distance ()
395 return self._distance
397 def source_file (self):
398 for ext in ('.ly', '.ly.txt'):
399 if os.path.exists (self.base_names[1] + ext):
400 return self.base_names[1] + ext
403 def add_file_compare (self, f1, f2):
406 def note_system_index (m):
407 system_index.append (int (m.group (1)))
410 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
411 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
413 self.base_names = (os.path.normpath (base1),
414 os.path.normpath (base2))
416 def note_original (match):
417 self.original_name = match.group (1)
420 if not self.original_name:
421 self.original_name = os.path.split (base1)[1]
423 ## ugh: drop the .ly.txt
424 for ext in ('.ly', '.ly.txt'):
426 re.sub (r'\\sourcefilename "([^"]+)"',
427 note_original, open (base1 + ext).read ())
431 s1 = read_signature_file (f1)
432 s2 = read_signature_file (f2)
434 link = SystemLink (s1, s2)
436 self.add_system_link (link, system_index[0])
438 def link_files_for_html (self, old_dir, new_dir, dest_dir):
439 png_linked = [[], []]
440 for ext in ('.png', '.ly', '-page*png'):
443 for f in glob.glob (self.base_names[oldnew] + ext):
444 dst = dest_dir + '/' + f
447 if f.endswith ('.png'):
448 png_linked[oldnew].append (f)
450 if options.compare_images:
451 for (old,new) in zip (png_linked[0], png_linked[1]):
452 compare_png_images (old, new, dest_dir)
454 def html_record_string (self, old_dir, new_dir):
455 def img_cell (ly, img, name):
459 name = '<tt>%s</tt>' % name
464 <img src="%(img)s" style="border-style: none; max-width: 500px;">
466 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
471 def multi_img_cell (ly, imgs, name):
475 name = '<tt>%s</tt>' % name
477 imgs_str = '\n'.join (['''<a href="%s">
478 <img src="%s" style="border-style: none; max-width: 500px;">
479 </a><br>''' % (img, img)
486 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
493 def cell (base, name):
494 pat = base + '-page*.png'
495 pages = glob.glob (pat)
498 return multi_img_cell (base + '.ly', sorted (pages), name)
500 return img_cell (base + '.ly', base + '.png', name)
503 html_2 = self.base_names[1] + '.html'
504 name = self.original_name
506 cell_1 = cell (self.base_names[0], name)
507 cell_2 = cell (self.base_names[1], name)
508 if options.compare_images:
509 cell_2 = cell_2.replace ('.png', '.compare.jpeg')
515 (<a href="%s">details</a>)
521 ''' % (self.distance (), html_2, cell_1, cell_2)
526 def html_system_details_string (self):
527 systems = self.system_links.items ()
531 for (c, link) in systems:
532 e = '<td>%d</td>' % c
533 for d in link.distance ():
534 e += '<td>%f</td>' % d
536 e = '<tr>%s</tr>' % e
540 e = '<td>%d</td>' % c
541 for s in (link.output_expression_details_string (),
542 link.orphan_details_string (),
543 link.geo_details_string ()):
544 e += "<td>%s</td>" % s
547 e = '<tr>%s</tr>' % e
550 original = self.original_name
553 <title>comparison details for %(original)s</title>
572 def write_html_system_details (self, dir1, dir2, dest_dir):
573 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
575 details = open_write_file (dest_file)
576 details.write (self.html_system_details_string ())
578 ################################################################
586 def compare_signature_files (f1, f2):
587 s1 = read_signature_file (f1)
588 s2 = read_signature_file (f2)
590 return SystemLink (s1, s2).distance ()
592 def paired_files (dir1, dir2, pattern):
594 Search DIR1 and DIR2 for PATTERN.
596 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
600 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
601 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
605 for f in files1.keys ():
612 return (pairs, files2.keys (), missing)
614 class ComparisonData:
616 self.result_dict = {}
621 def compare_trees (self, dir1, dir2):
622 self.compare_directories (dir1, dir2)
624 (root, dirs, files) = os.walk (dir1).next ()
626 d1 = os.path.join (dir1, d)
627 d2 = os.path.join (dir2, d)
629 if os.path.islink (d1) or os.path.islink (d2):
632 if os.path.isdir (d2):
633 self.compare_trees (d1, d2)
635 def compare_directories (self, dir1, dir2):
636 for ext in ['signature', 'midi']:
637 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
639 self.missing += [(dir1, m) for m in m1]
640 self.added += [(dir2, m) for m in m2]
643 if (options.max_count
644 and len (self.file_links) > options.max_count):
650 self.compare_files (f1, f2)
652 def compare_files (self, f1, f2):
653 if f1.endswith ('signature'):
654 self.compare_signature_files (f1, f2)
655 elif f1.endswith ('midi'):
656 self.compare_midi_files (f1, f2)
658 def compare_midi_files (self, f1, f2):
659 name = os.path.split (f1)[1]
661 file_link = MidiFileLink (f1, f2)
662 self.file_links[name] = file_link
664 def compare_signature_files (self, f1, f2):
665 name = os.path.split (f1)[1]
666 name = re.sub ('-[0-9]+.signature', '', name)
670 file_link = self.file_links[name]
672 file_link = SignatureFileLink ()
673 self.file_links[name] = file_link
675 file_link.add_file_compare (f1, f2)
677 def write_text_result_page (self, filename, threshold):
682 print 'writing "%s"' % filename
683 out = open_write_file (filename)
685 ## todo: support more scores.
686 results = [(link.distance(), link)
687 for link in self.file_links.values ()]
692 for (score, link) in results:
693 if score > threshold:
694 out.write (link.text_record_string ())
697 out.write ('%d below threshold\n' % len ([1 for s,l in results
698 if threshold >= s > 0.0]))
699 out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
701 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
702 self.write_text_result_page (dest_dir + '/index.txt', threshold)
704 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
705 dir1 = dir1.replace ('//', '/')
706 dir2 = dir2.replace ('//', '/')
708 results = [(link.distance(), link)
709 for link in self.file_links.values ()]
714 old_prefix = os.path.split (dir1)[1]
715 for (score, link) in results:
716 if score <= threshold:
719 link.link_files_for_html (dir1, dir2, dest_dir)
720 link.write_html_system_details (dir1, dir2, dest_dir)
722 html += link.html_record_string (dir1, dir2)
725 short_dir1 = shorten_string (dir1)
726 short_dir2 = shorten_string (dir2)
728 <table rules="rows" border bordercolor="blue">
731 <th>%(short_dir1)s</th>
732 <th>%(short_dir2)s</th>
736 </html>''' % locals()
739 below_count =len ([1 for s,l in results
740 if threshold >= s > 0.0])
743 html += ('<p>%d below threshold</p>' % below_count)
745 html += ('<p>%d unchanged</p>'
746 % len ([1 for (s,l) in results if s == 0.0]))
749 dest_file = dest_dir + '/index.html'
750 open_write_file (dest_file).write (html)
752 def print_results (self, threshold):
753 self.write_text_result_page ('', threshold)
755 def compare_trees (dir1, dir2, dest_dir, threshold):
756 data = ComparisonData ()
757 data.compare_trees (dir1, dir2)
758 data.print_results (threshold)
760 if os.path.isdir (dest_dir):
761 system ('rm -rf %s '% dest_dir)
763 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
764 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
766 ################################################################
770 if not os.path.isdir (x):
774 def link_file (x, y):
775 mkdir (os.path.split (y)[0])
779 print 'OSError', x, y, z
782 def open_write_file (x):
783 d = os.path.split (x)[0]
795 def test_paired_files ():
796 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
797 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
800 def test_compare_trees ():
801 system ('rm -rf dir1 dir2')
802 system ('mkdir dir1 dir2')
803 system ('cp 20{-*.signature,.ly,.png} dir1')
804 system ('cp 20{-*.signature,.ly,.png} dir2')
805 system ('cp 20expr{-*.signature,.ly,.png} dir1')
806 system ('cp 19{-*.signature,.ly,.png} dir2/')
807 system ('cp 19{-*.signature,.ly,.png} dir1/')
808 system ('cp 19-1.signature 19-sub-1.signature')
809 system ('cp 19.ly 19-sub.ly')
810 system ('cp 19.png 19-sub.png')
812 system ('cp 20multipage* dir1')
813 system ('cp 20multipage* dir2')
814 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
817 system ('mkdir -p dir1/subdir/ dir2/subdir/')
818 system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
819 system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
820 system ('cp 20grob{-*.signature,.ly,.png} dir2/')
821 system ('cp 20grob{-*.signature,.ly,.png} dir1/')
823 ## introduce differences
824 system ('cp 19-1.signature dir2/20-1.signature')
825 system ('cp 19.png dir2/20.png')
826 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
827 system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
828 system ('cp 20.png dir2/subdir/19-sub.png')
831 system ('cp 19-1.signature dir2/20grob-1.signature')
832 system ('cp 19-1.signature dir2/20grob-2.signature')
833 system ('cp 19multipage.midi dir1/midi-differ.midi')
834 system ('cp 20multipage.midi dir2/midi-differ.midi')
836 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
839 def test_basic_compare ():
843 #(set! toplevel-score-handler print-score-with-defaults)
844 #(set! toplevel-music-handler
846 (if (not (eq? (ly:music-property m 'void) #t))
847 (print-score-with-defaults
848 p (scorify-music m p)))))
850 \sourcefilename "my-source.ly"
853 \header { tagline = ##f }
856 \new Staff \relative c {
857 c4^"%(userstring)s" %(extragrob)s
859 \new Staff \relative c {
860 c4^"%(userstring)s" %(extragrob)s
868 dicts = [{ 'papermod' : '',
871 'userstring': 'test' },
872 { 'papermod' : '#(set-global-staff-size 19.5)',
875 'userstring': 'test' },
879 'userstring': 'blabla' },
882 'extragrob': 'r2. \\break c1',
883 'userstring': 'test' },
887 open (d['name'] + '.ly','w').write (ly_template % d)
889 names = [d['name'] for d in dicts]
891 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
895 #(set-default-paper-size "a6")
897 \relative {c1 \pageBreak c1 }
903 open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
904 open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
905 system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
907 test_compare_signatures (names)
909 def test_compare_signatures (names, timing=False):
920 for t in range (0, times):
921 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
925 print 'elapsed', (time.clock() - t0)/count
931 for (n1, s1) in sigs.items():
932 for (n2, s2) in sigs.items():
933 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
937 print 'elapsed', (time.clock() - t0)/count
939 results = combinations.items ()
944 assert combinations['20-20'] == (0.0,0.0,0.0)
945 assert combinations['20-20expr'][0] > 0.0
946 assert combinations['20-19'][2] < 10.0
947 assert combinations['20-19'][2] > 0.0
951 dir = 'test-output-distance'
953 do_clean = not os.path.exists (dir)
955 print 'test results in ', dir
957 system ('rm -rf ' + dir)
958 system ('mkdir ' + dir)
962 test_basic_compare ()
964 test_compare_trees ()
966 ################################################################
970 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
971 p.usage = 'output-distance.py [options] tree1 tree2'
973 p.add_option ('', '--test-self',
976 help='run test method')
978 p.add_option ('--max-count',
984 help='only analyze COUNT signature pairs')
986 p.add_option ('', '--threshold',
991 help='threshold for geometric distance')
993 p.add_option ('--no-compare-images',
994 dest="compare_images",
996 action="store_false",
997 help="Don't run graphical comparisons")
999 p.add_option ('-o', '--output-dir',
1004 help='where to put the test results [tree2/compare-tree1tree2]')
1007 (options, a) = p.parse_args ()
1009 if options.run_test:
1017 name = options.output_dir
1019 name = a[0].replace ('/', '')
1020 name = os.path.join (a[1], 'compare-' + shorten_string (name))
1022 compare_trees (a[0], a[1], name, options.threshold)
1024 if __name__ == '__main__':