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:
293 old_base = re.sub ("-[0-9]+.signature", '', os.path.split (oldfile)[1])
294 new_base = re.sub ("-[0-9]+.signature", '', newfile)
296 for ext in 'png', 'ly':
297 shutil.copy2 (old_base + '.' + ext, dest_dir)
299 img_1 = os.path.join (old_prefix, old_base + '.png')
300 ly_1 = os.path.join (old_prefix, old_base + '.ly')
302 img_2 = new_base.replace (dir2, '') + '.png'
303 img_2 = re.sub ("^/*", '', img_2)
305 ly_2 = img_2.replace ('.png','.ly')
307 def img_cell (ly, img):
311 <img src="%(img)s" style="border-style: none; max-width: 500px;">
313 <font size="-2">(<a href="%(ly)s">source</a>)
327 ''' % (score, img_cell (ly_1, img_1), img_cell (ly_2, img_2))
341 </html>''' % locals()
343 open (os.path.join (dir2, old_prefix) + '.html', 'w').write (html)
347 def compare_trees (dir1, dir2):
348 data = ComparisonData ()
349 data.compare_trees (dir1, dir2)
350 data.print_results ()
351 data.create_html_result_page (dir1, dir2)
352 data.create_text_result_page (dir1, dir2)
354 ################################################################
365 def test_paired_files ():
366 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
367 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
370 def test_compare_trees ():
371 system ('rm -rf dir1 dir2')
372 system ('mkdir dir1 dir2')
373 system ('cp 20{-0.signature,.ly,.png} dir1')
374 system ('cp 20{-0.signature,.ly,.png} dir2')
375 system ('cp 20expr{-0.signature,.ly,.png} dir1')
376 system ('cp 19{-0.signature,.ly,.png} dir2/')
377 system ('cp 19{-0.signature,.ly,.png} dir1/')
378 system ('cp 20grob{-0.signature,.ly,.png} dir2/')
380 ## introduce difference
381 system ('cp 19-0.signature dir2/20-0.signature')
383 compare_trees ('dir1', 'dir2')
386 def test_basic_compare ():
387 ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
388 #(set! toplevel-music-handler
390 (if (not (eq? (ly:music-property m 'void) #t))
391 (print-score-with-defaults
392 p (scorify-music m p)))))
397 c^"%(userstring)s" %(extragrob)s
401 dicts = [{ 'papermod' : '',
404 'userstring': 'test' },
405 { 'papermod' : '#(set-global-staff-size 19.5)',
408 'userstring': 'test' },
412 'userstring': 'blabla' },
416 'userstring': 'test' }]
419 open (d['name'] + '.ly','w').write (ly_template % d)
421 names = [d['name'] for d in dicts]
423 system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
425 sigs = dict ((n, read_signature_file ('%s-0.signature' % n)) for n in names)
427 for (n1, s1) in sigs.items():
428 for (n2, s2) in sigs.items():
429 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
431 results = combinations.items ()
436 assert combinations['20-20'] == 0.0
437 assert combinations['20-20expr'] > 50.0
438 assert combinations['20-19'] < 10.0
442 sa = read_signature_file (a)
443 sb = read_signature_file (b)
444 link = SystemLink (sa, sb)
445 print link.distance()
450 dir = 'output-distance-test'
452 print 'test results in ', dir
454 system ('rm -rf ' + dir)
455 system ('mkdir ' + dir)
459 test_basic_compare ()
460 test_compare_trees ()
462 ################################################################
466 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
467 p.usage = 'output-distance.py [options] tree1 tree2'
469 p.add_option ('', '--test',
472 help='run test method')
474 (o,a) = p.parse_args ()
484 compare_trees (a[0], a[1])
486 if __name__ == '__main__':