]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
* lily/ledger-line-engraver.cc (acknowledge_staff_symbol): be more
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4
5 import safeeval
6
7
8 X_AXIS = 0
9 Y_AXIS = 1
10 INFTY = 1e6
11
12 OUTPUT_EXPRESSION_PENALTY = 100
13 ORPHAN_GROB_PENALTY = 1000
14
15 def max_distance (x1, x2):
16     dist = 0.0
17
18     for (p,q) in zip (x1, x2):
19         dist = max (abs (p-q), dist)
20         
21     return dist
22
23
24 empty_interval = (INFTY, -INFTY)
25 empty_bbox = (empty_interval, empty_interval)
26
27 def interval_length (i):
28     return max (i[1]-i[0], 0) 
29     
30 def interval_union (i1, i2):
31     return (min (i1[0], i2[0]),
32             max (i1[1], i2[1]))
33
34 def interval_intersect (i1, i2):
35     return (max (i1[0], i2[0]),
36             min (i1[1], i2[1]))
37
38 def bbox_union (b1, b2):
39     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
40             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
41             
42 def bbox_intersection (b1, b2):
43     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
44             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
45
46 def bbox_area (b):
47     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
48
49 def bbox_diameter (b):
50     return max (interval_length (b[X_AXIS]),
51                 interval_length (b[Y_AXIS]))
52                 
53
54 def difference_area (a, b):
55     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
56
57 class GrobSignature:
58     def __init__ (self, exp_list):
59         (self.name, self.origin, bbox_x,
60          bbox_y, self.output_expression) = tuple (exp_list)
61         
62         self.bbox = (bbox_x, bbox_y)
63         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
64
65     def __repr__ (self):
66         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
67                                                  self.bbox[0][0],
68                                                  self.bbox[0][1],
69                                                  self.bbox[1][0],
70                                                  self.bbox[1][1])
71                                                  
72     def axis_centroid (self, axis):
73         return apply (sum, self.bbox[axis])  / 2 
74     
75     def centroid_distance (self, other, scale):
76         return max_distance (self.centroid, other.centroid) / scale 
77         
78     def bbox_distance (self, other):
79         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
80
81         if divisor:
82             return (difference_area (self.bbox, other.bbox) +
83                     difference_area (other.bbox, self.bbox)) / divisor
84         else:
85             return 0.0
86         
87     def expression_distance (self, other):
88         if self.output_expression == other.output_expression:
89             return 0.0
90         else:
91             return OUTPUT_EXPRESSION_PENALTY
92
93     def distance(self, other, max_distance):
94         return (self.expression_distance (other)
95                 + self.centroid_distance (other, max_distance)
96                 + self.bbox_distance (other))
97             
98 class SystemSignature:
99     def __init__ (self, grob_sigs):
100         d = {}
101         for g in grob_sigs:
102             val = d.setdefault (g.name, [])
103             val += [g]
104
105         self.grob_dict = d
106         self.set_all_bbox (grob_sigs)
107
108     def set_all_bbox (self, grobs):
109         self.bbox = empty_bbox
110         for g in grobs:
111             self.bbox = bbox_union (g.bbox, self.bbox)
112
113     def closest (self, grob_name, centroid):
114         min_d = INFTY
115         min_g = None
116         try:
117             grobs = self.grob_dict[grob_name]
118
119             for g in grobs:
120                 d = max_distance (g.centroid, centroid)
121                 if d < min_d:
122                     min_d = d
123                     min_g = g
124
125
126             return min_g
127
128         except KeyError:
129             return None
130     def grobs (self):
131         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
132
133 class SystemLink:
134     def __init__ (self, system1, system2):
135         self.system1 = system1
136         self.system2 = system2
137         
138         self.link_list_dict = {}
139         self.back_link_dict = {}
140
141         for g in system1.grobs ():
142             closest = system2.closest (g.name, g.centroid)
143             
144             self.link_list_dict.setdefault (closest, [])
145             self.link_list_dict[closest].append (g)
146             self.back_link_dict[g] = closest
147
148     def distance (self):
149         d = 0.0
150
151         scale = max (bbox_diameter (self.system1.bbox),
152                      bbox_diameter (self.system2.bbox))
153                                       
154         for (g1,g2) in self.back_link_dict.items ():
155             if g2 == None:
156                 d += ORPHAN_GROB_PENALTY
157             else:
158                 d += g1.distance (g2, scale)
159
160         for (g1,g2s) in self.link_list_dict.items ():
161             if len (g2s) != 1:
162                 d += ORPHAN_GROB_PENALTY
163
164         return d
165
166 ################################################################
167 # Files/directories
168
169 import glob
170
171 def read_signature_file (name):
172     print 'reading', name
173     exp_str = ("[%s]" % open (name).read ())
174     entries = safeeval.safe_eval (exp_str)
175
176     grob_sigs = [GrobSignature (e) for e in entries]
177     sig = SystemSignature (grob_sigs)
178     return sig
179
180
181 def compare_signature_files (f1, f2):
182     s1 = read_signature_file (f1)
183     s2 = read_signature_file (f2)
184     
185     return SystemLink (s1, s2).distance ()
186     
187     
188
189 def paired_files (dir1, dir2, pattern):
190     """
191     Search DIR1 and DIR2 for PATTERN.
192
193     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
194
195     """
196     
197     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
198     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
199
200     pairs = []
201     missing = []
202     for f in files1.keys ():
203         try:
204             files2.pop (f)
205             pairs.append (f)
206         except KeyError:
207             missing.append (f)
208
209     return (pairs, files2.keys (), missing)
210     
211 class ComparisonData:
212     def __init__ (self):
213         self.result_dict = {}
214         self.missing = []
215         self.added = []
216         
217     def compare_trees (self, dir1, dir2):
218         self.compare_directories (dir1, dir2)
219         
220         (root, files, dirs) = os.walk (dir1).next ()
221         for d in dirs:
222             d1 = os.path.join (dir1, d)
223             d2 = os.path.join (dir2, d)
224             
225             if os.path.isdir (d2):
226                 self.compare_trees (d1, d2)
227     
228     def compare_directories (self, dir1, dir2):
229         
230         (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
231
232         self.missing += [(dir1, m) for m in m1] 
233         self.added += [(dir2, m) for m in m2] 
234
235         for p in paired:
236             f = dir1 +  '/' +p
237             d = compare_signature_files (f, dir2 +  '/' +p)
238             self.result_dict[f] = d
239         
240     
241     def print_results (self):
242         results = [(score, file) for (file, score) in self.result_dict.items ()]  
243         results.sort ()
244         results.reverse ()
245
246         for (s, f) in results:
247             print '%30s %6f' % (f,s)
248
249         for (dir, file) in self.missing:
250             print '%-20s %s' % ('missing',os.path.join (dir, file))
251         for (dir, file) in self.added:
252             print '%10s%-10s %s' % ('','added', os.path.join (dir, file))
253         
254
255 def compare_trees (dir1, dir2):
256     data =  ComparisonData ()
257     data.compare_trees (dir1, dir2)
258     data.print_results ()
259     
260 ################################################################
261 # TESTING
262
263 import os
264 def system (x):
265     
266     print 'invoking', x
267     stat = os.system (x)
268     assert stat == 0
269
270 def test_paired_files ():
271     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
272                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
273                   
274     
275 def test_compare_trees ():
276     system ('rm -rf dir1 dir2')
277     system ('mkdir dir1 dir2')
278     system ('cp 20-0.signature dir1')
279     system ('cp 20expr-0.signature dir1')
280     system ('cp 19-0.signature dir2/20-0.signature')
281     system ('cp 19-0.signature dir2/')
282     system ('cp 19-0.signature dir1/')
283     system ('cp 20grob-0.signature dir2/')
284
285     compare_trees ('dir1', 'dir2')
286     
287 def test_basic_compare ():
288     ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
289 #(set! toplevel-music-handler
290  (lambda (p m)
291  (if (not (eq? (ly:music-property m 'void) #t))
292     (print-score-with-defaults
293     p (scorify-music m p)))))
294
295 #(ly:set-option 'point-and-click)
296
297
298
299 %(papermod)s
300
301 \relative c {
302   c^"%(userstring)s" %(extragrob)s
303   }
304 """
305
306
307     dicts = [{ 'papermod' : '',
308                'name' : '20',
309                'extragrob': '',
310                'userstring': 'test' },
311              { 'papermod' : '#(set-global-staff-size 19.5)',
312                'name' : '19',
313                'extragrob': '',
314                'userstring': 'test' },
315              { 'papermod' : '',
316                'name' : '20expr',
317                'extragrob': '',
318                'userstring': 'blabla' },
319              { 'papermod' : '',
320                'name' : '20grob',
321                'extragrob': 'c4',
322                'userstring': 'test' }]
323
324
325     for d in dicts:
326         open (d['name'] + '.ly','w').write (ly_template % d)
327         
328     names = [d['name'] for d in dicts]
329     
330     system ('lilypond -ddump-signatures -b eps ' + ' '.join (names))
331     
332     sigs = dict ((n, read_signature_file ('%s-0.signature' % n)) for n in names)
333
334     combinations = {}
335     for (n1, s1) in sigs.items():
336         for (n2, s2) in sigs.items():
337             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
338             
339
340     results =   combinations.items ()
341     results.sort ()
342     for k,v in results:
343         print '%-20s' % k, v
344
345     assert combinations['20-20'] == 0.0
346     assert combinations['20-20expr'] > 50.0
347     assert combinations['20-19'] < 10.0
348
349 def test_sigs (a,b):
350     sa = read_signature_file (a)
351     sb = read_signature_file (b)
352     link = SystemLink (sa, sb)
353     print link.distance()
354
355
356 def run_tests ():
357     dir = 'output-distance-test'
358
359     print 'test results in ', dir
360     system ('rm -rf ' + dir)
361     system ('mkdir ' + dir)
362     os.chdir (dir)
363
364     test_compare_trees ()
365     test_basic_compare ()
366     
367 ################################################################
368 #
369
370 def main ():
371     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
372     p.usage ('output-distance.py [options] tree1 tree2')
373     
374     p.add_option ('', '--test',
375                   dest="run_test",
376                   help='run test method')
377
378     (o,a) = p.parse_args ()
379
380     if len (a) != 2:
381         p.usage()
382         sys.exit (2)
383
384     if o.run_test:
385         run_tests ()
386         sys.exit (0)
387
388     compare_trees (a[0], a[1])
389
390 if __name__ == '__main__':
391     main()
392