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/')
19 OUTPUT_EXPRESSION_PENALTY = 1
20 ORPHAN_GROB_PENALTY = 1
23 def shorten_string (s):
25 if len (s) > 2*threshold:
26 s = s[:threshold] + '..' + s[-threshold:]
29 def max_distance (x1, x2):
32 for (p,q) in zip (x1, x2):
33 dist = max (abs (p-q), dist)
38 empty_interval = (INFTY, -INFTY)
39 empty_bbox = (empty_interval, empty_interval)
41 def interval_is_empty (i):
44 def interval_length (i):
45 return max (i[1]-i[0], 0)
47 def interval_union (i1, i2):
48 return (min (i1[0], i2[0]),
51 def interval_intersect (i1, i2):
52 return (max (i1[0], i2[0]),
55 def bbox_is_empty (b):
56 return (interval_is_empty (b[0])
57 or interval_is_empty (b[1]))
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]))
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]))
68 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
70 def bbox_diameter (b):
71 return max (interval_length (b[X_AXIS]),
72 interval_length (b[Y_AXIS]))
75 def difference_area (a, b):
76 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
79 def __init__ (self, exp_list):
80 (self.name, self.origin, bbox_x,
81 bbox_y, self.output_expression) = tuple (exp_list)
83 self.bbox = (bbox_x, bbox_y)
84 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
87 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
93 def axis_centroid (self, axis):
94 return apply (sum, self.bbox[axis]) / 2
96 def centroid_distance (self, other, scale):
97 return max_distance (self.centroid, other.centroid) / scale
99 def bbox_distance (self, other):
100 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
103 return (difference_area (self.bbox, other.bbox) +
104 difference_area (other.bbox, self.bbox)) / divisor
108 def expression_distance (self, other):
109 if self.output_expression == other.output_expression:
114 ################################################################
117 class SystemSignature:
118 def __init__ (self, grob_sigs):
121 val = d.setdefault (g.name, [])
125 self.set_all_bbox (grob_sigs)
127 def set_all_bbox (self, grobs):
128 self.bbox = empty_bbox
130 self.bbox = bbox_union (g.bbox, self.bbox)
132 def closest (self, grob_name, centroid):
136 grobs = self.grob_dict[grob_name]
139 d = max_distance (g.centroid, centroid)
150 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
152 ################################################################
153 ## comparison of systems.
156 def __init__ (self, system1, system2):
157 self.system1 = system1
158 self.system2 = system2
160 self.link_list_dict = {}
161 self.back_link_dict = {}
168 self.geo_distances = {}
171 self.expression_changed = []
173 self._geometric_distance = None
174 self._expression_change_count = None
175 self._orphan_count = None
177 for g in system1.grobs ():
179 ## skip empty bboxes.
180 if bbox_is_empty (g.bbox):
183 closest = system2.closest (g.name, g.centroid)
185 self.link_list_dict.setdefault (closest, [])
186 self.link_list_dict[closest].append (g)
187 self.back_link_dict[g] = closest
190 def calc_geometric_distance (self):
192 for (g1,g2) in self.back_link_dict.items ():
194 d = g1.bbox_distance (g2)
196 self.geo_distances[(g1,g2)] = d
200 self._geometric_distance = total
202 def calc_orphan_count (self):
204 for (g1, g2) in self.back_link_dict.items ():
206 self.orphans.append ((g1, None))
210 self._orphan_count = count
212 def calc_output_exp_distance (self):
214 for (g1,g2) in self.back_link_dict.items ():
216 d += g1.expression_distance (g2)
218 self._expression_change_count = d
220 def output_expression_details_string (self):
221 return ', '.join ([g1.name for g1 in self.expression_changed])
223 def geo_details_string (self):
224 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
228 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
230 def orphan_details_string (self):
231 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
233 def geometric_distance (self):
234 if self._geometric_distance == None:
235 self.calc_geometric_distance ()
236 return self._geometric_distance
238 def orphan_count (self):
239 if self._orphan_count == None:
240 self.calc_orphan_count ()
242 return self._orphan_count
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
250 return (self.output_expression_change_count (),
251 self.orphan_count (),
252 self.geometric_distance ())
254 def read_signature_file (name):
255 print 'reading', name
257 entries = open (name).read ().split ('\n')
258 def string_to_tup (s):
259 return tuple (map (float, s.split (' ')))
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])
266 return tuple (fields)
268 entries = [string_to_entry (e) for e in entries
269 if e and not e.startswith ('#')]
271 grob_sigs = [GrobSignature (e) for e in entries]
272 sig = SystemSignature (grob_sigs)
276 ################################################################
277 # different systems of a .ly file.
280 return os.popen (c).read ()
286 raise Exception ("failed")
289 def compare_png_images (old, new, dir):
291 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
293 return tuple (map (int, m.groups ()))
295 dest = os.path.join (dir, new.replace ('.png', '.compare.jpeg'))
297 dims1 = png_dims (old)
298 dims2 = png_dims (new)
299 except AttributeError:
301 system ('touch %(dest)s' % locals ())
304 dims = (min (dims1[0], dims2[0]),
305 min (dims1[1], dims2[1]))
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,)))
310 system ('compare -depth 8 crop1.png crop2.png diff.png')
312 system ("convert -depth 8 diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' matte.png")
314 system ("composite -quality 65 matte.png %(new)s %(dest)s" % locals ())
318 self._distance = None
320 def text_record_string (self):
321 return '%-30f %-20s\n' % (self.distance (),
323 def calc_distance (self):
327 if self._distance == None:
328 self._distance = self.calc_distance ()
330 return self._distance
335 def link_files_for_html (self, old_dir, new_dir, dest_dir):
338 def write_html_system_details (self, dir1, dir2, dest_dir):
341 def html_record_string (self, old_dir, new_dir):
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]))
351 def link_files_for_html (self, old_dir, new_dir, dest_dir):
353 link_file (f, os.path.join (dest_dir, f))
356 name = os.path.basename (self.files[0])
357 name = os.path.splitext (name)[0]
360 def calc_distance (self):
361 ## todo: could use import MIDI to pinpoint
362 ## what & where changed.
364 if self.contents[0] == self.contents[1]:
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)
378 <td><a href="%(f1)s"><tt>%(b1)s</tt></td>
379 <td><a href="%(f2)s"><tt>%(b2)s</tt></td>
382 def get_content (self, f):
388 class TextFileCompareLink (FileCompareLink):
389 def calc_distance (self):
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]
397 self.diff_lines = [l for l in diff]
398 return float (len (self.diff_lines))
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)
406 def html_record_string (self, d1, d2):
412 <td><a href="%s.diff.txt"><tt>%s</tt></a></td>
413 </tr>''' % (self.distance(),
415 os.path.join (d2, self.name ()),
419 class ProfileFileLink (TextFileCompareLink):
420 def calc_distance (self):
421 TextFileCompareLink.calc_distance (self)
426 r[oldnew][m.group(1)] = float (m.group (2))
428 re.sub ('([a-z]+): ([-0-9.]+)\n',
429 note_info, self.contents[oldnew])
432 factor = {'time': 1.0 ,
436 for k in ('time', 'cells'):
437 (v1,v2) = (r[0].get (k , -1),
440 if v1 <= 0 or v2 <= 0:
443 ratio = abs (v2 - v1) / float (v1+v2)
444 dist += math.exp (ratio * factor[k]) - 1
446 dist = min (dist, 100)
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)
456 class SignatureFileLink (FileLink):
458 FileLink.__init__ (self)
459 self.original_name = ''
460 self.base_names = ('','')
461 self.system_links = {}
464 return os.path.splitext (self.original_name)[0]
466 def add_system_link (self, link, number):
467 self.system_links[number] = link
469 def calc_distance (self):
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 ()
477 return d + orphan_distance
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
485 def add_file_compare (self, f1, f2):
488 def note_system_index (m):
489 system_index.append (int (m.group (1)))
492 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
493 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
495 self.base_names = (os.path.normpath (base1),
496 os.path.normpath (base2))
498 def note_original (match):
499 self.original_name = match.group (1)
502 if not self.original_name:
503 self.original_name = os.path.split (base1)[1]
505 ## ugh: drop the .ly.txt
506 for ext in ('.ly', '.ly.txt'):
508 re.sub (r'\\sourcefilename "([^"]+)"',
509 note_original, open (base1 + ext).read ())
513 s1 = read_signature_file (f1)
514 s2 = read_signature_file (f2)
516 link = SystemLink (s1, s2)
518 self.add_system_link (link, system_index[0])
521 def create_images (self, old_dir, new_dir, dest_dir):
523 files_created = [[], []]
524 for oldnew in (0, 1):
525 pat = self.base_names[oldnew] + '.eps'
527 for f in glob.glob (pat):
529 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
531 mkdir (os.path.split (outfile)[0])
532 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
534 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
535 ' %(infile)s -c quit ' % locals ())
537 files_created[oldnew].append (outfile)
542 def link_files_for_html (self, old_dir, new_dir, dest_dir):
543 to_compare = [[], []]
546 if options.create_images:
547 to_compare = self.create_images (old_dir, new_dir, dest_dir)
549 exts += ['.png', '-page*png']
553 for f in glob.glob (self.base_names[oldnew] + ext):
554 dst = dest_dir + '/' + f
557 if f.endswith ('.png'):
558 to_compare[oldnew].append (f)
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)
565 def html_record_string (self, old_dir, new_dir):
566 def img_cell (ly, img, name):
570 name = '<tt>%s</tt>' % name
575 <img src="%(img)s" style="border-style: none; max-width: 500px;">
577 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
581 def multi_img_cell (ly, imgs, name):
585 name = '<tt>%s</tt>' % name
587 imgs_str = '\n'.join (['''<a href="%s">
588 <img src="%s" style="border-style: none; max-width: 500px;">
589 </a><br>''' % (img, img)
596 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
603 def cell (base, name):
604 pat = base + '-page*.png'
605 pages = glob.glob (pat)
608 return multi_img_cell (base + '.ly', sorted (pages), name)
610 return img_cell (base + '.ly', base + '.png', name)
613 html_2 = self.base_names[1] + '.html'
614 name = self.original_name
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')
625 (<a href="%s">details</a>)
631 ''' % (self.distance (), html_2, cell_1, cell_2)
636 def html_system_details_string (self):
637 systems = self.system_links.items ()
641 for (c, link) in systems:
642 e = '<td>%d</td>' % c
643 for d in link.distance ():
644 e += '<td>%f</td>' % d
646 e = '<tr>%s</tr>' % e
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
657 e = '<tr>%s</tr>' % e
660 original = self.original_name
663 <title>comparison details for %(original)s</title>
682 def write_html_system_details (self, dir1, dir2, dest_dir):
683 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
685 details = open_write_file (dest_file)
686 details.write (self.html_system_details_string ())
688 ################################################################
694 def compare_signature_files (f1, f2):
695 s1 = read_signature_file (f1)
696 s2 = read_signature_file (f2)
698 return SystemLink (s1, s2).distance ()
700 def paired_files (dir1, dir2, pattern):
702 Search DIR1 and DIR2 for PATTERN.
704 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
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))
713 for f in files1.keys ():
720 return (pairs, files2.keys (), missing)
722 class ComparisonData:
724 self.result_dict = {}
729 def compare_trees (self, dir1, dir2):
730 self.compare_directories (dir1, dir2)
732 (root, dirs, files) = os.walk (dir1).next ()
734 d1 = os.path.join (dir1, d)
735 d2 = os.path.join (dir2, d)
737 if os.path.islink (d1) or os.path.islink (d2):
740 if os.path.isdir (d2):
741 self.compare_trees (d1, d2)
743 def compare_directories (self, dir1, dir2):
744 for ext in ['signature', 'midi', 'log', 'profile']:
745 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
747 self.missing += [(dir1, m) for m in m1]
748 self.added += [(dir2, m) for m in m2]
751 if (options.max_count
752 and len (self.file_links) > options.max_count):
758 self.compare_files (f1, f2)
760 def compare_files (self, f1, f2):
761 if f1.endswith ('signature'):
762 self.compare_signature_files (f1, f2)
764 ext = os.path.splitext (f1)[1]
766 '.midi': MidiFileLink,
767 '.log' : TextFileCompareLink,
768 '.profile': ProfileFileLink,
771 if klasses.has_key (ext):
772 self.compare_general_files (klasses[ext], f1, f2)
774 def compare_general_files (self, klass, f1, f2):
775 name = os.path.split (f1)[1]
777 file_link = klass (f1, f2)
778 self.file_links[name] = file_link
780 def compare_signature_files (self, f1, f2):
781 name = os.path.split (f1)[1]
782 name = re.sub ('-[0-9]+.signature', '', name)
786 file_link = self.file_links[name]
788 file_link = SignatureFileLink ()
789 self.file_links[name] = file_link
791 file_link.add_file_compare (f1, f2)
793 def remove_changed (self, dir, threshold):
794 (changed, below, unchanged) = self.thresholded_results (threshold)
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 ()]
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]
811 return (changed, below, unchanged)
813 def write_text_result_page (self, filename, threshold):
818 print 'writing "%s"' % filename
819 out = open_write_file (filename)
821 (changed, below, unchanged) = self.thresholded_results (threshold)
825 out.write (link.text_record_string ())
828 out.write ('%d below threshold\n' % len (below))
829 out.write ('%d unchanged\n' % len (unchanged))
831 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
832 self.write_text_result_page (dest_dir + '/index.txt', threshold)
834 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
835 dir1 = dir1.replace ('//', '/')
836 dir2 = dir2.replace ('//', '/')
838 (changed, below, unchanged) = self.thresholded_results (threshold)
842 old_prefix = os.path.split (dir1)[1]
844 link.link_files_for_html (dir1, dir2, dest_dir)
845 link.write_html_system_details (dir1, dir2, dest_dir)
847 html += link.html_record_string (dir1, dir2)
850 short_dir1 = shorten_string (dir1)
851 short_dir2 = shorten_string (dir2)
853 <table rules="rows" border bordercolor="blue">
856 <th>%(short_dir1)s</th>
857 <th>%(short_dir2)s</th>
861 </html>''' % locals()
864 below_count = len (below)
867 html += ('<p>%d below threshold</p>' % below_count)
869 html += ('<p>%d unchanged</p>' % len (unchanged))
871 dest_file = dest_dir + '/index.html'
872 open_write_file (dest_file).write (html)
874 def print_results (self, threshold):
875 self.write_text_result_page ('', threshold)
877 def compare_trees (dir1, dir2, dest_dir, threshold):
878 data = ComparisonData ()
879 data.compare_trees (dir1, dir2)
880 data.print_results (threshold)
882 if options.remove_changed:
883 data.remove_changed (dir2, threshold)
886 if os.path.isdir (dest_dir):
887 system ('rm -rf %s '% dest_dir)
889 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
890 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
892 ################################################################
896 if not os.path.isdir (x):
900 def link_file (x, y):
901 mkdir (os.path.split (y)[0])
905 print 'OSError', x, y, z
908 def open_write_file (x):
909 d = os.path.split (x)[0]
921 def test_paired_files ():
922 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
923 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
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')
941 system ('cp 20multipage* dir1')
942 system ('cp 20multipage* dir2')
943 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
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/')
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")
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')
969 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
972 def test_basic_compare ():
976 #(define default-toplevel-book-handler
977 print-book-with-defaults-as-systems )
979 #(ly:set-option (quote no-point-and-click))
981 \sourcefilename "my-source.ly"
984 \header { tagline = ##f }
987 \new Staff \relative c {
988 c4^"%(userstring)s" %(extragrob)s
990 \new Staff \relative c {
991 c4^"%(userstring)s" %(extragrob)s
999 dicts = [{ 'papermod' : '',
1002 'userstring': 'test' },
1003 { 'papermod' : '#(set-global-staff-size 19.5)',
1006 'userstring': 'test' },
1010 'userstring': 'blabla' },
1013 'extragrob': 'r2. \\break c1',
1014 'userstring': 'test' },
1018 open (d['name'] + '.ly','w').write (ly_template % d)
1020 names = [d['name'] for d in dicts]
1022 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1025 multipage_str = r'''
1026 #(set-default-paper-size "a6")
1028 \relative {c1 \pageBreak c1 }
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 ')
1038 test_compare_signatures (names)
1040 def test_compare_signatures (names, timing=False):
1051 for t in range (0, times):
1052 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1056 print 'elapsed', (time.clock() - t0)/count
1062 for (n1, s1) in sigs.items():
1063 for (n2, s2) in sigs.items():
1064 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1068 print 'elapsed', (time.clock() - t0)/count
1070 results = combinations.items ()
1073 print '%-20s' % k, v
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
1082 dir = 'test-output-distance'
1084 do_clean = not os.path.exists (dir)
1086 print 'test results in ', dir
1088 system ('rm -rf ' + dir)
1089 system ('mkdir ' + dir)
1093 test_basic_compare ()
1095 test_compare_trees ()
1097 ################################################################
1101 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1102 p.usage = 'output-distance.py [options] tree1 tree2'
1104 p.add_option ('', '--test-self',
1106 action="store_true",
1107 help='run test method')
1109 p.add_option ('--max-count',
1115 help='only analyze COUNT signature pairs')
1117 p.add_option ('', '--threshold',
1122 help='threshold for geometric distance')
1125 p.add_option ('--remove-changed',
1126 dest="remove_changed",
1128 action="store_true",
1129 help="Remove all files from tree2 that are over the threshold.")
1131 p.add_option ('--no-compare-images',
1132 dest="compare_images",
1134 action="store_false",
1135 help="Don't run graphical comparisons")
1137 p.add_option ('--create-images',
1138 dest="create_images",
1140 action="store_true",
1141 help="Create PNGs from EPSes")
1143 p.add_option ('-o', '--output-dir',
1148 help='where to put the test results [tree2/compare-tree1tree2]')
1151 (options, a) = p.parse_args ()
1153 if options.run_test:
1161 name = options.output_dir
1163 name = a[0].replace ('/', '')
1164 name = os.path.join (a[1], 'compare-' + shorten_string (name))
1166 compare_trees (a[0], a[1], name, options.threshold)
1168 if __name__ == '__main__':