]> git.donarmstrong.com Git - lilypond.git/blobdiff - buildscripts/output-distance.py
Add scons cruft.
[lilypond.git] / buildscripts / output-distance.py
index bebafe755935243f014c1812ef4f301023a1c33d..92768454dc4c80f5247137aa21386209f2aa46b0 100644 (file)
@@ -17,7 +17,6 @@ INFTY = 1e6
 
 OUTPUT_EXPRESSION_PENALTY = 1
 ORPHAN_GROB_PENALTY = 1
-THRESHOLD = 1.0
 inspect_max_count = 0
 
 def max_distance (x1, x2):
@@ -79,10 +78,10 @@ class GrobSignature:
 
     def __repr__ (self):
         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
-                                                 self.bbox[0][0],
-                                                 self.bbox[0][1],
-                                                 self.bbox[1][0],
-                                                 self.bbox[1][1])
+                                                   self.bbox[0][0],
+                                                   self.bbox[0][1],
+                                                   self.bbox[1][0],
+                                                   self.bbox[1][1])
                                                  
     def axis_centroid (self, axis):
         return apply (sum, self.bbox[axis])  / 2 
@@ -101,9 +100,12 @@ class GrobSignature:
         
     def expression_distance (self, other):
         if self.output_expression == other.output_expression:
-            return 0.0
+            return 0
         else:
-            return OUTPUT_EXPRESSION_PENALTY
+            return 1
+
+################################################################
+# single System.
 
 class SystemSignature:
     def __init__ (self, grob_sigs):
@@ -140,6 +142,9 @@ class SystemSignature:
     def grobs (self):
         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
 
+################################################################
+## comparison of systems.
+
 class SystemLink:
     def __init__ (self, system1, system2):
         self.system1 = system1
@@ -148,6 +153,20 @@ class SystemLink:
         self.link_list_dict = {}
         self.back_link_dict = {}
 
+
+        ## pairs
+        self.orphans = []
+
+        ## pair -> distance
+        self.geo_distances = {}
+
+        ## pairs
+        self.expression_changed = []
+
+        self._geometric_distance = None
+        self._expression_change_count = None
+        self._orphan_count = None
+        
         for g in system1.grobs ():
 
             ## skip empty bboxes.
@@ -160,45 +179,96 @@ class SystemLink:
             self.link_list_dict[closest].append (g)
             self.back_link_dict[g] = closest
 
-    def geometric_distance (self):
-        d = 0.0
+
+    def calc_geometric_distance (self):
+        total = 0.0
         for (g1,g2) in self.back_link_dict.items ():
             if g2:
-                # , scale
-                d += g1.bbox_distance (g2)
+                d = g1.bbox_distance (g2)
+                if d:
+                    self.geo_distances[(g1,g2)] = d
+
+                total += d
 
-        return d
+        self._geometric_distance = total
     
-    def orphan_distance (self):
-        d = 0
-        for (g1,g2) in self.back_link_dict.items ():
+    def calc_orphan_count (self):
+        count = 0
+        for (g1, g2) in self.back_link_dict.items ():
             if g2 == None:
-                d += ORPHAN_GROB_PENALTY
-        return d
+                self.orphans.append ((g1, None))
+                
+                count += 1
+
+        self._orphan_count = count
     
-    def output_exp_distance (self):
+    def calc_output_exp_distance (self):
         d = 0
         for (g1,g2) in self.back_link_dict.items ():
             if g2:
                 d += g1.expression_distance (g2)
 
-        return d
+        self._expression_change_count = d
+
+    def output_expression_details_string (self):
+        return ', '.join ([g1.name for g1 in self.expression_changed])
+    
+    def geo_details_string (self):
+        results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
+        results.sort ()
+        results.reverse ()
+        
+        return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
+
+    def orphan_details_string (self):
+        return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
 
+    def geometric_distance (self):
+        if self._geometric_distance == None:
+            self.calc_geometric_distance ()
+        return self._geometric_distance
+    
+    def orphan_count (self):
+        if self._orphan_count == None:
+            self.calc_orphan_count ()
+            
+        return self._orphan_count
+    
+    def output_expression_change_count (self):
+        if self._expression_change_count == None:
+            self.calc_output_exp_distance ()
+        return self._expression_change_count
+        
     def distance (self):
-        return (self.output_exp_distance (),
-                self.orphan_distance (),
+        return (self.output_expression_change_count (),
+                self.orphan_count (),
                 self.geometric_distance ())
     
 def read_signature_file (name):
     print 'reading', name
-    exp_str = ("[%s]" % open (name).read ())
-    entries = safeeval.safe_eval (exp_str)
+    
+    entries = open (name).read ().split ('\n')
+    def string_to_tup (s):
+        return tuple (map (float, s.split (' '))) 
+
+    def string_to_entry (s):
+        fields = s.split('@')
+        fields[2] = string_to_tup (fields[2])
+        fields[3] = string_to_tup (fields[3])
+
+        return tuple (fields)
+    
+    entries = [string_to_entry (e) for e in entries
+               if e and not e.startswith ('#')]
 
     grob_sigs = [GrobSignature (e) for e in entries]
     sig = SystemSignature (grob_sigs)
     return sig
 
 
+################################################################
+# different systems of a .ly file.
+
 class FileLink:
     def __init__ (self):
         self.original_name = ''
@@ -211,9 +281,13 @@ class FileLink:
 
     def calc_distance (self):
         d = 0.0
+
+        orphan_distance = 0.0
         for l in self.system_links.values ():
             d = max (d, l.geometric_distance ())
-        return d
+            orphan_distance += l.orphan_count ()
+            
+        return d + orphan_distance
 
     def distance (self):
         if type (self._distance) != type (0.0):
@@ -267,10 +341,11 @@ class FileLink:
         self.add_system_link (link, system_index[0])
 
     def link_files_for_html (self, old_dir, new_dir, dest_dir):
-        for ext in ('.png', '.ly'):
+        for ext in ('.png', '.ly', '-page*png'):
             for oldnew in (0,1):
-                link_file (self.base_names[oldnew] + ext, 
-                           dest_dir + '/' + self.base_names[oldnew] + ext)
+                for f in glob.glob (self.base_names[oldnew] + ext):
+                    print f
+                    link_file (f, dest_dir + '/' + f)
 
     def html_record_string (self,  old_dir, new_dir):
         def img_cell (ly, img, name):
@@ -288,12 +363,38 @@ class FileLink:
 </font>
 </td>
 ''' % locals ()
-        
 
-        img_1  = self.base_names[0] + '.png'
-        ly_1  = self.base_names[0] + '.ly'
-        img_2  = self.base_names[1] + '.png'
-        ly_2  = self.base_names[1] + '.ly'
+        def multi_img_cell (ly, imgs, name):
+            if not name:
+                name = 'source'
+            else:
+                name = '<tt>%s</tt>' % name
+
+            imgs_str = '\n'.join (['''<a href="%s">
+<img src="%s" style="border-style: none; max-width: 500px;">
+</a><br>''' % (img, img) 
+                                  for img in imgs])
+
+
+            return '''
+<td align="center">
+%(imgs_str)s
+<font size="-2">(<a href="%(ly)s">%(name)s</a>)
+</font>
+</td>
+''' % locals ()
+
+
+
+        def cell (base, name):
+            pages = glob.glob (base + '-page*.png')
+            
+            if pages:
+                return multi_img_cell (base + '.ly', sorted (pages), name)
+            else:
+                return img_cell (base + '.ly', base + '.png', name)
+            
+
         html_2  = self.base_names[1] + '.html'
         name = self.original_name
         
@@ -308,8 +409,8 @@ class FileLink:
 %s
 </tr>
 ''' % (self.distance (), html_2,
-       img_cell (ly_1, img_1, name), img_cell (ly_2, img_2, name))
-
+       cell (self.base_names[0], name),
+       cell (self.base_names[1], name))
 
         return html_entry
 
@@ -325,8 +426,19 @@ class FileLink:
                 e += '<td>%f</td>' % d
             
             e = '<tr>%s</tr>' % e
+
             html += e
 
+            e = '<td>%d</td>' % c
+            for s in (link.output_expression_details_string (),
+                      link.orphan_details_string (),
+                      link.geo_details_string ()):
+                e += "<td>%s</td>" % s
+
+            
+            e = '<tr>%s</tr>' % e
+            html += e
+            
         original = self.original_name
         html = '''<html>
 <head>
@@ -397,6 +509,7 @@ class ComparisonData:
         self.missing = []
         self.added = []
         self.file_links = {}
+
     def compare_trees (self, dir1, dir2):
         self.compare_directories (dir1, dir2)
         
@@ -441,7 +554,7 @@ class ComparisonData:
 
         file_link.add_file_compare (f1,f2)
 
-    def write_text_result_page (self, filename):
+    def write_text_result_page (self, filename, threshold):
         print 'writing "%s"' % filename
         out = None
         if filename == '':
@@ -457,18 +570,18 @@ class ComparisonData:
 
         
         for (score, link) in results:
-            if score > THRESHOLD:
+            if score > threshold:
                 out.write (link.text_record_string ())
 
         out.write ('\n\n')
         out.write ('%d below threshold\n' % len ([1 for s,l  in results
-                                                    if THRESHOLD >=  s > 0.0]))
+                                                    if threshold >=  s > 0.0]))
         out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
         
-    def create_text_result_page (self, dir1, dir2, dest_dir):
-        self.write_text_result_page (dest_dir + '/index.txt')
+    def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
+        self.write_text_result_page (dest_dir + '/index.txt', threshold)
         
-    def create_html_result_page (self, dir1, dir2, dest_dir):
+    def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
         dir1 = dir1.replace ('//', '/')
         dir2 = dir2.replace ('//', '/')
         
@@ -480,11 +593,11 @@ class ComparisonData:
         html = ''
         old_prefix = os.path.split (dir1)[1]
         for (score, link) in results:
-            if score <= THRESHOLD:
+            if score <= threshold:
                 continue
 
-            link.write_html_system_details (dir1, dir2, dest_dir)
             link.link_files_for_html (dir1, dir2, dest_dir) 
+            link.write_html_system_details (dir1, dir2, dest_dir)
             html += link.html_record_string (dir1, dir2)
 
 
@@ -492,8 +605,8 @@ class ComparisonData:
 <table rules="rows" border bordercolor="blue">
 <tr>
 <th>distance</th>
-<th>old</th>
-<th>new</th>
+<th>%(dir1)s</th>
+<th>%(dir2)s</th>
 </tr>
 %(html)s
 </table>
@@ -501,7 +614,7 @@ class ComparisonData:
 
         html += ('<p>')
         below_count  =len ([1 for s,l  in results
-                         if THRESHOLD >=  s > 0.0])
+                            if threshold >=  s > 0.0])
 
         if below_count:
             html += ('<p>%d below threshold</p>' % below_count)
@@ -513,20 +626,19 @@ class ComparisonData:
         dest_file = dest_dir + '/index.html'
         open_write_file (dest_file).write (html)
         
-    def print_results (self):
-        self.write_text_result_page ('')
-        
+    def print_results (self, threshold):
+        self.write_text_result_page ('', threshold)
 
-def compare_trees (dir1, dir2, dest_dir):
+def compare_trees (dir1, dir2, dest_dir, threshold):
     data = ComparisonData ()
     data.compare_trees (dir1, dir2)
-    data.print_results ()
+    data.print_results (threshold)
 
     if os.path.isdir (dest_dir):
         system ('rm -rf %s '% dest_dir)
 
-    data.create_html_result_page (dir1, dir2, dest_dir)
-    data.create_text_result_page (dir1, dir2, dest_dir)
+    data.create_html_result_page (dir1, dir2, dest_dir, threshold)
+    data.create_text_result_page (dir1, dir2, dest_dir, threshold)
     
 ################################################################
 # TESTING
@@ -538,7 +650,11 @@ def mkdir (x):
 
 def link_file (x, y):
     mkdir (os.path.split (y)[0])
-    os.link (x, y)
+    try:
+        os.link (x, y)
+    except OSError, z:
+        print 'OSError', x, y, z
+        raise OSError
     
 def open_write_file (x):
     d = os.path.split (x)[0]
@@ -569,6 +685,11 @@ def test_compare_trees ():
     system ('cp 19-1.signature 19-sub-1.signature')
     system ('cp 19.ly 19-sub.ly')
     system ('cp 19.png 19-sub.png')
+
+    system ('cp 20multipage* dir1')
+    system ('cp 20multipage* dir2')
+    system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
+
     
     system ('mkdir -p dir1/subdir/ dir2/subdir/')
     system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
@@ -584,20 +705,22 @@ def test_compare_trees ():
     system ('cp 19-1.signature dir2/20grob-1.signature')
     system ('cp 19-1.signature dir2/20grob-2.signature')
 
-    compare_trees ('dir1', 'dir2', 'compare-dir1dir2')
+    compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
 
 
 def test_basic_compare ():
-    ly_template = r"""#(set! toplevel-score-handler print-score-with-defaults)
-#(set! toplevel-music-handler
- (lambda (p m)
- (if (not (eq? (ly:music-property m 'void) #t))
-    (print-score-with-defaults
-    p (scorify-music m p)))))
+    ly_template = r"""
+#(set! toplevel-score-handler print-score-with-defaults)
+ #(set! toplevel-music-handler
+  (lambda (p m)
+  (if (not (eq? (ly:music-property m 'void) #t))
+     (print-score-with-defaults
+     p (scorify-music m p)))))
 
 \sourcefilename "my-source.ly"
-
 %(papermod)s
+\header { tagline = ##f } 
 <<
 \new Staff \relative c {
   c4^"%(userstring)s" %(extragrob)s
@@ -623,8 +746,8 @@ def test_basic_compare ():
              { 'papermod' : '',
                'name' : '20grob',
                'extragrob': 'r2. \\break c1',
-               'userstring': 'test' }
-
+               'userstring': 'test' },
+                
              ]
 
     for d in dicts:
@@ -634,11 +757,47 @@ def test_basic_compare ():
     
     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
     
-    sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
+
+    multipage_str = r'''
+    #(set-default-paper-size "a6")
+    {c1 \pageBreak c1 }
+    '''
+
+    open ('20multipage', 'w').write (multipage_str)
+    open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
+    system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
+    test_compare_signatures (names)
+    
+def test_compare_signatures (names, timing=False):
+
+    import time
+
+    times = 1
+    if timing:
+        times = 100
+
+    t0 = time.clock ()
+
+    count = 0
+    for t in range (0, times):
+        sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
+        count += 1
+
+    if timing:
+        print 'elapsed', (time.clock() - t0)/count
+
+
+    t0 = time.clock ()
+    count = 0
     combinations = {}
     for (n1, s1) in sigs.items():
         for (n2, s2) in sigs.items():
             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
+            count += 1
+
+    if timing:
+        print 'elapsed', (time.clock() - t0)/count
 
     results = combinations.items ()
     results.sort ()
@@ -652,9 +811,10 @@ def test_basic_compare ():
 
 
 def run_tests ():
-    do_clean = 0
     dir = 'output-distance-test'
 
+    do_clean = not os.path.exists (dir)
+
     print 'test results in ', dir
     if do_clean:
         system ('rm -rf ' + dir)
@@ -673,10 +833,11 @@ def main ():
     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
     p.usage = 'output-distance.py [options] tree1 tree2'
     
-    p.add_option ('', '--test',
+    p.add_option ('', '--test-self',
                   dest="run_test",
                   action="store_true",
                   help='run test method')
+    
     p.add_option ('--max-count',
                   dest="max_count",
                   metavar="COUNT",
@@ -684,7 +845,14 @@ def main ():
                   default=0, 
                   action="store",
                   help='only analyze COUNT signature pairs')
+
+    p.add_option ('', '--threshold',
+                  dest="threshold",
+                  default=0.3,
+                  action="store",
+                  type="float",
+                  help='threshold for geometric distance')
+
     (o,a) = p.parse_args ()
 
     if o.run_test:
@@ -698,7 +866,8 @@ def main ():
     global inspect_max_count
     inspect_max_count = o.max_count
 
-    compare_trees (a[0], a[1], a[1] + '/' +  a[0])
+    compare_trees (a[0], a[1], os.path.join (a[1],  'compare-' +  a[0]),
+                   o.threshold)
 
 if __name__ == '__main__':
     main()