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