]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/output-distance.py
(test_basic_compare): add
[lilypond.git] / buildscripts / output-distance.py
1 #!@TARGET_PYTHON@
2 import sys
3 import optparse
4 import os
5
6 ## so we can call directly as buildscripts/output-distance.py
7 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
8 sys.path.insert (0, me_path + '/../python/')
9
10
11 import safeeval
12
13
14 X_AXIS = 0
15 Y_AXIS = 1
16 INFTY = 1e6
17
18 OUTPUT_EXPRESSION_PENALTY = 1
19 ORPHAN_GROB_PENALTY = 1
20 inspect_max_count = 0
21
22 def max_distance (x1, x2):
23     dist = 0.0
24
25     for (p,q) in zip (x1, x2):
26         dist = max (abs (p-q), dist)
27         
28     return dist
29
30
31 empty_interval = (INFTY, -INFTY)
32 empty_bbox = (empty_interval, empty_interval)
33
34 def interval_is_empty (i):
35     return i[0] > i[1]
36
37 def interval_length (i):
38     return max (i[1]-i[0], 0) 
39     
40 def interval_union (i1, i2):
41     return (min (i1[0], i2[0]),
42             max (i1[1], i2[1]))
43
44 def interval_intersect (i1, i2):
45     return (max (i1[0], i2[0]),
46             min (i1[1], i2[1]))
47
48 def bbox_is_empty (b):
49     return (interval_is_empty (b[0])
50             or interval_is_empty (b[1]))
51
52 def bbox_union (b1, b2):
53     return (interval_union (b1[X_AXIS], b2[X_AXIS]),
54             interval_union (b2[Y_AXIS], b2[Y_AXIS]))
55             
56 def bbox_intersection (b1, b2):
57     return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
58             interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
59
60 def bbox_area (b):
61     return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
62
63 def bbox_diameter (b):
64     return max (interval_length (b[X_AXIS]),
65                 interval_length (b[Y_AXIS]))
66                 
67
68 def difference_area (a, b):
69     return bbox_area (a) - bbox_area (bbox_intersection (a,b))
70
71 class GrobSignature:
72     def __init__ (self, exp_list):
73         (self.name, self.origin, bbox_x,
74          bbox_y, self.output_expression) = tuple (exp_list)
75         
76         self.bbox = (bbox_x, bbox_y)
77         self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
78
79     def __repr__ (self):
80         return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
81                                                    self.bbox[0][0],
82                                                    self.bbox[0][1],
83                                                    self.bbox[1][0],
84                                                    self.bbox[1][1])
85                                                  
86     def axis_centroid (self, axis):
87         return apply (sum, self.bbox[axis])  / 2 
88     
89     def centroid_distance (self, other, scale):
90         return max_distance (self.centroid, other.centroid) / scale 
91         
92     def bbox_distance (self, other):
93         divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
94
95         if divisor:
96             return (difference_area (self.bbox, other.bbox) +
97                     difference_area (other.bbox, self.bbox)) / divisor
98         else:
99             return 0.0
100         
101     def expression_distance (self, other):
102         if self.output_expression == other.output_expression:
103             return 0
104         else:
105             return 1
106
107 ################################################################
108 # single System.
109
110 class SystemSignature:
111     def __init__ (self, grob_sigs):
112         d = {}
113         for g in grob_sigs:
114             val = d.setdefault (g.name, [])
115             val += [g]
116
117         self.grob_dict = d
118         self.set_all_bbox (grob_sigs)
119
120     def set_all_bbox (self, grobs):
121         self.bbox = empty_bbox
122         for g in grobs:
123             self.bbox = bbox_union (g.bbox, self.bbox)
124
125     def closest (self, grob_name, centroid):
126         min_d = INFTY
127         min_g = None
128         try:
129             grobs = self.grob_dict[grob_name]
130
131             for g in grobs:
132                 d = max_distance (g.centroid, centroid)
133                 if d < min_d:
134                     min_d = d
135                     min_g = g
136
137
138             return min_g
139
140         except KeyError:
141             return None
142     def grobs (self):
143         return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
144
145 ################################################################
146 ## comparison of systems.
147
148 class SystemLink:
149     def __init__ (self, system1, system2):
150         self.system1 = system1
151         self.system2 = system2
152         
153         self.link_list_dict = {}
154         self.back_link_dict = {}
155
156
157         ## pairs
158         self.orphans = []
159
160         ## pair -> distance
161         self.geo_distances = {}
162
163         ## pairs
164         self.expression_changed = []
165
166         self._geometric_distance = None
167         self._expression_change_count = None
168         self._orphan_count = None
169         
170         for g in system1.grobs ():
171
172             ## skip empty bboxes.
173             if bbox_is_empty (g.bbox):
174                 continue
175             
176             closest = system2.closest (g.name, g.centroid)
177             
178             self.link_list_dict.setdefault (closest, [])
179             self.link_list_dict[closest].append (g)
180             self.back_link_dict[g] = closest
181
182
183     def calc_geometric_distance (self):
184         total = 0.0
185         for (g1,g2) in self.back_link_dict.items ():
186             if g2:
187                 d = g1.bbox_distance (g2)
188                 if d:
189                     self.geo_distances[(g1,g2)] = d
190
191                 total += d
192
193         self._geometric_distance = total
194     
195     def calc_orphan_count (self):
196         count = 0
197         for (g1, g2) in self.back_link_dict.items ():
198             if g2 == None:
199                 self.orphans.append ((g1, None))
200                 
201                 count += 1
202
203         self._orphan_count = count
204     
205     def calc_output_exp_distance (self):
206         d = 0
207         for (g1,g2) in self.back_link_dict.items ():
208             if g2:
209                 d += g1.expression_distance (g2)
210
211         self._expression_change_count = d
212
213     def output_expression_details_string (self):
214         return ', '.join ([g1.name for g1 in self.expression_changed])
215     
216     def geo_details_string (self):
217         results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
218         results.sort ()
219         results.reverse ()
220         
221         return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
222
223     def orphan_details_string (self):
224         return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
225
226     def geometric_distance (self):
227         if self._geometric_distance == None:
228             self.calc_geometric_distance ()
229         return self._geometric_distance
230     
231     def orphan_count (self):
232         if self._orphan_count == None:
233             self.calc_orphan_count ()
234             
235         return self._orphan_count
236     
237     def output_expression_change_count (self):
238         if self._expression_change_count == None:
239             self.calc_output_exp_distance ()
240         return self._expression_change_count
241         
242     def distance (self):
243         return (self.output_expression_change_count (),
244                 self.orphan_count (),
245                 self.geometric_distance ())
246     
247 def read_signature_file (name):
248     print 'reading', name
249     
250     entries = open (name).read ().split ('\n')
251     def string_to_tup (s):
252         return tuple (map (float, s.split (' '))) 
253
254     def string_to_entry (s):
255         fields = s.split('@')
256         fields[2] = string_to_tup (fields[2])
257         fields[3] = string_to_tup (fields[3])
258
259         return tuple (fields)
260     
261     entries = [string_to_entry (e) for e in entries
262                if e and not e.startswith ('#')]
263
264     grob_sigs = [GrobSignature (e) for e in entries]
265     sig = SystemSignature (grob_sigs)
266     return sig
267
268
269 ################################################################
270 # different systems of a .ly file.
271
272 class FileLink:
273     def __init__ (self):
274         self.original_name = ''
275         self.base_names = ('','')
276         self.system_links = {}
277         self._distance = None
278         
279     def add_system_link (self, link, number):
280         self.system_links[number] = link
281
282     def calc_distance (self):
283         d = 0.0
284
285         orphan_distance = 0.0
286         for l in self.system_links.values ():
287             d = max (d, l.geometric_distance ())
288             orphan_distance += l.orphan_count ()
289             
290         return d + orphan_distance
291
292     def distance (self):
293         if type (self._distance) != type (0.0):
294             return self.calc_distance ()
295         
296         return self._distance
297
298     def text_record_string (self):
299         return '%-30f %-20s\n' % (self.distance (),
300                              self.original_name)
301
302     def source_file (self):
303         for ext in ('.ly', '.ly.txt'):
304             if os.path.exists (self.base_names[1] + ext):
305                 return self.base_names[1] + ext
306         return ''
307     
308     def add_file_compare (self, f1, f2):
309         system_index = [] 
310
311         def note_system_index (m):
312             system_index.append (int (m.group (1)))
313             return ''
314         
315         base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
316         base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
317
318         self.base_names = (os.path.normpath (base1),
319                            os.path.normpath (base2))
320
321         def note_original (match):
322             self.original_name = match.group (1)
323             return ''
324         
325         if not self.original_name:
326             self.original_name = os.path.split (base1)[1]
327
328             ## ugh: drop the .ly.txt
329             for ext in ('.ly', '.ly.txt'):
330                 try:
331                     re.sub (r'\\sourcefilename "([^"]+)"',
332                             note_original, open (base1 + ext).read ())
333                 except IOError:
334                     pass
335                 
336         s1 = read_signature_file (f1)
337         s2 = read_signature_file (f2)
338
339         link = SystemLink (s1, s2)
340
341         self.add_system_link (link, system_index[0])
342
343     def link_files_for_html (self, old_dir, new_dir, dest_dir):
344         for ext in ('.png', '.ly', '-page*png'):
345             for oldnew in (0,1):
346                 for f in glob.glob (self.base_names[oldnew] + ext):
347                     print f
348                     link_file (f, dest_dir + '/' + f)
349
350     def html_record_string (self,  old_dir, new_dir):
351         def img_cell (ly, img, name):
352             if not name:
353                 name = 'source'
354             else:
355                 name = '<tt>%s</tt>' % name
356                 
357             return '''
358 <td align="center">
359 <a href="%(img)s">
360 <img src="%(img)s" style="border-style: none; max-width: 500px;">
361 </a><br>
362 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
363 </font>
364 </td>
365 ''' % locals ()
366
367         def multi_img_cell (ly, imgs, name):
368             if not name:
369                 name = 'source'
370             else:
371                 name = '<tt>%s</tt>' % name
372
373             imgs_str = '\n'.join (['''<a href="%s">
374 <img src="%s" style="border-style: none; max-width: 500px;">
375 </a><br>''' % (img, img) 
376                                   for img in imgs])
377
378
379             return '''
380 <td align="center">
381 %(imgs_str)s
382 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
383 </font>
384 </td>
385 ''' % locals ()
386
387
388
389         def cell (base, name):
390             pages = glob.glob (base + '-page*.png')
391             if pages:
392                 return multi_img_cell (base + '.ly', pages, name)
393             else:
394                 return img_cell (base + '.ly', base + '.png', name)
395             
396
397         img_1  = self.base_names[0] + '.png'
398         ly_1  = self.base_names[0] + '.ly'
399         img_2  = self.base_names[1] + '.png'
400         ly_2  = self.base_names[1] + '.ly'
401         html_2  = self.base_names[1] + '.html'
402         name = self.original_name
403         
404         html_entry = '''
405 <tr>
406 <td>
407 %f<br>
408 (<a href="%s">details</a>)
409 </td>
410
411 %s
412 %s
413 </tr>
414 ''' % (self.distance (), html_2,
415        cell (self.base_names[0], name),
416        cell (self.base_names[1], name))
417
418         return html_entry
419
420
421     def html_system_details_string (self):
422         systems = self.system_links.items ()
423         systems.sort ()
424
425         html = ""
426         for (c, link) in systems:
427             e = '<td>%d</td>' % c
428             for d in link.distance ():
429                 e += '<td>%f</td>' % d
430             
431             e = '<tr>%s</tr>' % e
432
433             html += e
434
435             e = '<td>%d</td>' % c
436             for s in (link.output_expression_details_string (),
437                       link.orphan_details_string (),
438                       link.geo_details_string ()):
439                 e += "<td>%s</td>" % s
440
441             
442             e = '<tr>%s</tr>' % e
443             html += e
444             
445         original = self.original_name
446         html = '''<html>
447 <head>
448 <title>comparison details for %(original)s</title>
449 </head>
450 <body>
451 <table border=1>
452 <tr>
453 <th>system</th>
454 <th>output</th>
455 <th>orphan</th>
456 <th>geo</th>
457 </tr>
458
459 %(html)s
460 </table>
461
462 </body>
463 </html>
464 ''' % locals ()
465         return html
466
467     def write_html_system_details (self, dir1, dir2, dest_dir):
468         dest_file =  os.path.join (dest_dir, self.base_names[1] + '.html')
469
470         details = open_write_file (dest_file)
471         details.write (self.html_system_details_string ())
472
473 ################################################################
474 # Files/directories
475
476 import glob
477 import re
478
479
480
481 def compare_signature_files (f1, f2):
482     s1 = read_signature_file (f1)
483     s2 = read_signature_file (f2)
484     
485     return SystemLink (s1, s2).distance ()
486
487 def paired_files (dir1, dir2, pattern):
488     """
489     Search DIR1 and DIR2 for PATTERN.
490
491     Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
492
493     """
494     
495     files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
496     files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
497
498     pairs = []
499     missing = []
500     for f in files1.keys ():
501         try:
502             files2.pop (f)
503             pairs.append (f)
504         except KeyError:
505             missing.append (f)
506
507     return (pairs, files2.keys (), missing)
508     
509 class ComparisonData:
510     def __init__ (self):
511         self.result_dict = {}
512         self.missing = []
513         self.added = []
514         self.file_links = {}
515
516     def compare_trees (self, dir1, dir2):
517         self.compare_directories (dir1, dir2)
518         
519         (root, dirs, files) = os.walk (dir1).next ()
520         for d in dirs:
521             d1 = os.path.join (dir1, d)
522             d2 = os.path.join (dir2, d)
523
524             if os.path.islink (d1) or os.path.islink (d2):
525                 continue
526             
527             if os.path.isdir (d2):
528                 self.compare_trees (d1, d2)
529     
530     def compare_directories (self, dir1, dir2):
531
532         (paired, m1, m2) = paired_files (dir1, dir2, '*.signature')
533
534         self.missing += [(dir1, m) for m in m1] 
535         self.added += [(dir2, m) for m in m2] 
536
537         for p in paired:
538             if (inspect_max_count
539                 and len (self.file_links) > inspect_max_count):
540                 
541                 continue
542             
543             f2 = dir2 +  '/' + p
544             f1 = dir1 +  '/' + p
545             self.compare_files (f1, f2)
546
547     def compare_files (self, f1, f2):
548         name = os.path.split (f1)[1]
549         name = re.sub ('-[0-9]+.signature', '', name)
550         
551         file_link = None
552         try:
553             file_link = self.file_links[name]
554         except KeyError:
555             file_link = FileLink ()
556             self.file_links[name] = file_link
557
558         file_link.add_file_compare (f1,f2)
559
560     def write_text_result_page (self, filename, threshold):
561         print 'writing "%s"' % filename
562         out = None
563         if filename == '':
564             out = sys.stdout
565         else:
566             out = open_write_file (filename)
567
568         ## todo: support more scores.
569         results = [(link.distance(), link)
570                    for link in self.file_links.values ()]
571         results.sort ()
572         results.reverse ()
573
574         
575         for (score, link) in results:
576             if score > threshold:
577                 out.write (link.text_record_string ())
578
579         out.write ('\n\n')
580         out.write ('%d below threshold\n' % len ([1 for s,l  in results
581                                                     if threshold >=  s > 0.0]))
582         out.write ('%d unchanged\n' % len ([1 for (s,l) in results if s == 0.0]))
583         
584     def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
585         self.write_text_result_page (dest_dir + '/index.txt', threshold)
586         
587     def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
588         dir1 = dir1.replace ('//', '/')
589         dir2 = dir2.replace ('//', '/')
590         
591         results = [(link.distance(), link)
592                    for link in self.file_links.values ()]
593         results.sort ()
594         results.reverse ()
595
596         html = ''
597         old_prefix = os.path.split (dir1)[1]
598         for (score, link) in results:
599             if score <= threshold:
600                 continue
601
602             link.link_files_for_html (dir1, dir2, dest_dir) 
603             link.write_html_system_details (dir1, dir2, dest_dir)
604             html += link.html_record_string (dir1, dir2)
605
606
607         html = '''<html>
608 <table rules="rows" border bordercolor="blue">
609 <tr>
610 <th>distance</th>
611 <th>%(dir1)s</th>
612 <th>%(dir2)s</th>
613 </tr>
614 %(html)s
615 </table>
616 </html>''' % locals()
617
618         html += ('<p>')
619         below_count  =len ([1 for s,l  in results
620                             if threshold >=  s > 0.0])
621
622         if below_count:
623             html += ('<p>%d below threshold</p>' % below_count)
624
625         html += ('<p>%d unchanged</p>'
626                  % len ([1 for (s,l) in results if s == 0.0]))
627
628
629         dest_file = dest_dir + '/index.html'
630         open_write_file (dest_file).write (html)
631         
632     def print_results (self, threshold):
633         self.write_text_result_page ('', threshold)
634
635 def compare_trees (dir1, dir2, dest_dir, threshold):
636     data = ComparisonData ()
637     data.compare_trees (dir1, dir2)
638     data.print_results (threshold)
639
640     if os.path.isdir (dest_dir):
641         system ('rm -rf %s '% dest_dir)
642
643     data.create_html_result_page (dir1, dir2, dest_dir, threshold)
644     data.create_text_result_page (dir1, dir2, dest_dir, threshold)
645     
646 ################################################################
647 # TESTING
648
649 def mkdir (x):
650     if not os.path.isdir (x):
651         print 'mkdir', x
652         os.makedirs (x)
653
654 def link_file (x, y):
655     mkdir (os.path.split (y)[0])
656     try:
657         os.link (x, y)
658     except OSError, z:
659         print 'OSError', x, y, z
660         raise OSError
661     
662 def open_write_file (x):
663     d = os.path.split (x)[0]
664     mkdir (d)
665     return open (x, 'w')
666
667
668 def system (x):
669     
670     print 'invoking', x
671     stat = os.system (x)
672     assert stat == 0
673
674
675 def test_paired_files ():
676     print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
677                         os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
678                   
679     
680 def test_compare_trees ():
681     system ('rm -rf dir1 dir2')
682     system ('mkdir dir1 dir2')
683     system ('cp 20{-*.signature,.ly,.png} dir1')
684     system ('cp 20{-*.signature,.ly,.png} dir2')
685     system ('cp 20expr{-*.signature,.ly,.png} dir1')
686     system ('cp 19{-*.signature,.ly,.png} dir2/')
687     system ('cp 19{-*.signature,.ly,.png} dir1/')
688     system ('cp 19-1.signature 19-sub-1.signature')
689     system ('cp 19.ly 19-sub.ly')
690     system ('cp 19.png 19-sub.png')
691
692     system ('cp 20multipage* dir1')
693     system ('cp 20multipage* dir2')
694     system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
695
696     
697     system ('mkdir -p dir1/subdir/ dir2/subdir/')
698     system ('cp 19-sub{-*.signature,.ly,.png} dir1/subdir/')
699     system ('cp 19-sub{-*.signature,.ly,.png} dir2/subdir/')
700     system ('cp 20grob{-*.signature,.ly,.png} dir2/')
701     system ('cp 20grob{-*.signature,.ly,.png} dir1/')
702
703     ## introduce differences
704     system ('cp 19-1.signature dir2/20-1.signature')
705     system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
706
707     ## radical diffs.
708     system ('cp 19-1.signature dir2/20grob-1.signature')
709     system ('cp 19-1.signature dir2/20grob-2.signature')
710
711     compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
712
713
714 def test_basic_compare ():
715     ly_template = r"""
716 #(set! toplevel-score-handler print-score-with-defaults)
717  #(set! toplevel-music-handler
718   (lambda (p m)
719   (if (not (eq? (ly:music-property m 'void) #t))
720      (print-score-with-defaults
721      p (scorify-music m p)))))
722
723 \sourcefilename "my-source.ly"
724  
725 %(papermod)s
726 \header { tagline = ##f } 
727 <<
728 \new Staff \relative c {
729   c4^"%(userstring)s" %(extragrob)s
730   }
731 \new Staff \relative c {
732   c4^"%(userstring)s" %(extragrob)s
733   }
734 >>
735 """
736
737     dicts = [{ 'papermod' : '',
738                'name' : '20',
739                'extragrob': '',
740                'userstring': 'test' },
741              { 'papermod' : '#(set-global-staff-size 19.5)',
742                'name' : '19',
743                'extragrob': '',
744                'userstring': 'test' },
745              { 'papermod' : '',
746                'name' : '20expr',
747                'extragrob': '',
748                'userstring': 'blabla' },
749              { 'papermod' : '',
750                'name' : '20grob',
751                'extragrob': 'r2. \\break c1',
752                'userstring': 'test' },
753                 
754              ]
755
756     for d in dicts:
757         open (d['name'] + '.ly','w').write (ly_template % d)
758         
759     names = [d['name'] for d in dicts]
760     
761     system ('lilypond -ddump-signatures --png -b eps ' + ' '.join (names))
762     
763
764     multipage_str = r'''
765     #(set-default-paper-size "a6")
766     {c1 \pageBreak c1 }
767     '''
768
769     open ('20multipage', 'w').write (multipage_str)
770     open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
771     system ('lilypond -ddump-signatures --png 19multipage 20multipage ')
772  
773     test_compare_signatures (names)
774     
775 def test_compare_signatures (names, timing=False):
776
777     import time
778
779     times = 1
780     if timing:
781         times = 100
782
783     t0 = time.clock ()
784
785     count = 0
786     for t in range (0, times):
787         sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
788         count += 1
789
790     if timing:
791         print 'elapsed', (time.clock() - t0)/count
792
793
794     t0 = time.clock ()
795     count = 0
796     combinations = {}
797     for (n1, s1) in sigs.items():
798         for (n2, s2) in sigs.items():
799             combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
800             count += 1
801
802     if timing:
803         print 'elapsed', (time.clock() - t0)/count
804
805     results = combinations.items ()
806     results.sort ()
807     for k,v in results:
808         print '%-20s' % k, v
809
810     assert combinations['20-20'] == (0.0,0.0,0.0)
811     assert combinations['20-20expr'][0] > 0.0
812     assert combinations['20-19'][2] < 10.0
813     assert combinations['20-19'][2] > 0.0
814
815
816 def run_tests ():
817     dir = 'output-distance-test'
818
819     do_clean = not os.path.exists (dir)
820
821     print 'test results in ', dir
822     if do_clean:
823         system ('rm -rf ' + dir)
824         system ('mkdir ' + dir)
825         
826     os.chdir (dir)
827     if do_clean:
828         test_basic_compare ()
829         
830     test_compare_trees ()
831     
832 ################################################################
833 #
834
835 def main ():
836     p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
837     p.usage = 'output-distance.py [options] tree1 tree2'
838     
839     p.add_option ('', '--test-self',
840                   dest="run_test",
841                   action="store_true",
842                   help='run test method')
843     
844     p.add_option ('--max-count',
845                   dest="max_count",
846                   metavar="COUNT",
847                   type="int",
848                   default=0, 
849                   action="store",
850                   help='only analyze COUNT signature pairs')
851
852     p.add_option ('', '--threshold',
853                   dest="threshold",
854                   default=0.3,
855                   action="store",
856                   type="float",
857                   help='threshold for geometric distance')
858
859     (o,a) = p.parse_args ()
860
861     if o.run_test:
862         run_tests ()
863         sys.exit (0)
864
865     if len (a) != 2:
866         p.print_usage()
867         sys.exit (2)
868
869     global inspect_max_count
870     inspect_max_count = o.max_count
871
872     compare_trees (a[0], a[1], os.path.join (a[1],  'compare-' +  a[0]),
873                    o.threshold)
874
875 if __name__ == '__main__':
876     main()
877