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
23 def max_distance (x1, x2):
26 for (p,q) in zip (x1, x2):
27 dist = max (abs (p-q), dist)
32 empty_interval = (INFTY, -INFTY)
33 empty_bbox = (empty_interval, empty_interval)
35 def interval_is_empty (i):
38 def interval_length (i):
39 return max (i[1]-i[0], 0)
41 def interval_union (i1, i2):
42 return (min (i1[0], i2[0]),
45 def interval_intersect (i1, i2):
46 return (max (i1[0], i2[0]),
49 def bbox_is_empty (b):
50 return (interval_is_empty (b[0])
51 or interval_is_empty (b[1]))
53 def bbox_union (b1, b2):
54 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
55 interval_union (b2[Y_AXIS], b2[Y_AXIS]))
57 def bbox_intersection (b1, b2):
58 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
59 interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
62 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
64 def bbox_diameter (b):
65 return max (interval_length (b[X_AXIS]),
66 interval_length (b[Y_AXIS]))
69 def difference_area (a, b):
70 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
73 def __init__ (self, exp_list):
74 (self.name, self.origin, bbox_x,
75 bbox_y, self.output_expression) = tuple (exp_list)
77 self.bbox = (bbox_x, bbox_y)
78 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
81 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
87 def axis_centroid (self, axis):
88 return apply (sum, self.bbox[axis]) / 2
90 def centroid_distance (self, other, scale):
91 return max_distance (self.centroid, other.centroid) / scale
93 def bbox_distance (self, other):
94 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
97 return (difference_area (self.bbox, other.bbox) +
98 difference_area (other.bbox, self.bbox)) / divisor
102 def expression_distance (self, other):
103 if self.output_expression == other.output_expression:
106 return OUTPUT_EXPRESSION_PENALTY
108 class SystemSignature:
109 def __init__ (self, grob_sigs):
112 val = d.setdefault (g.name, [])
116 self.set_all_bbox (grob_sigs)
118 def set_all_bbox (self, grobs):
119 self.bbox = empty_bbox
121 self.bbox = bbox_union (g.bbox, self.bbox)
123 def closest (self, grob_name, centroid):
127 grobs = self.grob_dict[grob_name]
130 d = max_distance (g.centroid, centroid)
141 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
144 def __init__ (self, system1, system2):
145 self.system1 = system1
146 self.system2 = system2
148 self.link_list_dict = {}
149 self.back_link_dict = {}
151 for g in system1.grobs ():
153 ## skip empty bboxes.
154 if bbox_is_empty (g.bbox):
157 closest = system2.closest (g.name, g.centroid)
159 self.link_list_dict.setdefault (closest, [])
160 self.link_list_dict[closest].append (g)
161 self.back_link_dict[g] = closest
163 def geometric_distance (self):
165 for (g1,g2) in self.back_link_dict.items ():
168 d += g1.bbox_distance (g2)
172 def orphan_distance (self):
174 for (g1,g2) in self.back_link_dict.items ():
176 d += ORPHAN_GROB_PENALTY
179 def output_exp_distance (self):
181 for (g1,g2) in self.back_link_dict.items ():
183 d += g1.expression_distance (g2)
188 return (self.output_exp_distance (),
189 self.orphan_distance (),
190 self.geometric_distance ())
192 def read_signature_file (name):
193 print 'reading', name
194 exp_str = ("[%s]" % open (name).read ())
195 entries = safeeval.safe_eval (exp_str)
197 grob_sigs = [GrobSignature (e) for e in entries]
198 sig = SystemSignature (grob_sigs)
204 self.original_name = ''
205 self.base_names = ('','')
206 self.system_links = {}
207 self._distance = None
209 def add_system_link (self, link, number):
210 self.system_links[number] = link
212 def calc_distance (self):
214 for l in self.system_links.values ():
215 d = max (d, l.geometric_distance ())
219 if type (self._distance) != type (0.0):
220 return self.calc_distance ()
222 return self._distance
224 def text_record_string (self):
225 return '%-30f %-20s\n' % (self.distance (),
228 def source_file (self):
229 for ext in ('.ly', '.ly.txt'):
230 if os.path.exists (self.base_names[1] + ext):
231 return self.base_names[1] + ext
234 def add_file_compare (self, f1, f2):
237 def note_system_index (m):
238 system_index.append (int (m.group (1)))
241 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
242 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
244 self.base_names = (os.path.normpath (base1),
245 os.path.normpath (base2))
247 def note_original (match):
248 self.original_name = match.group (1)
251 if not self.original_name:
252 self.original_name = os.path.split (base1)[1]
254 ## ugh: drop the .ly.txt
255 for ext in ('.ly', '.ly.txt'):
257 re.sub (r'\\sourcefilename "([^"]+)"',
258 note_original, open (base1 + ext).read ())
262 s1 = read_signature_file (f1)
263 s2 = read_signature_file (f2)
265 link = SystemLink (s1, s2)
267 self.add_system_link (link, system_index[0])
269 def link_files_for_html (self, old_dir, new_dir, dest_dir):
270 for ext in ('.png', '.ly'):
272 link_file (self.base_names[oldnew] + ext,
273 dest_dir + '/' + self.base_names[oldnew] + ext)
275 def html_record_string (self, old_dir, new_dir):
276 def img_cell (ly, img, name):
280 name = '<tt>%s</tt>' % name
285 <img src="%(img)s" style="border-style: none; max-width: 500px;">
287 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
293 img_1 = self.base_names[0] + '.png'
294 ly_1 = self.base_names[0] + '.ly'
295 img_2 = self.base_names[1] + '.png'
296 ly_2 = self.base_names[1] + '.ly'
297 html_2 = self.base_names[1] + '.html'
298 name = self.original_name
304 (<a href="%s">details</a>)
310 ''' % (self.distance (), html_2,
311 img_cell (ly_1, img_1, name), img_cell (ly_2, img_2, name))
317 def html_system_details_string (self):
318 systems = self.system_links.items ()
322 for (c, link) in systems:
323 e = '<td>%d</td>' % c
324 for d in link.distance ():
325 e += '<td>%f</td>' % d
327 e = '<tr>%s</tr>' % e
330 original = self.original_name
333 <title>comparison details for %(original)s</title>
352 def write_html_system_details (self, dir1, dir2, dest_dir):
353 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
355 details = open_write_file (dest_file)
356 details.write (self.html_system_details_string ())
358 ################################################################
366 def compare_signature_files (f1, f2):
367 s1 = read_signature_file (f1)
368 s2 = read_signature_file (f2)
370 return SystemLink (s1, s2).distance ()
372 def paired_files (dir1, dir2, pattern):
374 Search DIR1 and DIR2 for PATTERN.
376 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
380 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
381 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
385 for f in files1.keys ():
392 return (pairs, files2.keys (), missing)
394 class ComparisonData:
396 self.result_dict = {}
400 def compare_trees (self, dir1, dir2):
401 self.compare_directories (dir1, dir2)
403 (root, dirs, files) = os.walk (dir1).next ()
405 d1 = os.path.join (dir1, d)
406 d2 = os.path.join (dir2, d)
408 if os.path.islink (d1) or os.path.islink (d2):
411 if os.path.isdir (d2):
412 self.compare_trees (d1, d2)
414 def compare_directories (self, dir1, dir2):
416 (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
418 self.missing += [(dir1, m) for m in m1]
419 self.added += [(dir2, m) for m in m2]
422 if (inspect_max_count
423 and len (self.file_links) > inspect_max_count):
429 self.compare_files (f1, f2)
431 def compare_files (self, f1, f2):
432 name = os.path.split (f1)[1]
433 name = re.sub ('-[0-9]+.signature', '', name)
437 file_link = self.file_links[name]
439 file_link = FileLink ()
440 self.file_links[name] = file_link
442 file_link.add_file_compare (f1,f2)
444 def write_text_result_page (self, filename):
445 print 'writing "%s"' % filename
450 out = open_write_file (filename)
452 ## todo: support more scores.
453 results = [(link.distance(), link)
454 for link in self.file_links.values ()]
459 for (score, link) in results:
460 if score > THRESHOLD:
461 out.write (link.text_record_string ())
464 out.write ('%d below threshold\n' % len ([1 for s,l in results
465 if THRESHOLD >= s > 0.0]))
466 out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
468 def create_text_result_page (self, dir1, dir2, dest_dir):
469 self.write_text_result_page (dest_dir + '/index.txt')
471 def create_html_result_page (self, dir1, dir2, dest_dir):
472 dir1 = dir1.replace ('//', '/')
473 dir2 = dir2.replace ('//', '/')
475 results = [(link.distance(), link)
476 for link in self.file_links.values ()]
481 old_prefix = os.path.split (dir1)[1]
482 for (score, link) in results:
483 if score <= THRESHOLD:
486 link.write_html_system_details (dir1, dir2, dest_dir)
487 link.link_files_for_html (dir1, dir2, dest_dir)
488 html += link.html_record_string (dir1, dir2)
492 <table rules="rows" border bordercolor="blue">
500 </html>''' % locals()
503 below_count =len ([1 for s,l in results
504 if THRESHOLD >= s > 0.0])
507 html += ('<p>%d below threshold</p>' % below_count)
509 html += ('<p>%d unchanged</p>'
510 % len ([1 for (s,l) in results if s == 0.0]))
513 dest_file = dest_dir + '/index.html'
514 open_write_file (dest_file).write (html)
516 def print_results (self):
517 self.write_text_result_page ('')
520 def compare_trees (dir1, dir2, dest_dir):
521 data = ComparisonData ()
522 data.compare_trees (dir1, dir2)
523 data.print_results ()
525 if os.path.isdir (dest_dir):
526 system ('rm -rf %s '% dest_dir)
528 data.create_html_result_page (dir1, dir2, dest_dir)
529 data.create_text_result_page (dir1, dir2, dest_dir)
531 ################################################################
535 if not os.path.isdir (x):
539 def link_file (x, y):
540 mkdir (os.path.split (y)[0])
543 def open_write_file (x):
544 d = os.path.split (x)[0]
556 def test_paired_files ():
557 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
558 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
561 def test_compare_trees ():
562 system ('rm -rf dir1 dir2')
563 system ('mkdir dir1 dir2')
564 system ('cp 20{-*.signature,.ly,.png} dir1')
565 system ('cp 20{-*.signature,.ly,.png} dir2')
566 system ('cp 20expr{-*.signature,.ly,.png} dir1')
567 system ('cp 19{-*.signature,.ly,.png} dir2/')
568 system ('cp 19{-*.signature,.ly,.png} dir1/')
569 system ('cp 19-1.signature 19-sub-1.signature')
570 system ('cp 19.ly 19-sub.ly')
571 system ('cp 19.png 19-sub.png')
573 system ('mkdir -p dir1/subdir/ dir2/subdir/')
574 system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
575 system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
576 system ('cp 20grob{-*.signature,.ly,.png} dir2/')
577 system ('cp 20grob{-*.signature,.ly,.png} dir1/')
579 ## introduce differences
580 system ('cp 19-1.signature dir2/20-1.signature')
581 system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
584 system ('cp 19-1.signature dir2/20grob-1.signature')
585 system ('cp 19-1.signature dir2/20grob-2.signature')
587 compare_trees ('dir1', 'dir2', 'compare-dir1dir2')
590 def test_basic_compare ():
591 ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
592 #(set! toplevel-music-handler
594 (if (not (eq? (ly:music-property m 'void) #t))
595 (print-score-with-defaults
596 p (scorify-music m p)))))
598 \sourcefilename "my-source.ly"
602 \new Staff \relative c {
603 c4^"%(userstring)s" %(extragrob)s
605 \new Staff \relative c {
606 c4^"%(userstring)s" %(extragrob)s
611 dicts = [{ 'papermod' : '',
614 'userstring': 'test' },
615 { 'papermod' : '#(set-global-staff-size 19.5)',
618 'userstring': 'test' },
622 'userstring': 'blabla' },
625 'extragrob': 'r2. \\break c1',
626 'userstring': 'test' }
631 open (d['name'] + '.ly','w').write (ly_template % d)
633 names = [d['name'] for d in dicts]
635 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
637 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
639 for (n1, s1) in sigs.items():
640 for (n2, s2) in sigs.items():
641 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
643 results = combinations.items ()
648 assert combinations['20-20'] == (0.0,0.0,0.0)
649 assert combinations['20-20expr'][0] > 0.0
650 assert combinations['20-19'][2] < 10.0
651 assert combinations['20-19'][2] > 0.0
656 dir = 'output-distance-test'
658 print 'test results in ', dir
660 system ('rm -rf ' + dir)
661 system ('mkdir ' + dir)
665 test_basic_compare ()
667 test_compare_trees ()
669 ################################################################
673 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
674 p.usage = 'output-distance.py [options] tree1 tree2'
676 p.add_option ('', '--test',
679 help='run test method')
680 p.add_option ('--max-count',
686 help='only analyze COUNT signature pairs')
688 (o,a) = p.parse_args ()
698 global inspect_max_count
699 inspect_max_count = o.max_count
701 compare_trees (a[0], a[1], a[1] + '/' + a[0])
703 if __name__ == '__main__':