]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
More sensible comparison measure of profile data.
[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         return '''<tr>
408 <td>
409 %f
410 </td>
411 <td><tt>%s</tt></td>
412 <td><a href="%s.diff.txt"><tt>%s</tt></a></td>
413 </tr>''' % (self.distance(),
414             self.files[0],
415             os.path.join (d2, self.name ()),
416             self.files[1])
417
418
419 class ProfileFileLink (TextFileCompareLink):
420     def calc_distance (self):
421         TextFileCompareLink.calc_distance (self)
422         
423         r = [{},{}]
424         for oldnew in (0,1):
425             def note_info (m):
426                 r[oldnew][m.group(1)] = float (m.group (2))
427             
428             re.sub ('([a-z]+): ([-0-9.]+)\n',
429                     note_info, self.contents[oldnew])
430
431         dist = 0.0
432         factor = {'time': 1.0 ,
433                   'cells': 10.0,
434                   }
435         
436         for k in ('time', 'cells'):
437             (v1,v2) = (r[0].get (k , -1),
438                        r[1].get (k , -1))
439
440             if v1 <= 0 or v2 <= 0:
441                 continue
442
443             ratio = abs (v2 - v1) / float (v1+v2)
444             dist += math.exp (ratio * factor[k]) - 1
445
446         dist = min (dist, 100)
447         
448         return dist
449
450 class MidiFileLink (FileCompareLink):
451     def get_content (self, f):
452         s = FileCompareLink.get_content (self, f)
453         s = re.sub ('LilyPond [0-9.]+', '', s)
454         return s
455
456 class SignatureFileLink (FileLink):
457     def __init__ (self):
458         FileLink.__init__ (self)
459         self.original_name = ''
460         self.base_names = ('','')
461         self.system_links = {}
462         
463     def name (self):
464         return os.path.splitext (self.original_name)[0]
465     
466     def add_system_link (self, link, number):
467         self.system_links[number] = link
468
469     def calc_distance (self):
470         d = 0.0
471
472         orphan_distance = 0.0
473         for l in self.system_links.values ():
474             d = max (d, l.geometric_distance ())
475             orphan_distance += l.orphan_count ()
476             
477         return d + orphan_distance
478
479     def source_file (self):
480         for ext in ('.ly', '.ly.txt'):
481             if os.path.exists (self.base_names[1] + ext):
482                 return self.base_names[1] + ext
483         return ''
484     
485     def add_file_compare (self, f1, f2):
486         system_index = [] 
487
488         def note_system_index (m):
489             system_index.append (int (m.group (1)))
490             return ''
491         
492         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
493         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
494
495         self.base_names = (os.path.normpath (base1),
496                            os.path.normpath (base2))
497
498         def note_original (match):
499             self.original_name = match.group (1)
500             return ''
501         
502         if not self.original_name:
503             self.original_name = os.path.split (base1)[1]
504
505             ## ugh: drop the .ly.txt
506             for ext in ('.ly', '.ly.txt'):
507                 try:
508                     re.sub (r'\\sourcefilename "([^"]+)"',
509                             note_original, open (base1 + ext).read ())
510                 except IOError:
511                     pass
512                 
513         s1 = read_signature_file (f1)
514         s2 = read_signature_file (f2)
515
516         link = SystemLink (s1, s2)
517
518         self.add_system_link (link, system_index[0])
519
520     
521     def create_images (self, old_dir, new_dir, dest_dir):
522
523         files_created = [[], []]
524         for oldnew in (0, 1):
525             pat = self.base_names[oldnew] + '.eps'
526
527             for f in glob.glob (pat):
528                 infile = f
529                 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
530
531                 mkdir (os.path.split (outfile)[0])
532                 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
533                        ' -r101 '
534                        ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
535                        ' %(infile)s  -c quit '  % locals ())
536
537                 files_created[oldnew].append (outfile)
538                 system (cmd)
539
540         return files_created
541     
542     def link_files_for_html (self, old_dir, new_dir, dest_dir):
543         to_compare = [[], []]
544
545         exts = ['.ly']
546         if options.create_images:
547             to_compare = self.create_images (old_dir, new_dir, dest_dir)
548         else:
549             exts += ['.png', '-page*png']
550         
551         for ext in exts:            
552             for oldnew in (0,1):
553                 for f in glob.glob (self.base_names[oldnew] + ext):
554                     dst = dest_dir + '/' + f
555                     link_file (f, dst)
556
557                     if f.endswith ('.png'):
558                         to_compare[oldnew].append (f)
559                         
560         if options.compare_images:                
561             for (old, new) in zip (to_compare[0], to_compare[1]):
562                 compare_png_images (old, new, dest_dir)
563
564                 
565     def html_record_string (self,  old_dir, new_dir):
566         def img_cell (ly, img, name):
567             if not name:
568                 name = 'source'
569             else:
570                 name = '<tt>%s</tt>' % name
571                 
572             return '''
573 <td align="center">
574 <a href="%(img)s">
575 <img src="%(img)s" style="border-style: none; max-width: 500px;">
576 </a><br>
577 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
578 </font>
579 </td>
580 ''' % locals ()
581         def multi_img_cell (ly, imgs, name):
582             if not name:
583                 name = 'source'
584             else:
585                 name = '<tt>%s</tt>' % name
586
587             imgs_str = '\n'.join (['''<a href="%s">
588 <img src="%s" style="border-style: none; max-width: 500px;">
589 </a><br>''' % (img, img) 
590                                   for img in imgs])
591
592
593             return '''
594 <td align="center">
595 %(imgs_str)s
596 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
597 </font>
598 </td>
599 ''' % locals ()
600
601
602
603         def cell (base, name):
604             pat = base + '-page*.png'
605             pages = glob.glob (pat)
606
607             if pages:
608                 return multi_img_cell (base + '.ly', sorted (pages), name)
609             else:
610                 return img_cell (base + '.ly', base + '.png', name)
611             
612
613         html_2  = self.base_names[1] + '.html'
614         name = self.original_name
615
616         cell_1 = cell (self.base_names[0], name)
617         cell_2 = cell (self.base_names[1], name)
618         if options.compare_images:
619             cell_2 = cell_2.replace ('.png', '.compare.jpeg')
620         
621         html_entry = '''
622 <tr>
623 <td>
624 %f<br>
625 (<a href="%s">details</a>)
626 </td>
627
628 %s
629 %s
630 </tr>
631 ''' % (self.distance (), html_2, cell_1, cell_2)
632
633         return html_entry
634
635
636     def html_system_details_string (self):
637         systems = self.system_links.items ()
638         systems.sort ()
639
640         html = ""
641         for (c, link) in systems:
642             e = '<td>%d</td>' % c
643             for d in link.distance ():
644                 e += '<td>%f</td>' % d
645             
646             e = '<tr>%s</tr>' % e
647
648             html += e
649
650             e = '<td>%d</td>' % c
651             for s in (link.output_expression_details_string (),
652                       link.orphan_details_string (),
653                       link.geo_details_string ()):
654                 e += "<td>%s</td>" % s
655
656             
657             e = '<tr>%s</tr>' % e
658             html += e
659             
660         original = self.original_name
661         html = '''<html>
662 <head>
663 <title>comparison details for %(original)s</title>
664 </head>
665 <body>
666 <table border=1>
667 <tr>
668 <th>system</th>
669 <th>output</th>
670 <th>orphan</th>
671 <th>geo</th>
672 </tr>
673
674 %(html)s
675 </table>
676
677 </body>
678 </html>
679 ''' % locals ()
680         return html
681
682     def write_html_system_details (self, dir1, dir2, dest_dir):
683         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
684
685         details = open_write_file (dest_file)
686         details.write (self.html_system_details_string ())
687
688 ################################################################
689 # Files/directories
690
691 import glob
692 import re
693
694 def compare_signature_files (f1, f2):
695     s1 = read_signature_file (f1)
696     s2 = read_signature_file (f2)
697     
698     return SystemLink (s1, s2).distance ()
699
700 def paired_files (dir1, dir2, pattern):
701     """
702     Search DIR1 and DIR2 for PATTERN.
703
704     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
705
706     """
707     
708     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
709     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
710
711     pairs = []
712     missing = []
713     for f in files1.keys ():
714         try:
715             files2.pop (f)
716             pairs.append (f)
717         except KeyError:
718             missing.append (f)
719
720     return (pairs, files2.keys (), missing)
721     
722 class ComparisonData:
723     def __init__ (self):
724         self.result_dict = {}
725         self.missing = []
726         self.added = []
727         self.file_links = {}
728
729     def compare_trees (self, dir1, dir2):
730         self.compare_directories (dir1, dir2)
731         
732         (root, dirs, files) = os.walk (dir1).next ()
733         for d in dirs:
734             d1 = os.path.join (dir1, d)
735             d2 = os.path.join (dir2, d)
736
737             if os.path.islink (d1) or os.path.islink (d2):
738                 continue
739             
740             if os.path.isdir (d2):
741                 self.compare_trees (d1, d2)
742     
743     def compare_directories (self, dir1, dir2):
744         for ext in ['signature', 'midi', 'log', 'profile']:
745             (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
746
747             self.missing += [(dir1, m) for m in m1] 
748             self.added += [(dir2, m) for m in m2] 
749
750             for p in paired:
751                 if (options.max_count
752                     and len (self.file_links) > options.max_count):
753                     
754                     continue
755                 
756                 f2 = dir2 +  '/' + p
757                 f1 = dir1 +  '/' + p
758                 self.compare_files (f1, f2)
759
760     def compare_files (self, f1, f2):
761         if f1.endswith ('signature'):
762             self.compare_signature_files (f1, f2)
763         else:
764             ext = os.path.splitext (f1)[1]
765             klasses = {
766                 '.midi': MidiFileLink,
767                 '.log' : TextFileCompareLink,
768                 '.profile': ProfileFileLink,
769                 }
770             
771             if klasses.has_key (ext):
772                 self.compare_general_files (klasses[ext], f1, f2)
773
774     def compare_general_files (self, klass, f1, f2):
775         name = os.path.split (f1)[1]
776
777         file_link = klass (f1, f2)
778         self.file_links[name] = file_link
779         
780     def compare_signature_files (self, f1, f2):
781         name = os.path.split (f1)[1]
782         name = re.sub ('-[0-9]+.signature', '', name)
783         
784         file_link = None
785         try:
786             file_link = self.file_links[name]
787         except KeyError:
788             file_link = SignatureFileLink ()
789             self.file_links[name] = file_link
790
791         file_link.add_file_compare (f1, f2)
792
793     def remove_changed (self, dir, threshold):
794         (changed, below, unchanged) = self.thresholded_results (threshold)
795         for link in changed:
796             try:
797                 system ('rm -f %s*' % link.base_names[1])
798             except AttributeError: ### UGH.
799                 system ('rm -f %s/%s*' % (dir, link.name ()))
800     def thresholded_results (self, threshold):
801         ## todo: support more scores.
802         results = [(link.distance(), link)
803                    for link in self.file_links.values ()]
804         results.sort ()
805         results.reverse ()
806
807         unchanged = [r for (d,r) in results if d == 0.0]
808         below = [r for (d,r) in results if threshold >= d > 0.0]
809         changed = [r for (d,r) in results if d > threshold]
810
811         return (changed, below, unchanged)
812                 
813     def write_text_result_page (self, filename, threshold):
814         out = None
815         if filename == '':
816             out = sys.stdout
817         else:
818             print 'writing "%s"' % filename
819             out = open_write_file (filename)
820
821         (changed, below, unchanged) = self.thresholded_results (threshold)
822
823         
824         for link in changed:
825             out.write (link.text_record_string ())
826
827         out.write ('\n\n')
828         out.write ('%d below threshold\n' % len (below))
829         out.write ('%d unchanged\n' % len (unchanged))
830         
831     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
832         self.write_text_result_page (dest_dir + '/index.txt', threshold)
833         
834     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
835         dir1 = dir1.replace ('//', '/')
836         dir2 = dir2.replace ('//', '/')
837
838         (changed, below, unchanged) = self.thresholded_results (threshold)
839
840
841         html = ''
842         old_prefix = os.path.split (dir1)[1]
843         for link in changed:
844             link.link_files_for_html (dir1, dir2, dest_dir) 
845             link.write_html_system_details (dir1, dir2, dest_dir)
846             
847             html += link.html_record_string (dir1, dir2)
848
849
850         short_dir1 = shorten_string (dir1)
851         short_dir2 = shorten_string (dir2)
852         html = '''<html>
853 <table rules="rows" border bordercolor="blue">
854 <tr>
855 <th>distance</th>
856 <th>%(short_dir1)s</th>
857 <th>%(short_dir2)s</th>
858 </tr>
859 %(html)s
860 </table>
861 </html>''' % locals()
862
863         html += ('<p>')
864         below_count = len (below)
865
866         if below_count:
867             html += ('<p>%d below threshold</p>' % below_count)
868             
869         html += ('<p>%d unchanged</p>' % len (unchanged))
870
871         dest_file = dest_dir + '/index.html'
872         open_write_file (dest_file).write (html)
873         
874     def print_results (self, threshold):
875         self.write_text_result_page ('', threshold)
876
877 def compare_trees (dir1, dir2, dest_dir, threshold):
878     data = ComparisonData ()
879     data.compare_trees (dir1, dir2)
880     data.print_results (threshold)
881
882     if options.remove_changed:
883         data.remove_changed (dir2, threshold)
884         return
885     
886     if os.path.isdir (dest_dir):
887         system ('rm -rf %s '% dest_dir)
888
889     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
890     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
891     
892 ################################################################
893 # TESTING
894
895 def mkdir (x):
896     if not os.path.isdir (x):
897         print 'mkdir', x
898         os.makedirs (x)
899
900 def link_file (x, y):
901     mkdir (os.path.split (y)[0])
902     try:
903         os.link (x, y)
904     except OSError, z:
905         print 'OSError', x, y, z
906         raise OSError
907     
908 def open_write_file (x):
909     d = os.path.split (x)[0]
910     mkdir (d)
911     return open (x, 'w')
912
913
914 def system (x):
915     
916     print 'invoking', x
917     stat = os.system (x)
918     assert stat == 0
919
920
921 def test_paired_files ():
922     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
923                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
924                   
925     
926 def test_compare_trees ():
927     system ('rm -rf dir1 dir2')
928     system ('mkdir dir1 dir2')
929     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
930     system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
931     system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
932     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
933     system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
934     system ('cp 19-1.signature 19-sub-1.signature')
935     system ('cp 19.ly 19-sub.ly')
936     system ('cp 19.profile 19-sub.profile')
937     system ('cp 19.log 19-sub.log')
938     system ('cp 19.png 19-sub.png')
939     system ('cp 19.eps 19-sub.eps')
940
941     system ('cp 20multipage* dir1')
942     system ('cp 20multipage* dir2')
943     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
944
945     
946     system ('mkdir -p dir1/subdir/ dir2/subdir/')
947     system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
948     system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
949     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
950     system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
951
952     ## introduce differences
953     system ('cp 19-1.signature dir2/20-1.signature')
954     system ('cp 19.profile dir2/20.profile')
955     system ('cp 19.png dir2/20.png')
956     system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
957     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
958     system ('cp 20.png dir2/subdir/19-sub.png')
959     system ("sed 's/: /: 1/g'  20.profile > dir2/subdir/19-sub.profile")
960
961     ## radical diffs.
962     system ('cp 19-1.signature dir2/20grob-1.signature')
963     system ('cp 19-1.signature dir2/20grob-2.signature')
964     system ('cp 19multipage.midi dir1/midi-differ.midi')
965     system ('cp 20multipage.midi dir2/midi-differ.midi')
966     system ('cp 19multipage.log dir1/log-differ.log')
967     system ('cp 19multipage.log dir2/log-differ.log &&  echo different >> dir2/log-differ.log &&  echo different >> dir2/log-differ.log')
968
969     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
970
971
972 def test_basic_compare ():
973     ly_template = r"""
974
975 \version "2.10.0"
976 #(define default-toplevel-book-handler
977   print-book-with-defaults-as-systems )
978
979 #(ly:set-option (quote no-point-and-click))
980
981 \sourcefilename "my-source.ly"
982  
983 %(papermod)s
984 \header { tagline = ##f }
985 \score {
986 <<
987 \new Staff \relative c {
988   c4^"%(userstring)s" %(extragrob)s
989   }
990 \new Staff \relative c {
991   c4^"%(userstring)s" %(extragrob)s
992   }
993 >>
994 \layout{}
995 }
996
997 """
998
999     dicts = [{ 'papermod' : '',
1000                'name' : '20',
1001                'extragrob': '',
1002                'userstring': 'test' },
1003              { 'papermod' : '#(set-global-staff-size 19.5)',
1004                'name' : '19',
1005                'extragrob': '',
1006                'userstring': 'test' },
1007              { 'papermod' : '',
1008                'name' : '20expr',
1009                'extragrob': '',
1010                'userstring': 'blabla' },
1011              { 'papermod' : '',
1012                'name' : '20grob',
1013                'extragrob': 'r2. \\break c1',
1014                'userstring': 'test' },
1015              ]
1016
1017     for d in dicts:
1018         open (d['name'] + '.ly','w').write (ly_template % d)
1019         
1020     names = [d['name'] for d in dicts]
1021
1022     system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1023     
1024
1025     multipage_str = r'''
1026     #(set-default-paper-size "a6")
1027     \score {
1028       \relative {c1 \pageBreak c1 }
1029       \layout {}
1030       \midi {}
1031     }
1032     '''
1033
1034     open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
1035     open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1036     system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1037  
1038     test_compare_signatures (names)
1039     
1040 def test_compare_signatures (names, timing=False):
1041
1042     import time
1043
1044     times = 1
1045     if timing:
1046         times = 100
1047
1048     t0 = time.clock ()
1049
1050     count = 0
1051     for t in range (0, times):
1052         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1053         count += 1
1054
1055     if timing:
1056         print 'elapsed', (time.clock() - t0)/count
1057
1058
1059     t0 = time.clock ()
1060     count = 0
1061     combinations = {}
1062     for (n1, s1) in sigs.items():
1063         for (n2, s2) in sigs.items():
1064             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1065             count += 1
1066
1067     if timing:
1068         print 'elapsed', (time.clock() - t0)/count
1069
1070     results = combinations.items ()
1071     results.sort ()
1072     for k,v in results:
1073         print '%-20s' % k, v
1074
1075     assert combinations['20-20'] == (0.0,0.0,0.0)
1076     assert combinations['20-20expr'][0] > 0.0
1077     assert combinations['20-19'][2] < 10.0
1078     assert combinations['20-19'][2] > 0.0
1079
1080
1081 def run_tests ():
1082     dir = 'test-output-distance'
1083
1084     do_clean = not os.path.exists (dir)
1085
1086     print 'test results in ', dir
1087     if do_clean:
1088         system ('rm -rf ' + dir)
1089         system ('mkdir ' + dir)
1090         
1091     os.chdir (dir)
1092     if do_clean:
1093         test_basic_compare ()
1094         
1095     test_compare_trees ()
1096     
1097 ################################################################
1098 #
1099
1100 def main ():
1101     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1102     p.usage = 'output-distance.py [options] tree1 tree2'
1103     
1104     p.add_option ('', '--test-self',
1105                   dest="run_test",
1106                   action="store_true",
1107                   help='run test method')
1108     
1109     p.add_option ('--max-count',
1110                   dest="max_count",
1111                   metavar="COUNT",
1112                   type="int",
1113                   default=0, 
1114                   action="store",
1115                   help='only analyze COUNT signature pairs')
1116
1117     p.add_option ('', '--threshold',
1118                   dest="threshold",
1119                   default=0.3,
1120                   action="store",
1121                   type="float",
1122                   help='threshold for geometric distance')
1123
1124
1125     p.add_option ('--remove-changed',
1126                   dest="remove_changed",
1127                   default=False,
1128                   action="store_true",
1129                   help="Remove all files from tree2 that are over the threshold.")
1130
1131     p.add_option ('--no-compare-images',
1132                   dest="compare_images",
1133                   default=True,
1134                   action="store_false",
1135                   help="Don't run graphical comparisons")
1136
1137     p.add_option ('--create-images',
1138                   dest="create_images",
1139                   default=False,
1140                   action="store_true",
1141                   help="Create PNGs from EPSes")
1142
1143     p.add_option ('-o', '--output-dir',
1144                   dest="output_dir",
1145                   default=None,
1146                   action="store",
1147                   type="string",
1148                   help='where to put the test results [tree2/compare-tree1tree2]')
1149
1150     global options
1151     (options, a) = p.parse_args ()
1152
1153     if options.run_test:
1154         run_tests ()
1155         sys.exit (0)
1156
1157     if len (a) != 2:
1158         p.print_usage()
1159         sys.exit (2)
1160
1161     name = options.output_dir
1162     if not name:
1163         name = a[0].replace ('/', '')
1164         name = os.path.join (a[1], 'compare-' + shorten_string (name))
1165     
1166     compare_trees (a[0], a[1], name, options.threshold)
1167
1168 if __name__ == '__main__':
1169     main()
1170