6 ## so we can call directly as buildscripts/output-distance.py
7 sys.path.insert (0, '../python')
16 OUTPUT_EXPRESSION_PENALTY = 100
17 ORPHAN_GROB_PENALTY = 1000
19 def max_distance (x1, x2):
22 for (p,q) in zip (x1, x2):
23 dist = max (abs (p-q), dist)
28 empty_interval = (INFTY, -INFTY)
29 empty_bbox = (empty_interval, empty_interval)
31 def interval_length (i):
32 return max (i[1]-i[0], 0)
34 def interval_union (i1, i2):
35 return (min (i1[0], i2[0]),
38 def interval_intersect (i1, i2):
39 return (max (i1[0], i2[0]),
42 def bbox_union (b1, b2):
43 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
44 interval_union (b2[Y_AXIS], b2[Y_AXIS]))
46 def bbox_intersection (b1, b2):
47 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
48 interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
51 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
53 def bbox_diameter (b):
54 return max (interval_length (b[X_AXIS]),
55 interval_length (b[Y_AXIS]))
58 def difference_area (a, b):
59 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
62 def __init__ (self, exp_list):
63 (self.name, self.origin, bbox_x,
64 bbox_y, self.output_expression) = tuple (exp_list)
66 self.bbox = (bbox_x, bbox_y)
67 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
70 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
76 def axis_centroid (self, axis):
77 return apply (sum, self.bbox[axis]) / 2
79 def centroid_distance (self, other, scale):
80 return max_distance (self.centroid, other.centroid) / scale
82 def bbox_distance (self, other):
83 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
86 return (difference_area (self.bbox, other.bbox) +
87 difference_area (other.bbox, self.bbox)) / divisor
91 def expression_distance (self, other):
92 if self.output_expression == other.output_expression:
95 return OUTPUT_EXPRESSION_PENALTY
97 def distance(self, other, max_distance):
98 return (self.expression_distance (other)
99 + self.centroid_distance (other, max_distance)
100 + self.bbox_distance (other))
102 class SystemSignature:
103 def __init__ (self, grob_sigs):
106 val = d.setdefault (g.name, [])
110 self.set_all_bbox (grob_sigs)
112 def set_all_bbox (self, grobs):
113 self.bbox = empty_bbox
115 self.bbox = bbox_union (g.bbox, self.bbox)
117 def closest (self, grob_name, centroid):
121 grobs = self.grob_dict[grob_name]
124 d = max_distance (g.centroid, centroid)
135 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
138 def __init__ (self, system1, system2):
139 self.system1 = system1
140 self.system2 = system2
142 self.link_list_dict = {}
143 self.back_link_dict = {}
145 for g in system1.grobs ():
146 closest = system2.closest (g.name, g.centroid)
148 self.link_list_dict.setdefault (closest, [])
149 self.link_list_dict[closest].append (g)
150 self.back_link_dict[g] = closest
155 scale = max (bbox_diameter (self.system1.bbox),
156 bbox_diameter (self.system2.bbox))
158 for (g1,g2) in self.back_link_dict.items ():
160 d += ORPHAN_GROB_PENALTY
162 d += g1.distance (g2, scale)
164 for (g1,g2s) in self.link_list_dict.items ():
166 d += ORPHAN_GROB_PENALTY
170 ################################################################
177 def read_signature_file (name):
178 print 'reading', name
179 exp_str = ("[%s]" % open (name).read ())
180 entries = safeeval.safe_eval (exp_str)
182 grob_sigs = [GrobSignature (e) for e in entries]
183 sig = SystemSignature (grob_sigs)
187 def compare_signature_files (f1, f2):
188 s1 = read_signature_file (f1)
189 s2 = read_signature_file (f2)
191 return SystemLink (s1, s2).distance ()
193 def paired_files (dir1, dir2, pattern):
195 Search DIR1 and DIR2 for PATTERN.
197 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
201 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
202 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
206 for f in files1.keys ():
213 return (pairs, files2.keys (), missing)
215 class ComparisonData:
217 self.result_dict = {}
221 def compare_trees (self, dir1, dir2):
222 self.compare_directories (dir1, dir2)
224 (root, dirs, files) = os.walk (dir1).next ()
226 d1 = os.path.join (dir1, d)
227 d2 = os.path.join (dir2, d)
229 if os.path.islink (d1) or os.path.islink (d2):
232 if os.path.isdir (d2):
233 self.compare_trees (d1, d2)
235 def compare_directories (self, dir1, dir2):
237 (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
239 self.missing += [(dir1, m) for m in m1]
240 self.added += [(dir2, m) for m in m2]
245 distance = compare_signature_files (f1, f2)
246 self.result_dict[f2] = (distance, f1)
248 def create_text_result_page (self, dir1, dir2):
249 self.write_text_result_page (dir2 + '/' + os.path.split (dir1)[1] + '.txt')
251 def write_text_result_page (self, filename):
252 print 'writing "%s"' % filename
257 out = open (filename, 'w')
259 results = [(score, oldfile, file) for (file, (score, oldfile)) in self.result_dict.items ()]
263 for (s, oldfile, f) in results:
264 out.write ('%-30f %-20s\n' % (s, f))
266 for (dir, file) in self.missing:
267 out.write ('%10s%-20s %s\n' % ('', 'missing',os.path.join (dir, file)))
268 for (dir, file) in self.added:
269 out.write ('%20s%-10s %s\n' % ('','added', os.path.join (dir, file)))
271 def print_results (self):
272 self.write_text_result_page ('')
274 def create_html_result_page (self, dir1, dir2):
275 dir1 = dir1.replace ('//', '/')
276 dir2 = dir2.replace ('//', '/')
280 results = [(score, oldfile, file) for (file, (score, oldfile)) in self.result_dict.items ()
281 if score > threshold]
287 old_prefix = os.path.split (dir1)[1]
289 dest_dir = os.path.join (dir2, old_prefix)
290 shutil.rmtree (dest_dir, ignore_errors=True)
292 for (score, oldfile, newfile) in results:
294 old_base = re.sub ("-[0-9]+.signature", '', oldfile)
295 old_name = os.path.split (old_base)[1]
296 new_base = re.sub ("-[0-9]+.signature", '', newfile)
298 for ext in 'png', 'ly':
299 src_file = old_base + '.' + ext
301 if os.path.exists (src_file):
302 shutil.copy2 (src_file, dest_dir)
304 print "warning: can't find", src_file
306 img_1 = os.path.join (old_prefix, old_name + '.png')
307 ly_1 = os.path.join (old_prefix, old_name + '.ly')
309 img_2 = new_base.replace (dir2, '') + '.png'
310 img_2 = re.sub ("^/*", '', img_2)
312 ly_2 = img_2.replace ('.png','.ly')
314 def img_cell (ly, img):
318 <img src="%(img)s" style="border-style: none; max-width: 500px;">
320 <font size="-2">(<a href="%(ly)s">source</a>)
334 ''' % (score, img_cell (ly_1, img_1), img_cell (ly_2, img_2))
348 </html>''' % locals()
350 open (os.path.join (dir2, old_prefix) + '.html', 'w').write (html)
354 def compare_trees (dir1, dir2):
355 data = ComparisonData ()
356 data.compare_trees (dir1, dir2)
357 data.print_results ()
358 data.create_html_result_page (dir1, dir2)
359 # data.create_text_result_page (dir1, dir2)
361 ################################################################
372 def test_paired_files ():
373 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
374 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
377 def test_compare_trees ():
378 system ('rm -rf dir1 dir2')
379 system ('mkdir dir1 dir2')
380 system ('cp 20{-0.signature,.ly,.png} dir1')
381 system ('cp 20{-0.signature,.ly,.png} dir2')
382 system ('cp 20expr{-0.signature,.ly,.png} dir1')
383 system ('cp 19{-0.signature,.ly,.png} dir2/')
384 system ('cp 19{-0.signature,.ly,.png} dir1/')
385 system ('cp 20grob{-0.signature,.ly,.png} dir2/')
387 ## introduce difference
388 system ('cp 19-0.signature dir2/20-0.signature')
390 compare_trees ('dir1', 'dir2')
393 def test_basic_compare ():
394 ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
395 #(set! toplevel-music-handler
397 (if (not (eq? (ly:music-property m 'void) #t))
398 (print-score-with-defaults
399 p (scorify-music m p)))))
404 c^"%(userstring)s" %(extragrob)s
408 dicts = [{ 'papermod' : '',
411 'userstring': 'test' },
412 { 'papermod' : '#(set-global-staff-size 19.5)',
415 'userstring': 'test' },
419 'userstring': 'blabla' },
423 'userstring': 'test' }]
426 open (d['name'] + '.ly','w').write (ly_template % d)
428 names = [d['name'] for d in dicts]
430 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
432 sigs = dict ((n, read_signature_file ('%s-0.signature' % n)) for n in names)
434 for (n1, s1) in sigs.items():
435 for (n2, s2) in sigs.items():
436 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
438 results = combinations.items ()
443 assert combinations['20-20'] == 0.0
444 assert combinations['20-20expr'] > 50.0
445 assert combinations['20-19'] < 10.0
449 sa = read_signature_file (a)
450 sb = read_signature_file (b)
451 link = SystemLink (sa, sb)
452 print link.distance()
457 dir = 'output-distance-test'
459 print 'test results in ', dir
461 system ('rm -rf ' + dir)
462 system ('mkdir ' + dir)
466 test_basic_compare ()
467 test_compare_trees ()
469 ################################################################
473 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
474 p.usage = 'output-distance.py [options] tree1 tree2'
476 p.add_option ('', '--test',
479 help='run test method')
481 (o,a) = p.parse_args ()
491 compare_trees (a[0], a[1])
493 if __name__ == '__main__':