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:
105 return OUTPUT_EXPRESSION_PENALTY
107 class SystemSignature:
108 def __init__ (self, grob_sigs):
111 val = d.setdefault (g.name, [])
115 self.set_all_bbox (grob_sigs)
117 def set_all_bbox (self, grobs):
118 self.bbox = empty_bbox
120 self.bbox = bbox_union (g.bbox, self.bbox)
122 def closest (self, grob_name, centroid):
126 grobs = self.grob_dict[grob_name]
129 d = max_distance (g.centroid, centroid)
140 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
143 def __init__ (self, system1, system2):
144 self.system1 = system1
145 self.system2 = system2
147 self.link_list_dict = {}
148 self.back_link_dict = {}
150 for g in system1.grobs ():
152 ## skip empty bboxes.
153 if bbox_is_empty (g.bbox):
156 closest = system2.closest (g.name, g.centroid)
158 self.link_list_dict.setdefault (closest, [])
159 self.link_list_dict[closest].append (g)
160 self.back_link_dict[g] = closest
162 def geometric_distance (self):
164 for (g1,g2) in self.back_link_dict.items ():
167 d += g1.bbox_distance (g2)
171 def orphan_distance (self):
173 for (g1,g2) in self.back_link_dict.items ():
175 d += ORPHAN_GROB_PENALTY
178 def output_exp_distance (self):
180 for (g1,g2) in self.back_link_dict.items ():
182 d += g1.expression_distance (g2)
187 return (self.output_exp_distance (),
188 self.orphan_distance (),
189 self.geometric_distance ())
191 def read_signature_file (name):
192 print 'reading', name
193 exp_str = ("[%s]" % open (name).read ())
194 entries = safeeval.safe_eval (exp_str)
196 grob_sigs = [GrobSignature (e) for e in entries]
197 sig = SystemSignature (grob_sigs)
203 self.original_name = ''
204 self.base_names = ('','')
205 self.system_links = {}
206 self._distance = None
208 def add_system_link (self, link, number):
209 self.system_links[number] = link
211 def calc_distance (self):
213 for l in self.system_links.values ():
214 d = max (d, l.geometric_distance ())
218 if type (self._distance) != type (0.0):
219 return self.calc_distance ()
221 return self._distance
223 def text_record_string (self):
224 return '%-30f %-20s\n' % (self.distance (),
227 def source_file (self):
228 for ext in ('.ly', '.ly.txt'):
229 if os.path.exists (self.base_names[1] + ext):
230 return self.base_names[1] + ext
233 def add_file_compare (self, f1, f2):
236 def note_system_index (m):
237 system_index.append (int (m.group (1)))
240 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
241 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
243 self.base_names = (os.path.normpath (base1),
244 os.path.normpath (base2))
246 def note_original (match):
247 self.original_name = match.group (1)
250 if not self.original_name:
251 self.original_name = os.path.split (base1)[1]
253 ## ugh: drop the .ly.txt
254 for ext in ('.ly', '.ly.txt'):
256 re.sub (r'\\sourcefilename "([^"]+)"',
257 note_original, open (base1 + ext).read ())
261 s1 = read_signature_file (f1)
262 s2 = read_signature_file (f2)
264 link = SystemLink (s1, s2)
266 self.add_system_link (link, system_index[0])
268 def link_files_for_html (self, old_dir, new_dir, dest_dir):
269 for ext in ('.png', '.ly'):
271 link_file (self.base_names[oldnew] + ext,
272 dest_dir + '/' + self.base_names[oldnew] + ext)
274 def html_record_string (self, old_dir, new_dir):
275 def img_cell (ly, img, name):
279 name = '<tt>%s</tt>' % name
284 <img src="%(img)s" style="border-style: none; max-width: 500px;">
286 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
292 img_1 = self.base_names[0] + '.png'
293 ly_1 = self.base_names[0] + '.ly'
294 img_2 = self.base_names[1] + '.png'
295 ly_2 = self.base_names[1] + '.ly'
296 html_2 = self.base_names[1] + '.html'
297 name = self.original_name
303 (<a href="%s">details</a>)
309 ''' % (self.distance (), html_2,
310 img_cell (ly_1, img_1, name), img_cell (ly_2, img_2, name))
316 def html_system_details_string (self):
317 systems = self.system_links.items ()
321 for (c, link) in systems:
322 e = '<td>%d</td>' % c
323 for d in link.distance ():
324 e += '<td>%f</td>' % d
326 e = '<tr>%s</tr>' % e
329 original = self.original_name
332 <title>comparison details for %(original)s</title>
351 def write_html_system_details (self, dir1, dir2, dest_dir):
352 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
354 details = open_write_file (dest_file)
355 details.write (self.html_system_details_string ())
357 ################################################################
365 def compare_signature_files (f1, f2):
366 s1 = read_signature_file (f1)
367 s2 = read_signature_file (f2)
369 return SystemLink (s1, s2).distance ()
371 def paired_files (dir1, dir2, pattern):
373 Search DIR1 and DIR2 for PATTERN.
375 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
379 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
380 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
384 for f in files1.keys ():
391 return (pairs, files2.keys (), missing)
393 class ComparisonData:
395 self.result_dict = {}
399 def compare_trees (self, dir1, dir2):
400 self.compare_directories (dir1, dir2)
402 (root, dirs, files) = os.walk (dir1).next ()
404 d1 = os.path.join (dir1, d)
405 d2 = os.path.join (dir2, d)
407 if os.path.islink (d1) or os.path.islink (d2):
410 if os.path.isdir (d2):
411 self.compare_trees (d1, d2)
413 def compare_directories (self, dir1, dir2):
415 (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
417 self.missing += [(dir1, m) for m in m1]
418 self.added += [(dir2, m) for m in m2]
421 if len (self.file_links) > 10:
426 self.compare_files (f1, f2)
428 def compare_files (self, f1, f2):
429 name = os.path.split (f1)[1]
430 name = re.sub ('-[0-9]+.signature', '', name)
434 file_link = self.file_links[name]
436 file_link = FileLink ()
437 self.file_links[name] = file_link
439 file_link.add_file_compare (f1,f2)
441 def write_text_result_page (self, filename):
442 print 'writing "%s"' % filename
447 out = open_write_file (filename)
449 ## todo: support more scores.
450 results = [(link.distance(), link)
451 for link in self.file_links.values ()]
456 for (score, link) in results:
457 if score > THRESHOLD:
458 out.write (link.text_record_string ())
461 out.write ('%d below threshold\n' % len ([1 for s,l in results
462 if THRESHOLD >= s > 0.0]))
463 out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
465 def create_text_result_page (self, dir1, dir2, dest_dir):
466 self.write_text_result_page (dest_dir + '/index.txt')
468 def create_html_result_page (self, dir1, dir2, dest_dir):
469 dir1 = dir1.replace ('//', '/')
470 dir2 = dir2.replace ('//', '/')
472 results = [(link.distance(), link)
473 for link in self.file_links.values ()]
478 old_prefix = os.path.split (dir1)[1]
479 for (score, link) in results:
480 if score <= THRESHOLD:
483 link.write_html_system_details (dir1, dir2, dest_dir)
484 link.link_files_for_html (dir1, dir2, dest_dir)
485 html += link.html_record_string (dir1, dir2)
489 <table rules="rows" border bordercolor="blue">
497 </html>''' % locals()
500 below_count =len ([1 for s,l in results
501 if THRESHOLD >= s > 0.0])
504 html += ('<p>%d below threshold</p>' % below_count)
506 html += ('<p>%d unchanged</p>'
507 % len ([1 for (s,l) in results if s == 0.0]))
510 dest_file = dest_dir + '/index.html'
511 open_write_file (dest_file).write (html)
513 def print_results (self):
514 self.write_text_result_page ('')
517 def compare_trees (dir1, dir2, dest_dir):
518 data = ComparisonData ()
519 data.compare_trees (dir1, dir2)
520 data.print_results ()
522 if os.path.isdir (dest_dir):
523 system ('rm -rf %s '% dest_dir)
525 data.create_html_result_page (dir1, dir2, dest_dir)
526 data.create_text_result_page (dir1, dir2, dest_dir)
528 ################################################################
532 if not os.path.isdir (x):
536 def link_file (x, y):
537 mkdir (os.path.split (y)[0])
540 def open_write_file (x):
541 d = os.path.split (x)[0]
553 def test_paired_files ():
554 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
555 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
558 def test_compare_trees ():
559 system ('rm -rf dir1 dir2')
560 system ('mkdir dir1 dir2')
561 system ('cp 20{-*.signature,.ly,.png} dir1')
562 system ('cp 20{-*.signature,.ly,.png} dir2')
563 system ('cp 20expr{-*.signature,.ly,.png} dir1')
564 system ('cp 19{-*.signature,.ly,.png} dir2/')
565 system ('cp 19{-*.signature,.ly,.png} dir1/')
566 system ('cp 19-1.signature 19-sub-1.signature')
567 system ('cp 19.ly 19-sub.ly')
568 system ('cp 19.png 19-sub.png')
570 system ('mkdir -p dir1/subdir/ dir2/subdir/')
571 system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
572 system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
573 system ('cp 20grob{-*.signature,.ly,.png} dir2/')
574 system ('cp 20grob{-*.signature,.ly,.png} dir1/')
576 ## introduce differences
577 system ('cp 19-1.signature dir2/20-1.signature')
580 system ('cp 19-1.signature dir2/20grob-1.signature')
581 system ('cp 19-1.signature dir2/20grob-2.signature')
583 compare_trees ('dir1', 'dir2', 'compare-dir1dir2')
586 def test_basic_compare ():
587 ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
588 #(set! toplevel-music-handler
590 (if (not (eq? (ly:music-property m 'void) #t))
591 (print-score-with-defaults
592 p (scorify-music m p)))))
594 \sourcefilename "my-source.ly"
598 \new Staff \relative c {
599 c4^"%(userstring)s" %(extragrob)s
601 \new Staff \relative c {
602 c4^"%(userstring)s" %(extragrob)s
607 dicts = [{ 'papermod' : '',
610 'userstring': 'test' },
611 { 'papermod' : '#(set-global-staff-size 19.5)',
614 'userstring': 'test' },
618 'userstring': 'blabla' },
621 'extragrob': 'r2. \\break c1',
622 'userstring': 'test' }
627 open (d['name'] + '.ly','w').write (ly_template % d)
629 names = [d['name'] for d in dicts]
631 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
633 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
635 for (n1, s1) in sigs.items():
636 for (n2, s2) in sigs.items():
637 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
639 results = combinations.items ()
644 assert combinations['20-20'] == (0.0,0.0,0.0)
645 assert combinations['20-20expr'][0] > 0.0
646 assert combinations['20-19'][2] < 10.0
647 assert combinations['20-19'][2] > 0.0
652 dir = 'output-distance-test'
654 print 'test results in ', dir
656 system ('rm -rf ' + dir)
657 system ('mkdir ' + dir)
661 test_basic_compare ()
663 test_compare_trees ()
665 ################################################################
669 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
670 p.usage = 'output-distance.py [options] tree1 tree2'
672 p.add_option ('', '--test',
675 help='run test method')
677 (o,a) = p.parse_args ()
687 compare_trees (a[0], a[1])
689 if __name__ == '__main__':