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 max_distance (x1, x2):
25 for (p,q) in zip (x1, x2):
26 dist = max (abs (p-q), dist)
31 empty_interval = (INFTY, -INFTY)
32 empty_bbox = (empty_interval, empty_interval)
34 def interval_is_empty (i):
37 def interval_length (i):
38 return max (i[1]-i[0], 0)
40 def interval_union (i1, i2):
41 return (min (i1[0], i2[0]),
44 def interval_intersect (i1, i2):
45 return (max (i1[0], i2[0]),
48 def bbox_is_empty (b):
49 return (interval_is_empty (b[0])
50 or interval_is_empty (b[1]))
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]))
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]))
61 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
63 def bbox_diameter (b):
64 return max (interval_length (b[X_AXIS]),
65 interval_length (b[Y_AXIS]))
68 def difference_area (a, b):
69 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
72 def __init__ (self, exp_list):
73 (self.name, self.origin, bbox_x,
74 bbox_y, self.output_expression) = tuple (exp_list)
76 self.bbox = (bbox_x, bbox_y)
77 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
80 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
86 def axis_centroid (self, axis):
87 return apply (sum, self.bbox[axis]) / 2
89 def centroid_distance (self, other, scale):
90 return max_distance (self.centroid, other.centroid) / scale
92 def bbox_distance (self, other):
93 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
96 return (difference_area (self.bbox, other.bbox) +
97 difference_area (other.bbox, self.bbox)) / divisor
101 def expression_distance (self, other):
102 if self.output_expression == other.output_expression:
107 ################################################################
110 class SystemSignature:
111 def __init__ (self, grob_sigs):
114 val = d.setdefault (g.name, [])
118 self.set_all_bbox (grob_sigs)
120 def set_all_bbox (self, grobs):
121 self.bbox = empty_bbox
123 self.bbox = bbox_union (g.bbox, self.bbox)
125 def closest (self, grob_name, centroid):
129 grobs = self.grob_dict[grob_name]
132 d = max_distance (g.centroid, centroid)
143 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
145 ################################################################
146 ## comparison of systems.
149 def __init__ (self, system1, system2):
150 self.system1 = system1
151 self.system2 = system2
153 self.link_list_dict = {}
154 self.back_link_dict = {}
161 self.geo_distances = {}
164 self.expression_changed = []
166 self._geometric_distance = None
167 self._expression_change_count = None
168 self._orphan_count = None
170 for g in system1.grobs ():
172 ## skip empty bboxes.
173 if bbox_is_empty (g.bbox):
176 closest = system2.closest (g.name, g.centroid)
178 self.link_list_dict.setdefault (closest, [])
179 self.link_list_dict[closest].append (g)
180 self.back_link_dict[g] = closest
183 def calc_geometric_distance (self):
185 for (g1,g2) in self.back_link_dict.items ():
187 d = g1.bbox_distance (g2)
189 self.geo_distances[(g1,g2)] = d
193 self._geometric_distance = total
195 def calc_orphan_count (self):
197 for (g1, g2) in self.back_link_dict.items ():
199 self.orphans.append ((g1, None))
203 self._orphan_count = count
205 def calc_output_exp_distance (self):
207 for (g1,g2) in self.back_link_dict.items ():
209 d += g1.expression_distance (g2)
211 self._expression_change_count = d
213 def output_expression_details_string (self):
214 return ', '.join ([g1.name for g1 in self.expression_changed])
216 def geo_details_string (self):
217 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
221 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
223 def orphan_details_string (self):
224 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
226 def geometric_distance (self):
227 if self._geometric_distance == None:
228 self.calc_geometric_distance ()
229 return self._geometric_distance
231 def orphan_count (self):
232 if self._orphan_count == None:
233 self.calc_orphan_count ()
235 return self._orphan_count
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
243 return (self.output_expression_change_count (),
244 self.orphan_count (),
245 self.geometric_distance ())
247 def read_signature_file (name):
248 print 'reading', name
250 entries = open (name).read ().split ('\n')
251 def string_to_tup (s):
252 return tuple (map (float, s.split (' ')))
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])
259 return tuple (fields)
261 entries = [string_to_entry (e) for e in entries
262 if e and not e.startswith ('#')]
264 grob_sigs = [GrobSignature (e) for e in entries]
265 sig = SystemSignature (grob_sigs)
269 ################################################################
270 # different systems of a .ly file.
273 return os.popen (c).read ()
279 raise Exception ("failed")
282 def compare_png_images (old, new, dir):
284 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
286 return tuple (map (int, m.groups ()))
288 dest = os.path.join (dir, new.replace ('.png', '.compare.png'))
290 dims1 = png_dims (old)
291 dims2 = png_dims (new)
292 except AttributeError:
296 dims = (min (dims1[0], dims2[0]),
297 min (dims1[1], dims2[1]))
299 system ('convert -depth 8 -crop %dx%d+0+0 %s crop1.png' % (dims + (old,)))
300 system ('convert -depth 8 -crop %dx%d+0+0 %s crop2.png' % (dims + (new,)))
302 system ('compare -depth 8 crop1.png crop2.png diff.png')
304 system ("convert -depth 8 diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' matte.png")
306 system ("composite -depth 8 -type Palette matte.png %(new)s %(dest)s" % locals ())
310 self.original_name = ''
311 self.base_names = ('','')
312 self.system_links = {}
313 self._distance = None
315 def add_system_link (self, link, number):
316 self.system_links[number] = link
318 def calc_distance (self):
321 orphan_distance = 0.0
322 for l in self.system_links.values ():
323 d = max (d, l.geometric_distance ())
324 orphan_distance += l.orphan_count ()
326 return d + orphan_distance
329 if type (self._distance) != type (0.0):
330 return self.calc_distance ()
332 return self._distance
334 def text_record_string (self):
335 return '%-30f %-20s\n' % (self.distance (),
338 def source_file (self):
339 for ext in ('.ly', '.ly.txt'):
340 if os.path.exists (self.base_names[1] + ext):
341 return self.base_names[1] + ext
344 def add_file_compare (self, f1, f2):
347 def note_system_index (m):
348 system_index.append (int (m.group (1)))
351 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
352 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
354 self.base_names = (os.path.normpath (base1),
355 os.path.normpath (base2))
357 def note_original (match):
358 self.original_name = match.group (1)
361 if not self.original_name:
362 self.original_name = os.path.split (base1)[1]
364 ## ugh: drop the .ly.txt
365 for ext in ('.ly', '.ly.txt'):
367 re.sub (r'\\sourcefilename "([^"]+)"',
368 note_original, open (base1 + ext).read ())
372 s1 = read_signature_file (f1)
373 s2 = read_signature_file (f2)
375 link = SystemLink (s1, s2)
377 self.add_system_link (link, system_index[0])
379 def link_files_for_html (self, old_dir, new_dir, dest_dir):
380 png_linked = [[], []]
381 for ext in ('.png', '.ly', '-page*png'):
384 for f in glob.glob (self.base_names[oldnew] + ext):
385 dst = dest_dir + '/' + f
388 if f.endswith ('.png'):
389 png_linked[oldnew].append (f)
391 for (old,new) in zip (png_linked[0], png_linked[1]):
392 compare_png_images (old, new, dest_dir)
394 def html_record_string (self, old_dir, new_dir):
395 def img_cell (ly, img, name):
399 name = '<tt>%s</tt>' % name
404 <img src="%(img)s" style="border-style: none; max-width: 500px;">
406 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
411 def multi_img_cell (ly, imgs, name):
415 name = '<tt>%s</tt>' % name
417 imgs_str = '\n'.join (['''<a href="%s">
418 <img src="%s" style="border-style: none; max-width: 500px;">
419 </a><br>''' % (img, img)
426 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
433 def cell (base, name):
434 pat = base + '-page*.png'
435 pages = glob.glob (pat)
438 return multi_img_cell (base + '.ly', sorted (pages), name)
440 return img_cell (base + '.ly', base + '.png', name)
443 html_2 = self.base_names[1] + '.html'
444 name = self.original_name
450 (<a href="%s">details</a>)
456 ''' % (self.distance (), html_2,
457 cell (self.base_names[0], name),
458 cell (self.base_names[1], name).replace ('.png', '.compare.png'))
463 def html_system_details_string (self):
464 systems = self.system_links.items ()
468 for (c, link) in systems:
469 e = '<td>%d</td>' % c
470 for d in link.distance ():
471 e += '<td>%f</td>' % d
473 e = '<tr>%s</tr>' % e
477 e = '<td>%d</td>' % c
478 for s in (link.output_expression_details_string (),
479 link.orphan_details_string (),
480 link.geo_details_string ()):
481 e += "<td>%s</td>" % s
484 e = '<tr>%s</tr>' % e
487 original = self.original_name
490 <title>comparison details for %(original)s</title>
509 def write_html_system_details (self, dir1, dir2, dest_dir):
510 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
512 details = open_write_file (dest_file)
513 details.write (self.html_system_details_string ())
515 ################################################################
523 def compare_signature_files (f1, f2):
524 s1 = read_signature_file (f1)
525 s2 = read_signature_file (f2)
527 return SystemLink (s1, s2).distance ()
529 def paired_files (dir1, dir2, pattern):
531 Search DIR1 and DIR2 for PATTERN.
533 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
537 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
538 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
542 for f in files1.keys ():
549 return (pairs, files2.keys (), missing)
551 class ComparisonData:
553 self.result_dict = {}
558 def compare_trees (self, dir1, dir2):
559 self.compare_directories (dir1, dir2)
561 (root, dirs, files) = os.walk (dir1).next ()
563 d1 = os.path.join (dir1, d)
564 d2 = os.path.join (dir2, d)
566 if os.path.islink (d1) or os.path.islink (d2):
569 if os.path.isdir (d2):
570 self.compare_trees (d1, d2)
572 def compare_directories (self, dir1, dir2):
574 (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
576 self.missing += [(dir1, m) for m in m1]
577 self.added += [(dir2, m) for m in m2]
580 if (inspect_max_count
581 and len (self.file_links) > inspect_max_count):
587 self.compare_files (f1, f2)
589 def compare_files (self, f1, f2):
590 name = os.path.split (f1)[1]
591 name = re.sub ('-[0-9]+.signature', '', name)
595 file_link = self.file_links[name]
597 file_link = FileLink ()
598 self.file_links[name] = file_link
600 file_link.add_file_compare (f1,f2)
602 def write_text_result_page (self, filename, threshold):
603 print 'writing "%s"' % filename
608 out = open_write_file (filename)
610 ## todo: support more scores.
611 results = [(link.distance(), link)
612 for link in self.file_links.values ()]
617 for (score, link) in results:
618 if score > threshold:
619 out.write (link.text_record_string ())
622 out.write ('%d below threshold\n' % len ([1 for s,l in results
623 if threshold >= s > 0.0]))
624 out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
626 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
627 self.write_text_result_page (dest_dir + '/index.txt', threshold)
629 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
630 dir1 = dir1.replace ('//', '/')
631 dir2 = dir2.replace ('//', '/')
633 results = [(link.distance(), link)
634 for link in self.file_links.values ()]
639 old_prefix = os.path.split (dir1)[1]
640 for (score, link) in results:
641 if score <= threshold:
644 link.link_files_for_html (dir1, dir2, dest_dir)
645 link.write_html_system_details (dir1, dir2, dest_dir)
647 html += link.html_record_string (dir1, dir2)
651 <table rules="rows" border bordercolor="blue">
659 </html>''' % locals()
662 below_count =len ([1 for s,l in results
663 if threshold >= s > 0.0])
666 html += ('<p>%d below threshold</p>' % below_count)
668 html += ('<p>%d unchanged</p>'
669 % len ([1 for (s,l) in results if s == 0.0]))
672 dest_file = dest_dir + '/index.html'
673 open_write_file (dest_file).write (html)
675 def print_results (self, threshold):
676 self.write_text_result_page ('', threshold)
678 def compare_trees (dir1, dir2, dest_dir, threshold):
679 data = ComparisonData ()
680 data.compare_trees (dir1, dir2)
681 data.print_results (threshold)
683 if os.path.isdir (dest_dir):
684 system ('rm -rf %s '% dest_dir)
686 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
687 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
689 ################################################################
693 if not os.path.isdir (x):
697 def link_file (x, y):
698 mkdir (os.path.split (y)[0])
702 print 'OSError', x, y, z
705 def open_write_file (x):
706 d = os.path.split (x)[0]
718 def test_paired_files ():
719 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
720 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
723 def test_compare_trees ():
724 system ('rm -rf dir1 dir2')
725 system ('mkdir dir1 dir2')
726 system ('cp 20{-*.signature,.ly,.png} dir1')
727 system ('cp 20{-*.signature,.ly,.png} dir2')
728 system ('cp 20expr{-*.signature,.ly,.png} dir1')
729 system ('cp 19{-*.signature,.ly,.png} dir2/')
730 system ('cp 19{-*.signature,.ly,.png} dir1/')
731 system ('cp 19-1.signature 19-sub-1.signature')
732 system ('cp 19.ly 19-sub.ly')
733 system ('cp 19.png 19-sub.png')
735 system ('cp 20multipage* dir1')
736 system ('cp 20multipage* dir2')
737 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
740 system ('mkdir -p dir1/subdir/ dir2/subdir/')
741 system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
742 system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
743 system ('cp 20grob{-*.signature,.ly,.png} dir2/')
744 system ('cp 20grob{-*.signature,.ly,.png} dir1/')
746 ## introduce differences
747 system ('cp 19-1.signature dir2/20-1.signature')
748 system ('cp 19.png dir2/20.png')
749 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
750 system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
751 system ('cp 20.png dir2/subdir/19-sub.png')
754 system ('cp 19-1.signature dir2/20grob-1.signature')
755 system ('cp 19-1.signature dir2/20grob-2.signature')
757 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
760 def test_basic_compare ():
762 #(set! toplevel-score-handler print-score-with-defaults)
763 #(set! toplevel-music-handler
765 (if (not (eq? (ly:music-property m 'void) #t))
766 (print-score-with-defaults
767 p (scorify-music m p)))))
769 \sourcefilename "my-source.ly"
772 \header { tagline = ##f }
774 \new Staff \relative c {
775 c4^"%(userstring)s" %(extragrob)s
777 \new Staff \relative c {
778 c4^"%(userstring)s" %(extragrob)s
783 dicts = [{ 'papermod' : '',
786 'userstring': 'test' },
787 { 'papermod' : '#(set-global-staff-size 19.5)',
790 'userstring': 'test' },
794 'userstring': 'blabla' },
797 'extragrob': 'r2. \\break c1',
798 'userstring': 'test' },
803 open (d['name'] + '.ly','w').write (ly_template % d)
805 names = [d['name'] for d in dicts]
807 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
811 #(set-default-paper-size "a6")
815 open ('20multipage', 'w').write (multipage_str)
816 open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
817 system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
819 test_compare_signatures (names)
821 def test_compare_signatures (names, timing=False):
832 for t in range (0, times):
833 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
837 print 'elapsed', (time.clock() - t0)/count
843 for (n1, s1) in sigs.items():
844 for (n2, s2) in sigs.items():
845 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
849 print 'elapsed', (time.clock() - t0)/count
851 results = combinations.items ()
856 assert combinations['20-20'] == (0.0,0.0,0.0)
857 assert combinations['20-20expr'][0] > 0.0
858 assert combinations['20-19'][2] < 10.0
859 assert combinations['20-19'][2] > 0.0
863 dir = 'test-output-distance'
865 do_clean = not os.path.exists (dir)
867 print 'test results in ', dir
869 system ('rm -rf ' + dir)
870 system ('mkdir ' + dir)
874 test_basic_compare ()
876 test_compare_trees ()
878 ################################################################
882 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
883 p.usage = 'output-distance.py [options] tree1 tree2'
885 p.add_option ('', '--test-self',
888 help='run test method')
890 p.add_option ('--max-count',
896 help='only analyze COUNT signature pairs')
898 p.add_option ('', '--threshold',
903 help='threshold for geometric distance')
905 (o,a) = p.parse_args ()
915 global inspect_max_count
916 inspect_max_count = o.max_count
918 compare_trees (a[0], a[1], os.path.join (a[1], 'compare-' + a[0]),
921 if __name__ == '__main__':