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
28 self.dir = tempfile.mkdtemp ()
29 print 'dir is', self.dir
31 print 'rm -rf %s' % self.dir
32 os.system ('rm -rf %s' % self.dir )
40 temp_dir = TempDirectory ()
45 return os.popen (c).read ()
51 raise Exception ("failed")
54 def shorten_string (s):
56 if len (s) > 2*threshold:
57 s = s[:threshold] + '..' + s[-threshold:]
60 def max_distance (x1, x2):
63 for (p,q) in zip (x1, x2):
64 dist = max (abs (p-q), dist)
68 empty_interval = (INFTY, -INFTY)
69 empty_bbox = (empty_interval, empty_interval)
71 def interval_is_empty (i):
74 def interval_length (i):
75 return max (i[1]-i[0], 0)
77 def interval_union (i1, i2):
78 return (min (i1[0], i2[0]),
81 def interval_intersect (i1, i2):
82 return (max (i1[0], i2[0]),
85 def bbox_is_empty (b):
86 return (interval_is_empty (b[0])
87 or interval_is_empty (b[1]))
89 def bbox_union (b1, b2):
90 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
91 interval_union (b2[Y_AXIS], b2[Y_AXIS]))
93 def bbox_intersection (b1, b2):
94 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
95 interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
98 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
100 def bbox_diameter (b):
101 return max (interval_length (b[X_AXIS]),
102 interval_length (b[Y_AXIS]))
105 def difference_area (a, b):
106 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
109 def __init__ (self, exp_list):
110 (self.name, self.origin, bbox_x,
111 bbox_y, self.output_expression) = tuple (exp_list)
113 self.bbox = (bbox_x, bbox_y)
114 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
117 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
123 def axis_centroid (self, axis):
124 return apply (sum, self.bbox[axis]) / 2
126 def centroid_distance (self, other, scale):
127 return max_distance (self.centroid, other.centroid) / scale
129 def bbox_distance (self, other):
130 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
133 return (difference_area (self.bbox, other.bbox) +
134 difference_area (other.bbox, self.bbox)) / divisor
138 def expression_distance (self, other):
139 if self.output_expression == other.output_expression:
144 ################################################################
147 class SystemSignature:
148 def __init__ (self, grob_sigs):
151 val = d.setdefault (g.name, [])
155 self.set_all_bbox (grob_sigs)
157 def set_all_bbox (self, grobs):
158 self.bbox = empty_bbox
160 self.bbox = bbox_union (g.bbox, self.bbox)
162 def closest (self, grob_name, centroid):
166 grobs = self.grob_dict[grob_name]
169 d = max_distance (g.centroid, centroid)
180 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
182 ################################################################
183 ## comparison of systems.
186 def __init__ (self, system1, system2):
187 self.system1 = system1
188 self.system2 = system2
190 self.link_list_dict = {}
191 self.back_link_dict = {}
198 self.geo_distances = {}
201 self.expression_changed = []
203 self._geometric_distance = None
204 self._expression_change_count = None
205 self._orphan_count = None
207 for g in system1.grobs ():
209 ## skip empty bboxes.
210 if bbox_is_empty (g.bbox):
213 closest = system2.closest (g.name, g.centroid)
215 self.link_list_dict.setdefault (closest, [])
216 self.link_list_dict[closest].append (g)
217 self.back_link_dict[g] = closest
220 def calc_geometric_distance (self):
222 for (g1,g2) in self.back_link_dict.items ():
224 d = g1.bbox_distance (g2)
226 self.geo_distances[(g1,g2)] = d
230 self._geometric_distance = total
232 def calc_orphan_count (self):
234 for (g1, g2) in self.back_link_dict.items ():
236 self.orphans.append ((g1, None))
240 self._orphan_count = count
242 def calc_output_exp_distance (self):
244 for (g1,g2) in self.back_link_dict.items ():
246 d += g1.expression_distance (g2)
248 self._expression_change_count = d
250 def output_expression_details_string (self):
251 return ', '.join ([g1.name for g1 in self.expression_changed])
253 def geo_details_string (self):
254 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
258 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
260 def orphan_details_string (self):
261 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
263 def geometric_distance (self):
264 if self._geometric_distance == None:
265 self.calc_geometric_distance ()
266 return self._geometric_distance
268 def orphan_count (self):
269 if self._orphan_count == None:
270 self.calc_orphan_count ()
272 return self._orphan_count
274 def output_expression_change_count (self):
275 if self._expression_change_count == None:
276 self.calc_output_exp_distance ()
277 return self._expression_change_count
280 return (self.output_expression_change_count (),
281 self.orphan_count (),
282 self.geometric_distance ())
284 def read_signature_file (name):
285 print 'reading', name
287 entries = open (name).read ().split ('\n')
288 def string_to_tup (s):
289 return tuple (map (float, s.split (' ')))
291 def string_to_entry (s):
292 fields = s.split('@')
293 fields[2] = string_to_tup (fields[2])
294 fields[3] = string_to_tup (fields[3])
296 return tuple (fields)
298 entries = [string_to_entry (e) for e in entries
299 if e and not e.startswith ('#')]
301 grob_sigs = [GrobSignature (e) for e in entries]
302 sig = SystemSignature (grob_sigs)
306 ################################################################
307 # different systems of a .ly file.
309 hash_to_original_name = {}
311 def compare_png_images (old, new, dest_dir):
313 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
315 return tuple (map (int, m.groups ()))
317 dest = os.path.join (dest_dir, new.replace ('.png', '.compare.jpeg'))
319 dims1 = png_dims (old)
320 dims2 = png_dims (new)
321 except AttributeError:
323 system ('touch %(dest)s' % locals ())
326 dims = (min (dims1[0], dims2[0]),
327 min (dims1[1], dims2[1]))
329 dir = get_temp_dir ()
330 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop1.png' % (dims + (old, dir)))
331 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop2.png' % (dims + (new, dir)))
333 system ('compare -depth 8 %(dir)s/crop1.png %(dir)s/crop2.png %(dir)s/diff.png' % locals ())
335 system ("convert -depth 8 %(dir)s/diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' %(dir)s/matte.png" % locals ())
337 system ("composite -quality 65 %(dir)s/matte.png %(new)s %(dest)s" % locals ())
341 self._distance = None
343 def text_record_string (self):
344 return '%-30f %-20s\n' % (self.distance (),
346 def calc_distance (self):
350 if self._distance == None:
351 self._distance = self.calc_distance ()
353 return self._distance
358 def link_files_for_html (self, old_dir, new_dir, dest_dir):
361 def write_html_system_details (self, dir1, dir2, dest_dir):
364 def html_record_string (self, old_dir, new_dir):
367 class FileCompareLink (FileLink):
368 def __init__ (self, f1, f2):
369 FileLink.__init__ (self)
370 self.files = (f1, f2)
371 self.contents = (self.get_content (self.files[0]),
372 self.get_content (self.files[1]))
374 def link_files_for_html (self, old_dir, new_dir, dest_dir):
376 link_file (f, os.path.join (dest_dir, f))
378 def extension (self):
382 name = os.path.basename (self.files[0])
383 name = os.path.splitext (name)[0]
384 name = hash_to_original_name.get (name, name)
386 name = os.path.splitext (name)[0] + self.extension ()
389 def calc_distance (self):
390 ## todo: could use import MIDI to pinpoint
391 ## what & where changed.
393 if self.contents[0] == self.contents[1]:
398 def html_record_string (self, d1, d2):
399 (dist, f1, f2) = (self.distance(),) + self.files
400 b1 = os.path.basename (f1)
401 b2 = os.path.basename (f2)
407 <td><a href="%(f1)s"><tt>%(b1)s</tt></td>
408 <td><a href="%(f2)s"><tt>%(b2)s</tt></td>
411 def get_content (self, f):
417 class TextFileCompareLink (FileCompareLink):
418 def calc_distance (self):
420 diff = difflib.unified_diff (self.contents[0].strip().split ('\n'),
421 self.contents[1].strip().split ('\n'),
422 fromfiledate = self.files[0],
423 tofiledate = self.files[1]
426 self.diff_lines = [l for l in diff]
427 return float (len (self.diff_lines))
429 def link_files_for_html (self, old_dir, new_dir, dest_dir):
430 str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
431 f = os.path.join (new_dir, self.name ()) + '.diff.txt'
432 f = os.path.join (dest_dir, f)
433 open_write_file (f).write (str)
435 def extension (self):
438 def html_record_string (self, d1, d2):
439 (dist, f1, f2) = (self.distance(),) + self.files
440 b1 = os.path.basename (f1)
441 b2 = os.path.basename (f2)
448 <td><a href="%s.diff.txt"><tt>%s</tt></a></td>
451 os.path.join (d2, self.name ()),
455 class ProfileFileLink (TextFileCompareLink):
456 def extension (self):
459 def calc_distance (self):
460 TextFileCompareLink.calc_distance (self)
465 r[oldnew][m.group(1)] = float (m.group (2))
467 re.sub ('([a-z]+): ([-0-9.]+)\n',
468 note_info, self.contents[oldnew])
471 factor = {'time': 1.0 ,
475 for k in ('time', 'cells'):
476 (v1,v2) = (r[0].get (k , -1),
479 if v1 <= 0 or v2 <= 0:
482 ratio = abs (v2 - v1) / float (v1+v2)
483 dist += math.exp (ratio * factor[k]) - 1
485 dist = min (dist, 100)
489 class MidiFileLink (FileCompareLink):
490 def get_content (self, f):
491 s = FileCompareLink.get_content (self, f)
492 s = re.sub ('LilyPond [0-9.]+', '', s)
495 def extension (self):
499 class SignatureFileLink (FileLink):
501 FileLink.__init__ (self)
502 self.base_names = ('','')
503 self.system_links = {}
505 def extension (self):
510 base = os.path.basename (self.base_names[1])
511 base = os.path.splitext (base)[0]
513 base = hash_to_original_name.get (base, base)
514 base = os.path.splitext (base)[0] + self.extension ()
517 def add_system_link (self, link, number):
518 self.system_links[number] = link
520 def calc_distance (self):
523 orphan_distance = 0.0
524 for l in self.system_links.values ():
525 d = max (d, l.geometric_distance ())
526 orphan_distance += l.orphan_count ()
528 return d + orphan_distance
530 def source_file (self):
531 for ext in ('.ly', '.ly.txt'):
532 if os.path.exists (self.base_names[1] + ext):
533 return self.base_names[1] + ext
536 def add_file_compare (self, f1, f2):
539 def note_system_index (m):
540 system_index.append (int (m.group (1)))
543 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
544 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
546 self.base_names = (os.path.normpath (base1),
547 os.path.normpath (base2))
549 def note_original (match):
550 hash_to_original_name[os.path.basename (self.base_names[1])] = match.group (1)
553 ## ugh: drop the .ly.txt
554 for ext in ('.ly', '.ly.txt'):
556 re.sub (r'\\sourcefilename "([^"]+)"',
557 note_original, open (base1 + ext).read ())
561 s1 = read_signature_file (f1)
562 s2 = read_signature_file (f2)
564 link = SystemLink (s1, s2)
566 self.add_system_link (link, system_index[0])
569 def create_images (self, old_dir, new_dir, dest_dir):
571 files_created = [[], []]
572 for oldnew in (0, 1):
573 pat = self.base_names[oldnew] + '.eps'
575 for f in glob.glob (pat):
577 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
579 mkdir (os.path.split (outfile)[0])
580 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
582 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
583 ' %(infile)s -c quit ' % locals ())
585 files_created[oldnew].append (outfile)
590 def link_files_for_html (self, old_dir, new_dir, dest_dir):
591 to_compare = [[], []]
594 if options.create_images:
595 to_compare = self.create_images (old_dir, new_dir, dest_dir)
597 exts += ['.png', '-page*png']
601 for f in glob.glob (self.base_names[oldnew] + ext):
602 dst = dest_dir + '/' + f
605 if f.endswith ('.png'):
606 to_compare[oldnew].append (f)
608 if options.compare_images:
609 for (old, new) in zip (to_compare[0], to_compare[1]):
610 compare_png_images (old, new, dest_dir)
613 def html_record_string (self, old_dir, new_dir):
614 def img_cell (ly, img, name):
618 name = '<tt>%s</tt>' % name
623 <img src="%(img)s" style="border-style: none; max-width: 500px;">
625 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
629 def multi_img_cell (ly, imgs, name):
633 name = '<tt>%s</tt>' % name
635 imgs_str = '\n'.join (['''<a href="%s">
636 <img src="%s" style="border-style: none; max-width: 500px;">
637 </a><br>''' % (img, img)
644 <font size="-2">(<a href="%(ly)s">%(name)s</a>)
651 def cell (base, name):
652 pat = base + '-page*.png'
653 pages = glob.glob (pat)
656 return multi_img_cell (base + '.ly', sorted (pages), name)
658 return img_cell (base + '.ly', base + '.png', name)
661 html_2 = self.base_names[1] + '.html'
664 cell_1 = cell (self.base_names[0], name)
665 cell_2 = cell (self.base_names[1], name)
666 if options.compare_images:
667 cell_2 = cell_2.replace ('.png', '.compare.jpeg')
673 (<a href="%s">details</a>)
679 ''' % (self.distance (), html_2, cell_1, cell_2)
684 def html_system_details_string (self):
685 systems = self.system_links.items ()
689 for (c, link) in systems:
690 e = '<td>%d</td>' % c
691 for d in link.distance ():
692 e += '<td>%f</td>' % d
694 e = '<tr>%s</tr>' % e
698 e = '<td>%d</td>' % c
699 for s in (link.output_expression_details_string (),
700 link.orphan_details_string (),
701 link.geo_details_string ()):
702 e += "<td>%s</td>" % s
705 e = '<tr>%s</tr>' % e
708 original = self.name ()
711 <title>comparison details for %(original)s</title>
730 def write_html_system_details (self, dir1, dir2, dest_dir):
731 dest_file = os.path.join (dest_dir, self.base_names[1] + '.html')
733 details = open_write_file (dest_file)
734 details.write (self.html_system_details_string ())
736 ################################################################
742 def compare_signature_files (f1, f2):
743 s1 = read_signature_file (f1)
744 s2 = read_signature_file (f2)
746 return SystemLink (s1, s2).distance ()
748 def paired_files (dir1, dir2, pattern):
750 Search DIR1 and DIR2 for PATTERN.
752 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
756 files1 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir1 + '/' + pattern))
757 files2 = dict ((os.path.split (f)[1], 1) for f in glob.glob (dir2 + '/' + pattern))
761 for f in files1.keys ():
768 return (pairs, files2.keys (), missing)
770 class ComparisonData:
772 self.result_dict = {}
777 def compare_trees (self, dir1, dir2):
778 self.compare_directories (dir1, dir2)
780 (root, dirs, files) = os.walk (dir1).next ()
782 d1 = os.path.join (dir1, d)
783 d2 = os.path.join (dir2, d)
785 if os.path.islink (d1) or os.path.islink (d2):
788 if os.path.isdir (d2):
789 self.compare_trees (d1, d2)
791 def compare_directories (self, dir1, dir2):
792 for ext in ['signature', 'midi', 'log', 'profile']:
793 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
795 self.missing += [(dir1, m) for m in m1]
796 self.added += [(dir2, m) for m in m2]
799 if (options.max_count
800 and len (self.file_links) > options.max_count):
806 self.compare_files (f1, f2)
808 def compare_files (self, f1, f2):
809 if f1.endswith ('signature'):
810 self.compare_signature_files (f1, f2)
812 ext = os.path.splitext (f1)[1]
814 '.midi': MidiFileLink,
815 '.log' : TextFileCompareLink,
816 '.profile': ProfileFileLink,
819 if klasses.has_key (ext):
820 self.compare_general_files (klasses[ext], f1, f2)
822 def compare_general_files (self, klass, f1, f2):
823 name = os.path.split (f1)[1]
825 file_link = klass (f1, f2)
826 self.file_links[name] = file_link
828 def compare_signature_files (self, f1, f2):
829 name = os.path.split (f1)[1]
830 name = re.sub ('-[0-9]+.signature', '', name)
834 file_link = self.file_links[name]
836 file_link = SignatureFileLink ()
837 self.file_links[name] = file_link
839 file_link.add_file_compare (f1, f2)
841 def remove_changed (self, dir, threshold):
842 (changed, below, unchanged) = self.thresholded_results (threshold)
845 system ('rm -f %s*' % link.base_names[1])
846 except AttributeError: ### UGH.
847 system ('rm -f %s/%s*' % (dir, link.name ()))
848 def thresholded_results (self, threshold):
849 ## todo: support more scores.
850 results = [(link.distance(), link)
851 for link in self.file_links.values ()]
855 unchanged = [r for (d,r) in results if d == 0.0]
856 below = [r for (d,r) in results if threshold >= d > 0.0]
857 changed = [r for (d,r) in results if d > threshold]
859 return (changed, below, unchanged)
861 def write_text_result_page (self, filename, threshold):
866 print 'writing "%s"' % filename
867 out = open_write_file (filename)
869 (changed, below, unchanged) = self.thresholded_results (threshold)
873 out.write (link.text_record_string ())
876 out.write ('%d below threshold\n' % len (below))
877 out.write ('%d unchanged\n' % len (unchanged))
879 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
880 self.write_text_result_page (dest_dir + '/index.txt', threshold)
882 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
883 dir1 = dir1.replace ('//', '/')
884 dir2 = dir2.replace ('//', '/')
886 (changed, below, unchanged) = self.thresholded_results (threshold)
890 old_prefix = os.path.split (dir1)[1]
892 link.link_files_for_html (dir1, dir2, dest_dir)
893 link.write_html_system_details (dir1, dir2, dest_dir)
895 html += link.html_record_string (dir1, dir2)
898 short_dir1 = shorten_string (dir1)
899 short_dir2 = shorten_string (dir2)
901 <table rules="rows" border bordercolor="blue">
904 <th>%(short_dir1)s</th>
905 <th>%(short_dir2)s</th>
909 </html>''' % locals()
912 below_count = len (below)
915 html += ('<p>%d below threshold</p>' % below_count)
917 html += ('<p>%d unchanged</p>' % len (unchanged))
919 dest_file = dest_dir + '/index.html'
920 open_write_file (dest_file).write (html)
922 def print_results (self, threshold):
923 self.write_text_result_page ('', threshold)
925 def compare_trees (dir1, dir2, dest_dir, threshold):
926 data = ComparisonData ()
927 data.compare_trees (dir1, dir2)
928 data.print_results (threshold)
930 if options.remove_changed:
931 data.remove_changed (dir2, threshold)
934 if os.path.isdir (dest_dir):
935 system ('rm -rf %s '% dest_dir)
937 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
938 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
940 ################################################################
944 if not os.path.isdir (x):
948 def link_file (x, y):
949 mkdir (os.path.split (y)[0])
953 print 'OSError', x, y, z
956 def open_write_file (x):
957 d = os.path.split (x)[0]
969 def test_paired_files ():
970 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
971 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
974 def test_compare_trees ():
975 system ('rm -rf dir1 dir2')
976 system ('mkdir dir1 dir2')
977 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
978 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
979 system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
980 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
981 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
982 system ('cp 19-1.signature 19-sub-1.signature')
983 system ('cp 19.ly 19-sub.ly')
984 system ('cp 19.profile 19-sub.profile')
985 system ('cp 19.log 19-sub.log')
986 system ('cp 19.png 19-sub.png')
987 system ('cp 19.eps 19-sub.eps')
989 system ('cp 20multipage* dir1')
990 system ('cp 20multipage* dir2')
991 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
994 system ('mkdir -p dir1/subdir/ dir2/subdir/')
995 system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
996 system ('cp 19-sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
997 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
998 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1000 ## introduce differences
1001 system ('cp 19-1.signature dir2/20-1.signature')
1002 system ('cp 19.profile dir2/20.profile')
1003 system ('cp 19.png dir2/20.png')
1004 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1005 system ('cp 20-1.signature dir2/subdir/19-sub-1.signature')
1006 system ('cp 20.png dir2/subdir/19-sub.png')
1007 system ("sed 's/: /: 1/g' 20.profile > dir2/subdir/19-sub.profile")
1010 system ('cp 19-1.signature dir2/20grob-1.signature')
1011 system ('cp 19-1.signature dir2/20grob-2.signature')
1012 system ('cp 19multipage.midi dir1/midi-differ.midi')
1013 system ('cp 20multipage.midi dir2/midi-differ.midi')
1014 system ('cp 19multipage.log dir1/log-differ.log')
1015 system ('cp 19multipage.log dir2/log-differ.log && echo different >> dir2/log-differ.log && echo different >> dir2/log-differ.log')
1017 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', 0.5)
1020 def test_basic_compare ():
1024 #(define default-toplevel-book-handler
1025 print-book-with-defaults-as-systems )
1027 #(ly:set-option (quote no-point-and-click))
1029 \sourcefilename "my-source.ly"
1032 \header { tagline = ##f }
1035 \new Staff \relative c {
1036 c4^"%(userstring)s" %(extragrob)s
1038 \new Staff \relative c {
1039 c4^"%(userstring)s" %(extragrob)s
1047 dicts = [{ 'papermod' : '',
1050 'userstring': 'test' },
1051 { 'papermod' : '#(set-global-staff-size 19.5)',
1054 'userstring': 'test' },
1058 'userstring': 'blabla' },
1061 'extragrob': 'r2. \\break c1',
1062 'userstring': 'test' },
1066 open (d['name'] + '.ly','w').write (ly_template % d)
1068 names = [d['name'] for d in dicts]
1070 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1073 multipage_str = r'''
1074 #(set-default-paper-size "a6")
1076 \relative {c1 \pageBreak c1 }
1082 open ('20multipage', 'w').write (multipage_str.replace ('c1', 'd1'))
1083 open ('19multipage', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1084 system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1086 test_compare_signatures (names)
1088 def test_compare_signatures (names, timing=False):
1099 for t in range (0, times):
1100 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1104 print 'elapsed', (time.clock() - t0)/count
1110 for (n1, s1) in sigs.items():
1111 for (n2, s2) in sigs.items():
1112 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1116 print 'elapsed', (time.clock() - t0)/count
1118 results = combinations.items ()
1121 print '%-20s' % k, v
1123 assert combinations['20-20'] == (0.0,0.0,0.0)
1124 assert combinations['20-20expr'][0] > 0.0
1125 assert combinations['20-19'][2] < 10.0
1126 assert combinations['20-19'][2] > 0.0
1130 dir = 'test-output-distance'
1132 do_clean = not os.path.exists (dir)
1134 print 'test results in ', dir
1136 system ('rm -rf ' + dir)
1137 system ('mkdir ' + dir)
1141 test_basic_compare ()
1143 test_compare_trees ()
1145 ################################################################
1149 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1150 p.usage = 'output-distance.py [options] tree1 tree2'
1152 p.add_option ('', '--test-self',
1154 action="store_true",
1155 help='run test method')
1157 p.add_option ('--max-count',
1163 help='only analyze COUNT signature pairs')
1165 p.add_option ('', '--threshold',
1170 help='threshold for geometric distance')
1173 p.add_option ('--remove-changed',
1174 dest="remove_changed",
1176 action="store_true",
1177 help="Remove all files from tree2 that are over the threshold.")
1179 p.add_option ('--no-compare-images',
1180 dest="compare_images",
1182 action="store_false",
1183 help="Don't run graphical comparisons")
1185 p.add_option ('--create-images',
1186 dest="create_images",
1188 action="store_true",
1189 help="Create PNGs from EPSes")
1191 p.add_option ('-o', '--output-dir',
1196 help='where to put the test results [tree2/compare-tree1tree2]')
1199 (options, a) = p.parse_args ()
1201 if options.run_test:
1209 name = options.output_dir
1211 name = a[0].replace ('/', '')
1212 name = os.path.join (a[1], 'compare-' + shorten_string (name))
1214 compare_trees (a[0], a[1], name, options.threshold)
1216 if __name__ == '__main__':