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
249 exp_str = ("[%s]" % open (name).read ())
250 entries = safeeval.safe_eval (exp_str)
252 grob_sigs = [GrobSignature (e) for e in entries]
253 sig = SystemSignature (grob_sigs)
257 ################################################################
258 # different systems of a .ly file.
262 self.original_name = ''
263 self.base_names = ('','')
264 self.system_links = {}
265 self._distance = None
267 def add_system_link (self, link, number):
268 self.system_links[number] = link
270 def calc_distance (self):
272 for l in self.system_links.values ():
273 d = max (d, l.geometric_distance ())
277 if type (self._distance) != type (0.0):
278 return self.calc_distance ()
280 return self._distance
282 def text_record_string (self):
283 return '%-30f %-20s\n' % (self.distance (),
286 def source_file (self):
287 for ext in ('.ly', '.ly.txt'):
288 if os.path.exists (self.base_names[1] + ext):
289 return self.base_names[1] + ext
292 def add_file_compare (self, f1, f2):
295 def note_system_index (m):
296 system_index.append (int (m.group (1)))
299 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
300 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
302 self.base_names = (os.path.normpath (base1),
303 os.path.normpath (base2))
305 def note_original (match):
306 self.original_name = match.group (1)
309 if not self.original_name:
310 self.original_name = os.path.split (base1)[1]
312 ## ugh: drop the .ly.txt
313 for ext in ('.ly', '.ly.txt'):
315 re.sub (r'\\sourcefilename "([^"]+)"',
316 note_original, open (base1 + ext).read ())
320 s1 = read_signature_file (f1)
321 s2 = read_signature_file (f2)
323 link = SystemLink (s1, s2)
325 self.add_system_link (link, system_index[0])
327 def link_files_for_html (self, old_dir, new_dir, dest_dir):
328 for ext in ('.png', '.ly'):
330 link_file (self.base_names[oldnew] + ext,
331 dest_dir + '/' + self.base_names[oldnew] + ext)
333 def html_record_string (self, old_dir, new_dir):
334 def img_cell (ly, img, name):
338 name = '<tt>%s</tt>' % name
343 <img src="%(img)s" style="border-style: none; max-width: 500px;">
345 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
351 img_1 = self.base_names[0] + '.png'
352 ly_1 = self.base_names[0] + '.ly'
353 img_2 = self.base_names[1] + '.png'
354 ly_2 = self.base_names[1] + '.ly'
355 html_2 = self.base_names[1] + '.html'
356 name = self.original_name
362 (<a href="%s">details</a>)
368 ''' % (self.distance (), html_2,
369 img_cell (ly_1, img_1, name), img_cell (ly_2, img_2, name))
375 def html_system_details_string (self):
376 systems = self.system_links.items ()
380 for (c, link) in systems:
381 e = '<td>%d</td>' % c
382 for d in link.distance ():
383 e += '<td>%f</td>' % d
385 e = '<tr>%s</tr>' % e
389 e = '<td>%d</td>' % c
390 for s in (link.output_expression_details_string (),
391 link.orphan_details_string (),
392 link.geo_details_string ()):
393 e += "<td>%s</td>" % s
396 e = '<tr>%s</tr>' % e
399 original = self.original_name
402 <title>comparison details for %(original)s</title>
421 def write_html_system_details (self, dir1, dir2, dest_dir):
422 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
424 details = open_write_file (dest_file)
425 details.write (self.html_system_details_string ())
427 ################################################################
435 def compare_signature_files (f1, f2):
436 s1 = read_signature_file (f1)
437 s2 = read_signature_file (f2)
439 return SystemLink (s1, s2).distance ()
441 def paired_files (dir1, dir2, pattern):
443 Search DIR1 and DIR2 for PATTERN.
445 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
449 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
450 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
454 for f in files1.keys ():
461 return (pairs, files2.keys (), missing)
463 class ComparisonData:
465 self.result_dict = {}
470 def compare_trees (self, dir1, dir2):
471 self.compare_directories (dir1, dir2)
473 (root, dirs, files) = os.walk (dir1).next ()
475 d1 = os.path.join (dir1, d)
476 d2 = os.path.join (dir2, d)
478 if os.path.islink (d1) or os.path.islink (d2):
481 if os.path.isdir (d2):
482 self.compare_trees (d1, d2)
484 def compare_directories (self, dir1, dir2):
486 (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
488 self.missing += [(dir1, m) for m in m1]
489 self.added += [(dir2, m) for m in m2]
492 if (inspect_max_count
493 and len (self.file_links) > inspect_max_count):
499 self.compare_files (f1, f2)
501 def compare_files (self, f1, f2):
502 name = os.path.split (f1)[1]
503 name = re.sub ('-[0-9]+.signature', '', name)
507 file_link = self.file_links[name]
509 file_link = FileLink ()
510 self.file_links[name] = file_link
512 file_link.add_file_compare (f1,f2)
514 def write_text_result_page (self, filename, threshold):
515 print 'writing "%s"' % filename
520 out = open_write_file (filename)
522 ## todo: support more scores.
523 results = [(link.distance(), link)
524 for link in self.file_links.values ()]
529 for (score, link) in results:
530 if score > threshold:
531 out.write (link.text_record_string ())
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]))
538 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
539 self.write_text_result_page (dest_dir + '/index.txt', threshold)
541 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
542 dir1 = dir1.replace ('//', '/')
543 dir2 = dir2.replace ('//', '/')
545 results = [(link.distance(), link)
546 for link in self.file_links.values ()]
551 old_prefix = os.path.split (dir1)[1]
552 for (score, link) in results:
553 if score <= threshold:
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)
562 <table rules="rows" border bordercolor="blue">
570 </html>''' % locals()
573 below_count =len ([1 for s,l in results
574 if threshold >= s > 0.0])
577 html += ('<p>%d below threshold</p>' % below_count)
579 html += ('<p>%d unchanged</p>'
580 % len ([1 for (s,l) in results if s == 0.0]))
583 dest_file = dest_dir + '/index.html'
584 open_write_file (dest_file).write (html)
586 def print_results (self, threshold):
587 self.write_text_result_page ('', threshold)
589 def compare_trees (dir1, dir2, dest_dir, threshold):
590 data = ComparisonData ()
591 data.compare_trees (dir1, dir2)
592 data.print_results (threshold)
594 if os.path.isdir (dest_dir):
595 system ('rm -rf %s '% dest_dir)
597 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
598 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
600 ################################################################
604 if not os.path.isdir (x):
608 def link_file (x, y):
609 mkdir (os.path.split (y)[0])
612 def open_write_file (x):
613 d = os.path.split (x)[0]
625 def test_paired_files ():
626 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
627 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
630 def test_compare_trees ():
631 system ('rm -rf dir1 dir2')
632 system ('mkdir dir1 dir2')
633 system ('cp 20{-*.signature,.ly,.png} dir1')
634 system ('cp 20{-*.signature,.ly,.png} dir2')
635 system ('cp 20expr{-*.signature,.ly,.png} dir1')
636 system ('cp 19{-*.signature,.ly,.png} dir2/')
637 system ('cp 19{-*.signature,.ly,.png} dir1/')
638 system ('cp 19-1.signature 19-sub-1.signature')
639 system ('cp 19.ly 19-sub.ly')
640 system ('cp 19.png 19-sub.png')
642 system ('mkdir -p dir1/subdir/ dir2/subdir/')
643 system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
644 system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
645 system ('cp 20grob{-*.signature,.ly,.png} dir2/')
646 system ('cp 20grob{-*.signature,.ly,.png} dir1/')
648 ## introduce differences
649 system ('cp 19-1.signature dir2/20-1.signature')
650 system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
653 system ('cp 19-1.signature dir2/20grob-1.signature')
654 system ('cp 19-1.signature dir2/20grob-2.signature')
656 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
659 def test_basic_compare ():
660 ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
661 #(set! toplevel-music-handler
663 (if (not (eq? (ly:music-property m 'void) #t))
664 (print-score-with-defaults
665 p (scorify-music m p)))))
667 \sourcefilename "my-source.ly"
671 \new Staff \relative c {
672 c4^"%(userstring)s" %(extragrob)s
674 \new Staff \relative c {
675 c4^"%(userstring)s" %(extragrob)s
680 dicts = [{ 'papermod' : '',
683 'userstring': 'test' },
684 { 'papermod' : '#(set-global-staff-size 19.5)',
687 'userstring': 'test' },
691 'userstring': 'blabla' },
694 'extragrob': 'r2. \\break c1',
695 'userstring': 'test' }
700 open (d['name'] + '.ly','w').write (ly_template % d)
702 names = [d['name'] for d in dicts]
704 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
706 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
708 for (n1, s1) in sigs.items():
709 for (n2, s2) in sigs.items():
710 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
712 results = combinations.items ()
717 assert combinations['20-20'] == (0.0,0.0,0.0)
718 assert combinations['20-20expr'][0] > 0.0
719 assert combinations['20-19'][2] < 10.0
720 assert combinations['20-19'][2] > 0.0
724 dir = 'output-distance-test'
726 do_clean = not os.path.exists (dir)
728 print 'test results in ', dir
730 system ('rm -rf ' + dir)
731 system ('mkdir ' + dir)
735 test_basic_compare ()
737 test_compare_trees ()
739 ################################################################
743 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
744 p.usage = 'output-distance.py [options] tree1 tree2'
746 p.add_option ('', '--test-self',
749 help='run test method')
750 p.add_option ('--max-count',
756 help='only analyze COUNT signature pairs')
759 p.add_option ('', '--threshold',
764 help='threshold for geometric distance')
766 (o,a) = p.parse_args ()
776 global inspect_max_count
777 inspect_max_count = o.max_count
779 compare_trees (a[0], a[1], os.path.join (a[1], 'compare-' + a[0]),
782 if __name__ == '__main__':