]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
further tweaks in html output.
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4 import os
5 import math
6
7 ## so we can call directly as buildscripts/output-distance.py
8 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
9 sys.path.insert (0, me_path + '/../python/')
10
11
12 import safeeval
13
14
15 X_AXIS = 0
16 Y_AXIS = 1
17 INFTY = 1e6
18
19 OUTPUT_EXPRESSION_PENALTY = 1
20 ORPHAN_GROB_PENALTY = 1
21 options = None
22
23 def shorten_string (s):
24     threshold = 15 
25     if len (s) > 2*threshold:
26         s = s[:threshold] + '..' + s[-threshold:]
27     return s
28
29 def max_distance (x1, x2):
30     dist = 0.0
31
32     for (p,q) in zip (x1, x2):
33         dist = max (abs (p-q), dist)
34         
35     return dist
36
37
38 empty_interval = (INFTY, -INFTY)
39 empty_bbox = (empty_interval, empty_interval)
40
41 def interval_is_empty (i):
42     return i[0] > i[1]
43
44 def interval_length (i):
45     return max (i[1]-i[0], 0) 
46     
47 def interval_union (i1, i2):
48     return (min (i1[0], i2[0]),
49             max (i1[1], i2[1]))
50
51 def interval_intersect (i1, i2):
52     return (max (i1[0], i2[0]),
53             min (i1[1], i2[1]))
54
55 def bbox_is_empty (b):
56     return (interval_is_empty (b[0])
57             or interval_is_empty (b[1]))
58
59 def bbox_union (b1, b2):
60     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
61             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
62             
63 def bbox_intersection (b1, b2):
64     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
65             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
66
67 def bbox_area (b):
68     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
69
70 def bbox_diameter (b):
71     return max (interval_length (b[X_AXIS]),
72                 interval_length (b[Y_AXIS]))
73                 
74
75 def difference_area (a, b):
76     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
77
78 class GrobSignature:
79     def __init__ (self, exp_list):
80         (self.name, self.origin, bbox_x,
81          bbox_y, self.output_expression) = tuple (exp_list)
82         
83         self.bbox = (bbox_x, bbox_y)
84         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
85
86     def __repr__ (self):
87         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
88                                                    self.bbox[0][0],
89                                                    self.bbox[0][1],
90                                                    self.bbox[1][0],
91                                                    self.bbox[1][1])
92                                                  
93     def axis_centroid (self, axis):
94         return apply (sum, self.bbox[axis])  / 2 
95     
96     def centroid_distance (self, other, scale):
97         return max_distance (self.centroid, other.centroid) / scale 
98         
99     def bbox_distance (self, other):
100         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
101
102         if divisor:
103             return (difference_area (self.bbox, other.bbox) +
104                     difference_area (other.bbox, self.bbox)) / divisor
105         else:
106             return 0.0
107         
108     def expression_distance (self, other):
109         if self.output_expression == other.output_expression:
110             return 0
111         else:
112             return 1
113
114 ################################################################
115 # single System.
116
117 class SystemSignature:
118     def __init__ (self, grob_sigs):
119         d = {}
120         for g in grob_sigs:
121             val = d.setdefault (g.name, [])
122             val += [g]
123
124         self.grob_dict = d
125         self.set_all_bbox (grob_sigs)
126
127     def set_all_bbox (self, grobs):
128         self.bbox = empty_bbox
129         for g in grobs:
130             self.bbox = bbox_union (g.bbox, self.bbox)
131
132     def closest (self, grob_name, centroid):
133         min_d = INFTY
134         min_g = None
135         try:
136             grobs = self.grob_dict[grob_name]
137
138             for g in grobs:
139                 d = max_distance (g.centroid, centroid)
140                 if d < min_d:
141                     min_d = d
142                     min_g = g
143
144
145             return min_g
146
147         except KeyError:
148             return None
149     def grobs (self):
150         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
151
152 ################################################################
153 ## comparison of systems.
154
155 class SystemLink:
156     def __init__ (self, system1, system2):
157         self.system1 = system1
158         self.system2 = system2
159         
160         self.link_list_dict = {}
161         self.back_link_dict = {}
162
163
164         ## pairs
165         self.orphans = []
166
167         ## pair -> distance
168         self.geo_distances = {}
169
170         ## pairs
171         self.expression_changed = []
172
173         self._geometric_distance = None
174         self._expression_change_count = None
175         self._orphan_count = None
176         
177         for g in system1.grobs ():
178
179             ## skip empty bboxes.
180             if bbox_is_empty (g.bbox):
181                 continue
182             
183             closest = system2.closest (g.name, g.centroid)
184             
185             self.link_list_dict.setdefault (closest, [])
186             self.link_list_dict[closest].append (g)
187             self.back_link_dict[g] = closest
188
189
190     def calc_geometric_distance (self):
191         total = 0.0
192         for (g1,g2) in self.back_link_dict.items ():
193             if g2:
194                 d = g1.bbox_distance (g2)
195                 if d:
196                     self.geo_distances[(g1,g2)] = d
197
198                 total += d
199
200         self._geometric_distance = total
201     
202     def calc_orphan_count (self):
203         count = 0
204         for (g1, g2) in self.back_link_dict.items ():
205             if g2 == None:
206                 self.orphans.append ((g1, None))
207                 
208                 count += 1
209
210         self._orphan_count = count
211     
212     def calc_output_exp_distance (self):
213         d = 0
214         for (g1,g2) in self.back_link_dict.items ():
215             if g2:
216                 d += g1.expression_distance (g2)
217
218         self._expression_change_count = d
219
220     def output_expression_details_string (self):
221         return ', '.join ([g1.name for g1 in self.expression_changed])
222     
223     def geo_details_string (self):
224         results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
225         results.sort ()
226         results.reverse ()
227         
228         return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
229
230     def orphan_details_string (self):
231         return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
232
233     def geometric_distance (self):
234         if self._geometric_distance == None:
235             self.calc_geometric_distance ()
236         return self._geometric_distance
237     
238     def orphan_count (self):
239         if self._orphan_count == None:
240             self.calc_orphan_count ()
241             
242         return self._orphan_count
243     
244     def output_expression_change_count (self):
245         if self._expression_change_count == None:
246             self.calc_output_exp_distance ()
247         return self._expression_change_count
248         
249     def distance (self):
250         return (self.output_expression_change_count (),
251                 self.orphan_count (),
252                 self.geometric_distance ())
253     
254 def read_signature_file (name):
255     print 'reading', name
256     
257     entries = open (name).read ().split ('\n')
258     def string_to_tup (s):
259         return tuple (map (float, s.split (' '))) 
260
261     def string_to_entry (s):
262         fields = s.split('@')
263         fields[2] = string_to_tup (fields[2])
264         fields[3] = string_to_tup (fields[3])
265
266         return tuple (fields)
267     
268     entries = [string_to_entry (e) for e in entries
269                if e and not e.startswith ('#')]
270
271     grob_sigs = [GrobSignature (e) for e in entries]
272     sig = SystemSignature (grob_sigs)
273     return sig
274
275
276 ################################################################
277 # different systems of a .ly file.
278 def read_pipe (c):
279     print 'pipe' , c
280     return os.popen (c).read ()
281
282 def system (c):
283     print 'system' , c
284     s = os.system (c)
285     if s :
286         raise Exception ("failed")
287     return
288
289 def compare_png_images (old, new, dir):
290     def png_dims (f):
291         m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
292         
293         return tuple (map (int, m.groups ()))
294
295     dest = os.path.join (dir, new.replace ('.png', '.compare.jpeg'))
296     try:
297         dims1 = png_dims (old)
298         dims2 = png_dims (new)
299     except AttributeError:
300         ## hmmm. what to do?
301         system ('touch %(dest)s' % locals ())
302         return
303     
304     dims = (min (dims1[0], dims2[0]),
305             min (dims1[1], dims2[1]))
306
307     system ('convert -depth 8 -crop %dx%d+0+0 %s crop1.png' % (dims + (old,)))
308     system ('convert -depth 8 -crop %dx%d+0+0 %s crop2.png' % (dims + (new,)))
309
310     system ('compare -depth 8 crop1.png crop2.png diff.png')
311
312     system ("convert  -depth 8 diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity'    matte.png")
313
314     system ("composite -quality 65 matte.png %(new)s %(dest)s" % locals ())
315
316 class FileLink:
317     def __init__ (self):
318         self._distance = None
319
320     def text_record_string (self):
321         return '%-30f %-20s\n' % (self.distance (),
322                                   self.name ())
323     def calc_distance (self):
324         return 0.0
325
326     def distance (self):
327         if self._distance == None:
328            self._distance = self.calc_distance ()
329
330         return self._distance
331     
332     def name (self):
333         return '<undefined>'
334     
335     def link_files_for_html (self, old_dir, new_dir, dest_dir):
336         pass
337
338     def write_html_system_details (self, dir1, dir2, dest_dir):
339         pass
340         
341     def html_record_string (self,  old_dir, new_dir):
342         return ''
343
344 class FileCompareLink (FileLink):
345     def __init__ (self, f1, f2):
346         FileLink.__init__ (self)
347         self.files = (f1, f2)
348         self.contents = (self.get_content (self.files[0]),
349                          self.get_content (self.files[1]))
350         
351     def link_files_for_html (self, old_dir, new_dir, dest_dir):
352         for f in self.files:
353             link_file (f, os.path.join (dest_dir, f))
354
355     def name (self):
356         name = os.path.basename (self.files[0])
357         name = os.path.splitext (name)[0]
358         return name
359         
360     def calc_distance (self):
361         ## todo: could use import MIDI to pinpoint
362         ## what & where changed.
363
364         if self.contents[0] == self.contents[1]:
365             return 0.0
366         else:
367             return 100.0;
368         
369     def html_record_string (self, d1, d2):
370         (dist, f1, f2) = (self.distance(),) + self.files
371         b1 = os.path.basename (f1)
372         b2 = os.path.basename (f2)
373         
374         return '''<tr>
375 <td>
376 %(dist)f
377 </td>
378 <td><a href="%(f1)s"><tt>%(b1)s</tt></td>
379 <td><a href="%(f2)s"><tt>%(b2)s</tt></td>
380 </tr>''' % locals ()
381
382     def get_content (self, f):
383         print 'reading', f
384         s = open (f).read ()
385         return s
386     
387         
388 class TextFileCompareLink (FileCompareLink):
389     def calc_distance (self):
390         import difflib
391         diff = difflib.unified_diff (self.contents[0].strip().split ('\n'),
392                                      self.contents[1].strip().split ('\n'),
393                                      fromfiledate = self.files[0],
394                                      tofiledate = self.files[1]
395                                      )
396
397         self.diff_lines =  [l for l in diff]
398         return float (len (self.diff_lines))
399         
400     def link_files_for_html (self, old_dir, new_dir, dest_dir):
401         str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
402         f = os.path.join (new_dir, self.name ()) + '.diff.txt'
403         f = os.path.join (dest_dir, f)
404         open_write_file (f).write (str)
405      
406     def html_record_string (self, d1, d2):
407         (dist, f1, f2) = (self.distance(),) + self.files
408         b1 = os.path.basename (f1)
409         b2 = os.path.basename (f2)
410         
411         return '''<tr>
412 <td>
413 %f
414 </td>
415 <td><tt>%s</tt></td>
416 <td><a href="%s.diff.txt"><tt>%s</tt></a></td>
417 </tr>''' % (dist,
418             b1,
419             os.path.join (d2, self.name ()),
420             b2)
421
422
423 class ProfileFileLink (TextFileCompareLink):
424     def calc_distance (self):
425         TextFileCompareLink.calc_distance (self)
426         
427         r = [{},{}]
428         for oldnew in (0,1):
429             def note_info (m):
430                 r[oldnew][m.group(1)] = float (m.group (2))
431             
432             re.sub ('([a-z]+): ([-0-9.]+)\n',
433                     note_info, self.contents[oldnew])
434
435         dist = 0.0
436         factor = {'time': 1.0 ,
437                   'cells': 10.0,
438                   }
439         
440         for k in ('time', 'cells'):
441             (v1,v2) = (r[0].get (k , -1),
442                        r[1].get (k , -1))
443
444             if v1 <= 0 or v2 <= 0:
445                 continue
446
447             ratio = abs (v2 - v1) / float (v1+v2)
448             dist += math.exp (ratio * factor[k]) - 1
449
450         dist = min (dist, 100)
451         
452         return dist
453
454 class MidiFileLink (FileCompareLink):
455     def get_content (self, f):
456         s = FileCompareLink.get_content (self, f)
457         s = re.sub ('LilyPond [0-9.]+', '', s)
458         return s
459
460 class SignatureFileLink (FileLink):
461     def __init__ (self):
462         FileLink.__init__ (self)
463         self.original_name = ''
464         self.base_names = ('','')
465         self.system_links = {}
466         
467     def name (self):
468         return os.path.splitext (self.original_name)[0]
469     
470     def add_system_link (self, link, number):
471         self.system_links[number] = link
472
473     def calc_distance (self):
474         d = 0.0
475
476         orphan_distance = 0.0
477         for l in self.system_links.values ():
478             d = max (d, l.geometric_distance ())
479             orphan_distance += l.orphan_count ()
480             
481         return d + orphan_distance
482
483     def source_file (self):
484         for ext in ('.ly', '.ly.txt'):
485             if os.path.exists (self.base_names[1] + ext):
486                 return self.base_names[1] + ext
487         return ''
488     
489     def add_file_compare (self, f1, f2):
490         system_index = [] 
491
492         def note_system_index (m):
493             system_index.append (int (m.group (1)))
494             return ''
495         
496         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
497         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
498
499         self.base_names = (os.path.normpath (base1),
500                            os.path.normpath (base2))
501
502         def note_original (match):
503             self.original_name = match.group (1)
504             return ''
505         
506         if not self.original_name:
507             self.original_name = os.path.split (base1)[1]
508
509             ## ugh: drop the .ly.txt
510             for ext in ('.ly', '.ly.txt'):
511                 try:
512                     re.sub (r'\\sourcefilename "([^"]+)"',
513                             note_original, open (base1 + ext).read ())
514                 except IOError:
515                     pass
516                 
517         s1 = read_signature_file (f1)
518         s2 = read_signature_file (f2)
519
520         link = SystemLink (s1, s2)
521
522         self.add_system_link (link, system_index[0])
523
524     
525     def create_images (self, old_dir, new_dir, dest_dir):
526
527         files_created = [[], []]
528         for oldnew in (0, 1):
529             pat = self.base_names[oldnew] + '.eps'
530
531             for f in glob.glob (pat):
532                 infile = f
533                 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
534
535                 mkdir (os.path.split (outfile)[0])
536                 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
537                        ' -r101 '
538                        ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
539                        ' %(infile)s  -c quit '  % locals ())
540
541                 files_created[oldnew].append (outfile)
542                 system (cmd)
543
544         return files_created
545     
546     def link_files_for_html (self, old_dir, new_dir, dest_dir):
547         to_compare = [[], []]
548
549         exts = ['.ly']
550         if options.create_images:
551             to_compare = self.create_images (old_dir, new_dir, dest_dir)
552         else:
553             exts += ['.png', '-page*png']
554         
555         for ext in exts:            
556             for oldnew in (0,1):
557                 for f in glob.glob (self.base_names[oldnew] + ext):
558                     dst = dest_dir + '/' + f
559                     link_file (f, dst)
560
561                     if f.endswith ('.png'):
562                         to_compare[oldnew].append (f)
563                         
564         if options.compare_images:                
565             for (old, new) in zip (to_compare[0], to_compare[1]):
566                 compare_png_images (old, new, dest_dir)
567
568                 
569     def html_record_string (self,  old_dir, new_dir):
570         def img_cell (ly, img, name):
571             if not name:
572                 name = 'source'
573             else:
574                 name = '<tt>%s</tt>' % name
575                 
576             return '''
577 <td align="center">
578 <a href="%(img)s">
579 <img src="%(img)s" style="border-style: none; max-width: 500px;">
580 </a><br>
581 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
582 </font>
583 </td>
584 ''' % locals ()
585         def multi_img_cell (ly, imgs, name):
586             if not name:
587                 name = 'source'
588             else:
589                 name = '<tt>%s</tt>' % name
590
591             imgs_str = '\n'.join (['''<a href="%s">
592 <img src="%s" style="border-style: none; max-width: 500px;">
593 </a><br>''' % (img, img) 
594                                   for img in imgs])
595
596
597             return '''
598 <td align="center">
599 %(imgs_str)s
600 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
601 </font>
602 </td>
603 ''' % locals ()
604
605
606
607         def cell (base, name):
608             pat = base + '-page*.png'
609             pages = glob.glob (pat)
610
611             if pages:
612                 return multi_img_cell (base + '.ly', sorted (pages), name)
613             else:
614                 return img_cell (base + '.ly', base + '.png', name)
615             
616
617         html_2  = self.base_names[1] + '.html'
618         name = self.original_name
619
620         cell_1 = cell (self.base_names[0], name)
621         cell_2 = cell (self.base_names[1], name)
622         if options.compare_images:
623             cell_2 = cell_2.replace ('.png', '.compare.jpeg')
624         
625         html_entry = '''
626 <tr>
627 <td>
628 %f<br>
629 (<a href="%s">details</a>)
630 </td>
631
632 %s
633 %s
634 </tr>
635 ''' % (self.distance (), html_2, cell_1, cell_2)
636
637         return html_entry
638
639
640     def html_system_details_string (self):
641         systems = self.system_links.items ()
642         systems.sort ()
643
644         html = ""
645         for (c, link) in systems:
646             e = '<td>%d</td>' % c
647             for d in link.distance ():
648                 e += '<td>%f</td>' % d
649             
650             e = '<tr>%s</tr>' % e
651
652             html += e
653
654             e = '<td>%d</td>' % c
655             for s in (link.output_expression_details_string (),
656                       link.orphan_details_string (),
657                       link.geo_details_string ()):
658                 e += "<td>%s</td>" % s
659
660             
661             e = '<tr>%s</tr>' % e
662             html += e
663             
664         original = self.original_name
665         html = '''<html>
666 <head>
667 <title>comparison details for %(original)s</title>
668 </head>
669 <body>
670 <table border=1>
671 <tr>
672 <th>system</th>
673 <th>output</th>
674 <th>orphan</th>
675 <th>geo</th>
676 </tr>
677
678 %(html)s
679 </table>
680
681 </body>
682 </html>
683 ''' % locals ()
684         return html
685
686     def write_html_system_details (self, dir1, dir2, dest_dir):
687         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
688
689         details = open_write_file (dest_file)
690         details.write (self.html_system_details_string ())
691
692 ################################################################
693 # Files/directories
694
695 import glob
696 import re
697
698 def compare_signature_files (f1, f2):
699     s1 = read_signature_file (f1)
700     s2 = read_signature_file (f2)
701     
702     return SystemLink (s1, s2).distance ()
703
704 def paired_files (dir1, dir2, pattern):
705     """
706     Search DIR1 and DIR2 for PATTERN.
707
708     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
709
710     """
711     
712     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
713     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
714
715     pairs = []
716     missing = []
717     for f in files1.keys ():
718         try:
719             files2.pop (f)
720             pairs.append (f)
721         except KeyError:
722             missing.append (f)
723
724     return (pairs, files2.keys (), missing)
725     
726 class ComparisonData:
727     def __init__ (self):
728         self.result_dict = {}
729         self.missing = []
730         self.added = []
731         self.file_links = {}
732
733     def compare_trees (self, dir1, dir2):
734         self.compare_directories (dir1, dir2)
735         
736         (root, dirs, files) = os.walk (dir1).next ()
737         for d in dirs:
738             d1 = os.path.join (dir1, d)
739             d2 = os.path.join (dir2, d)
740
741             if os.path.islink (d1) or os.path.islink (d2):
742                 continue
743             
744             if os.path.isdir (d2):
745                 self.compare_trees (d1, d2)
746     
747     def compare_directories (self, dir1, dir2):
748         for ext in ['signature', 'midi', 'log', 'profile']:
749             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
750
751             self.missing += [(dir1, m) for m in m1] 
752             self.added += [(dir2, m) for m in m2] 
753
754             for p in paired:
755                 if (options.max_count
756                     and len (self.file_links) > options.max_count):
757                     
758                     continue
759                 
760                 f2 = dir2 +  '/' + p
761                 f1 = dir1 +  '/' + p
762                 self.compare_files (f1, f2)
763
764     def compare_files (self, f1, f2):
765         if f1.endswith ('signature'):
766             self.compare_signature_files (f1, f2)
767         else:
768             ext = os.path.splitext (f1)[1]
769             klasses = {
770                 '.midi': MidiFileLink,
771                 '.log' : TextFileCompareLink,
772                 '.profile': ProfileFileLink,
773                 }
774             
775             if klasses.has_key (ext):
776                 self.compare_general_files (klasses[ext], f1, f2)
777
778     def compare_general_files (self, klass, f1, f2):
779         name = os.path.split (f1)[1]
780
781         file_link = klass (f1, f2)
782         self.file_links[name] = file_link
783         
784     def compare_signature_files (self, f1, f2):
785         name = os.path.split (f1)[1]
786         name = re.sub ('-[0-9]+.signature', '', name)
787         
788         file_link = None
789         try:
790             file_link = self.file_links[name]
791         except KeyError:
792             file_link = SignatureFileLink ()
793             self.file_links[name] = file_link
794
795         file_link.add_file_compare (f1, f2)
796
797     def remove_changed (self, dir, threshold):
798         (changed, below, unchanged) = self.thresholded_results (threshold)
799         for link in changed:
800             try:
801                 system ('rm -f %s*' % link.base_names[1])
802             except AttributeError: ### UGH.
803                 system ('rm -f %s/%s*' % (dir, link.name ()))
804     def thresholded_results (self, threshold):
805         ## todo: support more scores.
806         results = [(link.distance(), link)
807                    for link in self.file_links.values ()]
808         results.sort ()
809         results.reverse ()
810
811         unchanged = [r for (d,r) in results if d == 0.0]
812         below = [r for (d,r) in results if threshold >= d > 0.0]
813         changed = [r for (d,r) in results if d > threshold]
814
815         return (changed, below, unchanged)
816                 
817     def write_text_result_page (self, filename, threshold):
818         out = None
819         if filename == '':
820             out = sys.stdout
821         else:
822             print 'writing "%s"' % filename
823             out = open_write_file (filename)
824
825         (changed, below, unchanged) = self.thresholded_results (threshold)
826
827         
828         for link in changed:
829             out.write (link.text_record_string ())
830
831         out.write ('\n\n')
832         out.write ('%d below threshold\n' % len (below))
833         out.write ('%d unchanged\n' % len (unchanged))
834         
835     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
836         self.write_text_result_page (dest_dir + '/index.txt', threshold)
837         
838     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
839         dir1 = dir1.replace ('//', '/')
840         dir2 = dir2.replace ('//', '/')
841
842         (changed, below, unchanged) = self.thresholded_results (threshold)
843
844
845         html = ''
846         old_prefix = os.path.split (dir1)[1]
847         for link in changed:
848             link.link_files_for_html (dir1, dir2, dest_dir) 
849             link.write_html_system_details (dir1, dir2, dest_dir)
850             
851             html += link.html_record_string (dir1, dir2)
852
853
854         short_dir1 = shorten_string (dir1)
855         short_dir2 = shorten_string (dir2)
856         html = '''<html>
857 <table rules="rows" border bordercolor="blue">
858 <tr>
859 <th>distance</th>
860 <th>%(short_dir1)s</th>
861 <th>%(short_dir2)s</th>
862 </tr>
863 %(html)s
864 </table>
865 </html>''' % locals()
866
867         html += ('<p>')
868         below_count = len (below)
869
870         if below_count:
871             html += ('<p>%d below threshold</p>' % below_count)
872             
873         html += ('<p>%d unchanged</p>' % len (unchanged))
874
875         dest_file = dest_dir + '/index.html'
876         open_write_file (dest_file).write (html)
877         
878     def print_results (self, threshold):
879         self.write_text_result_page ('', threshold)
880
881 def compare_trees (dir1, dir2, dest_dir, threshold):
882     data = ComparisonData ()
883     data.compare_trees (dir1, dir2)
884     data.print_results (threshold)
885
886     if options.remove_changed:
887         data.remove_changed (dir2, threshold)
888         return
889     
890     if os.path.isdir (dest_dir):
891         system ('rm -rf %s '% dest_dir)
892
893     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
894     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
895     
896 ################################################################
897 # TESTING
898
899 def mkdir (x):
900     if not os.path.isdir (x):
901         print 'mkdir', x
902         os.makedirs (x)
903
904 def link_file (x, y):
905     mkdir (os.path.split (y)[0])
906     try:
907         os.link (x, y)
908     except OSError, z:
909         print 'OSError', x, y, z
910         raise OSError
911     
912 def open_write_file (x):
913     d = os.path.split (x)[0]
914     mkdir (d)
915     return open (x, 'w')
916
917
918 def system (x):
919     
920     print 'invoking', x
921     stat = os.system (x)
922     assert stat == 0
923
924
925 def test_paired_files ():
926     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
927                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
928                   
929     
930 def test_compare_trees ():
931     system ('rm -rf dir1 dir2')
932     system ('mkdir dir1 dir2')
933     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
934     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
935     system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
936     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
937     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
938     system ('cp 19-1.signature 19-sub-1.signature')
939     system ('cp 19.ly 19-sub.ly')
940     system ('cp 19.profile 19-sub.profile')
941     system ('cp 19.log 19-sub.log')
942     system ('cp 19.png 19-sub.png')
943     system ('cp 19.eps 19-sub.eps')
944
945     system ('cp 20multipage* dir1')
946     system ('cp 20multipage* dir2')
947     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
948
949     
950     system ('mkdir -p dir1/subdir/ dir2/subdir/')
951     system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
952     system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
953     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
954     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
955
956     ## introduce differences
957     system ('cp 19-1.signature dir2/20-1.signature')
958     system ('cp 19.profile dir2/20.profile')
959     system ('cp 19.png dir2/20.png')
960     system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
961     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
962     system ('cp 20.png dir2/subdir/19-sub.png')
963     system ("sed 's/: /: 1/g'  20.profile > dir2/subdir/19-sub.profile")
964
965     ## radical diffs.
966     system ('cp 19-1.signature dir2/20grob-1.signature')
967     system ('cp 19-1.signature dir2/20grob-2.signature')
968     system ('cp 19multipage.midi dir1/midi-differ.midi')
969     system ('cp 20multipage.midi dir2/midi-differ.midi')
970     system ('cp 19multipage.log dir1/log-differ.log')
971     system ('cp 19multipage.log dir2/log-differ.log &&  echo different >> dir2/log-differ.log &&  echo different >> dir2/log-differ.log')
972
973     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
974
975
976 def test_basic_compare ():
977     ly_template = r"""
978
979 \version "2.10.0"
980 #(define default-toplevel-book-handler
981   print-book-with-defaults-as-systems )
982
983 #(ly:set-option (quote no-point-and-click))
984
985 \sourcefilename "my-source.ly"
986  
987 %(papermod)s
988 \header { tagline = ##f }
989 \score {
990 <<
991 \new Staff \relative c {
992   c4^"%(userstring)s" %(extragrob)s
993   }
994 \new Staff \relative c {
995   c4^"%(userstring)s" %(extragrob)s
996   }
997 >>
998 \layout{}
999 }
1000
1001 """
1002
1003     dicts = [{ 'papermod' : '',
1004                'name' : '20',
1005                'extragrob': '',
1006                'userstring': 'test' },
1007              { 'papermod' : '#(set-global-staff-size 19.5)',
1008                'name' : '19',
1009                'extragrob': '',
1010                'userstring': 'test' },
1011              { 'papermod' : '',
1012                'name' : '20expr',
1013                'extragrob': '',
1014                'userstring': 'blabla' },
1015              { 'papermod' : '',
1016                'name' : '20grob',
1017                'extragrob': 'r2. \\break c1',
1018                'userstring': 'test' },
1019              ]
1020
1021     for d in dicts:
1022         open (d['name'] + '.ly','w').write (ly_template % d)
1023         
1024     names = [d['name'] for d in dicts]
1025
1026     system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1027     
1028
1029     multipage_str = r'''
1030     #(set-default-paper-size "a6")
1031     \score {
1032       \relative {c1 \pageBreak c1 }
1033       \layout {}
1034       \midi {}
1035     }
1036     '''
1037
1038     open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
1039     open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1040     system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1041  
1042     test_compare_signatures (names)
1043     
1044 def test_compare_signatures (names, timing=False):
1045
1046     import time
1047
1048     times = 1
1049     if timing:
1050         times = 100
1051
1052     t0 = time.clock ()
1053
1054     count = 0
1055     for t in range (0, times):
1056         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1057         count += 1
1058
1059     if timing:
1060         print 'elapsed', (time.clock() - t0)/count
1061
1062
1063     t0 = time.clock ()
1064     count = 0
1065     combinations = {}
1066     for (n1, s1) in sigs.items():
1067         for (n2, s2) in sigs.items():
1068             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1069             count += 1
1070
1071     if timing:
1072         print 'elapsed', (time.clock() - t0)/count
1073
1074     results = combinations.items ()
1075     results.sort ()
1076     for k,v in results:
1077         print '%-20s' % k, v
1078
1079     assert combinations['20-20'] == (0.0,0.0,0.0)
1080     assert combinations['20-20expr'][0] > 0.0
1081     assert combinations['20-19'][2] < 10.0
1082     assert combinations['20-19'][2] > 0.0
1083
1084
1085 def run_tests ():
1086     dir = 'test-output-distance'
1087
1088     do_clean = not os.path.exists (dir)
1089
1090     print 'test results in ', dir
1091     if do_clean:
1092         system ('rm -rf ' + dir)
1093         system ('mkdir ' + dir)
1094         
1095     os.chdir (dir)
1096     if do_clean:
1097         test_basic_compare ()
1098         
1099     test_compare_trees ()
1100     
1101 ################################################################
1102 #
1103
1104 def main ():
1105     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1106     p.usage = 'output-distance.py [options] tree1 tree2'
1107     
1108     p.add_option ('', '--test-self',
1109                   dest="run_test",
1110                   action="store_true",
1111                   help='run test method')
1112     
1113     p.add_option ('--max-count',
1114                   dest="max_count",
1115                   metavar="COUNT",
1116                   type="int",
1117                   default=0, 
1118                   action="store",
1119                   help='only analyze COUNT signature pairs')
1120
1121     p.add_option ('', '--threshold',
1122                   dest="threshold",
1123                   default=0.3,
1124                   action="store",
1125                   type="float",
1126                   help='threshold for geometric distance')
1127
1128
1129     p.add_option ('--remove-changed',
1130                   dest="remove_changed",
1131                   default=False,
1132                   action="store_true",
1133                   help="Remove all files from tree2 that are over the threshold.")
1134
1135     p.add_option ('--no-compare-images',
1136                   dest="compare_images",
1137                   default=True,
1138                   action="store_false",
1139                   help="Don't run graphical comparisons")
1140
1141     p.add_option ('--create-images',
1142                   dest="create_images",
1143                   default=False,
1144                   action="store_true",
1145                   help="Create PNGs from EPSes")
1146
1147     p.add_option ('-o', '--output-dir',
1148                   dest="output_dir",
1149                   default=None,
1150                   action="store",
1151                   type="string",
1152                   help='where to put the test results [tree2/compare-tree1tree2]')
1153
1154     global options
1155     (options, a) = p.parse_args ()
1156
1157     if options.run_test:
1158         run_tests ()
1159         sys.exit (0)
1160
1161     if len (a) != 2:
1162         p.print_usage()
1163         sys.exit (2)
1164
1165     name = options.output_dir
1166     if not name:
1167         name = a[0].replace ('/', '')
1168         name = os.path.join (a[1], 'compare-' + shorten_string (name))
1169     
1170     compare_trees (a[0], a[1], name, options.threshold)
1171
1172 if __name__ == '__main__':
1173     main()
1174