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 ################################################################
29 self.dir = tempfile.mkdtemp ()
30 print 'dir is', self.dir
32 print 'rm -rf %s' % self.dir
33 os.system ('rm -rf %s' % self.dir )
41 temp_dir = TempDirectory ()
46 return os.popen (c).read ()
52 raise Exception ("failed")
55 def shorten_string (s):
57 if len (s) > 2*threshold:
58 s = s[:threshold] + '..' + s[-threshold:]
61 def max_distance (x1, x2):
64 for (p,q) in zip (x1, x2):
65 dist = max (abs (p-q), dist)
70 def compare_png_images (old, new, dest_dir):
72 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
74 return tuple (map (int, m.groups ()))
76 dest = os.path.join (dest_dir, new.replace ('.png', '.compare.jpeg'))
78 dims1 = png_dims (old)
79 dims2 = png_dims (new)
80 except AttributeError:
82 system ('touch %(dest)s' % locals ())
85 dims = (min (dims1[0], dims2[0]),
86 min (dims1[1], dims2[1]))
89 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop1.png' % (dims + (old, dir)))
90 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop2.png' % (dims + (new, dir)))
92 system ('compare -depth 8 %(dir)s/crop1.png %(dir)s/crop2.png %(dir)s/diff.png' % locals ())
94 system ("convert -depth 8 %(dir)s/diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' %(dir)s/matte.png" % locals ())
96 system ("composite -quality 65 %(dir)s/matte.png %(new)s %(dest)s" % locals ())
99 ################################################################
100 # interval/bbox arithmetic.
102 empty_interval = (INFTY, -INFTY)
103 empty_bbox = (empty_interval, empty_interval)
105 def interval_is_empty (i):
108 def interval_length (i):
109 return max (i[1]-i[0], 0)
111 def interval_union (i1, i2):
112 return (min (i1[0], i2[0]),
115 def interval_intersect (i1, i2):
116 return (max (i1[0], i2[0]),
119 def bbox_is_empty (b):
120 return (interval_is_empty (b[0])
121 or interval_is_empty (b[1]))
123 def bbox_union (b1, b2):
124 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
125 interval_union (b2[Y_AXIS], b2[Y_AXIS]))
127 def bbox_intersection (b1, b2):
128 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
129 interval_intersect (b2[Y_AXIS], b2[Y_AXIS]))
132 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
134 def bbox_diameter (b):
135 return max (interval_length (b[X_AXIS]),
136 interval_length (b[Y_AXIS]))
139 def difference_area (a, b):
140 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
143 def __init__ (self, exp_list):
144 (self.name, self.origin, bbox_x,
145 bbox_y, self.output_expression) = tuple (exp_list)
147 self.bbox = (bbox_x, bbox_y)
148 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
151 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
157 def axis_centroid (self, axis):
158 return apply (sum, self.bbox[axis]) / 2
160 def centroid_distance (self, other, scale):
161 return max_distance (self.centroid, other.centroid) / scale
163 def bbox_distance (self, other):
164 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
167 return (difference_area (self.bbox, other.bbox) +
168 difference_area (other.bbox, self.bbox)) / divisor
172 def expression_distance (self, other):
173 if self.output_expression == other.output_expression:
178 ################################################################
181 class SystemSignature:
182 def __init__ (self, grob_sigs):
185 val = d.setdefault (g.name, [])
189 self.set_all_bbox (grob_sigs)
191 def set_all_bbox (self, grobs):
192 self.bbox = empty_bbox
194 self.bbox = bbox_union (g.bbox, self.bbox)
196 def closest (self, grob_name, centroid):
200 grobs = self.grob_dict[grob_name]
203 d = max_distance (g.centroid, centroid)
214 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
216 ################################################################
217 ## comparison of systems.
220 def __init__ (self, system1, system2):
221 self.system1 = system1
222 self.system2 = system2
224 self.link_list_dict = {}
225 self.back_link_dict = {}
232 self.geo_distances = {}
235 self.expression_changed = []
237 self._geometric_distance = None
238 self._expression_change_count = None
239 self._orphan_count = None
241 for g in system1.grobs ():
243 ## skip empty bboxes.
244 if bbox_is_empty (g.bbox):
247 closest = system2.closest (g.name, g.centroid)
249 self.link_list_dict.setdefault (closest, [])
250 self.link_list_dict[closest].append (g)
251 self.back_link_dict[g] = closest
254 def calc_geometric_distance (self):
256 for (g1,g2) in self.back_link_dict.items ():
258 d = g1.bbox_distance (g2)
260 self.geo_distances[(g1,g2)] = d
264 self._geometric_distance = total
266 def calc_orphan_count (self):
268 for (g1, g2) in self.back_link_dict.items ():
270 self.orphans.append ((g1, None))
274 self._orphan_count = count
276 def calc_output_exp_distance (self):
278 for (g1,g2) in self.back_link_dict.items ():
280 d += g1.expression_distance (g2)
282 self._expression_change_count = d
284 def output_expression_details_string (self):
285 return ', '.join ([g1.name for g1 in self.expression_changed])
287 def geo_details_string (self):
288 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
292 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
294 def orphan_details_string (self):
295 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
297 def geometric_distance (self):
298 if self._geometric_distance == None:
299 self.calc_geometric_distance ()
300 return self._geometric_distance
302 def orphan_count (self):
303 if self._orphan_count == None:
304 self.calc_orphan_count ()
306 return self._orphan_count
308 def output_expression_change_count (self):
309 if self._expression_change_count == None:
310 self.calc_output_exp_distance ()
311 return self._expression_change_count
314 return (self.output_expression_change_count (),
315 self.orphan_count (),
316 self.geometric_distance ())
318 def read_signature_file (name):
319 print 'reading', name
321 entries = open (name).read ().split ('\n')
322 def string_to_tup (s):
323 return tuple (map (float, s.split (' ')))
325 def string_to_entry (s):
326 fields = s.split('@')
327 fields[2] = string_to_tup (fields[2])
328 fields[3] = string_to_tup (fields[3])
330 return tuple (fields)
332 entries = [string_to_entry (e) for e in entries
333 if e and not e.startswith ('#')]
335 grob_sigs = [GrobSignature (e) for e in entries]
336 sig = SystemSignature (grob_sigs)
340 ################################################################
341 # different systems of a .ly file.
343 hash_to_original_name = {}
346 def __init__ (self, f1, f2):
347 self._distance = None
348 self.file_names = (f1, f2)
350 def text_record_string (self):
351 return '%-30f %-20s\n' % (self.distance (),
353 def calc_distance (self):
357 if self._distance == None:
358 self._distance = self.calc_distance ()
360 return self._distance
364 base = os.path.basename (self.file_names[1])
365 base = os.path.splitext (base)[0]
367 base = hash_to_original_name.get (base, base)
368 base = os.path.splitext (base)[0]
371 def extension (self):
372 return os.path.splitext (self.file_names[1])[1]
374 def link_files_for_html (self, dest_dir):
375 for f in self.file_names:
376 link_file (f, os.path.join (dest_dir, f))
378 def get_distance_details (self):
381 def get_cell (self, oldnew):
384 def get_file (self, oldnew):
385 return self.file_names[oldnew]
387 def html_record_string (self, dest_dir):
388 self.link_files_for_html (dest_dir)
390 dist = self.distance()
392 details = self.get_distance_details ()
394 details_base = os.path.splitext (self.file_names[1])[0]
395 details_base += '.details.html'
396 fn = dest_dir + '/' + details_base
397 open (fn, 'w').write (details)
399 details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
401 cell1 = self.get_cell (0)
402 cell2 = self.get_cell (1)
404 name = self.name () + self.extension ()
405 file1 = self.get_file (0)
406 file2 = self.get_file (1)
413 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
414 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
418 class FileCompareLink (FileLink):
419 def __init__ (self, f1, f2):
420 FileLink.__init__ (self, f1, f2)
421 self.contents = (self.get_content (self.file_names[0]),
422 self.get_content (self.file_names[1]))
425 def calc_distance (self):
426 ## todo: could use import MIDI to pinpoint
427 ## what & where changed.
429 if self.contents[0] == self.contents[1]:
434 def get_content (self, f):
440 class GitFileCompareLink (FileCompareLink):
441 def get_cell (self, oldnew):
442 return self.contents[oldnew]
444 def calc_distance (self):
445 if self.contents[0] == self.contents[1]:
448 d = 1.0001 *options.threshold
453 class TextFileCompareLink (FileCompareLink):
454 def calc_distance (self):
456 diff = difflib.unified_diff (self.contents[0].strip().split ('\n'),
457 self.contents[1].strip().split ('\n'),
458 fromfiledate = self.file_names[0],
459 tofiledate = self.file_names[1]
462 self.diff_lines = [l for l in diff]
463 self.diff_lines = self.diff_lines[2:]
465 return float (len ([l for l in self.diff_lines if l[0] in '-+']))
467 def get_cell (self, oldnew):
470 str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
471 str = '<font size="-2"><pre>%s</pre></font>' % str
475 class ProfileFileLink (FileCompareLink):
476 def __init__ (self, f1, f2):
477 FileCompareLink.__init__ (self, f1, f2)
478 self.results = [{}, {}]
480 def get_cell (self, oldnew):
482 for k in ('time', 'cells'):
484 str += '%-8s: %d\n' % (k, int (self.results[oldnew][k]))
486 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
489 return '<pre>%s</pre>' % str
491 def get_ratio (self, key):
492 (v1,v2) = (self.results[0].get (key, -1),
493 self.results[1].get (key, -1))
495 if v1 <= 0 or v2 <= 0:
498 return (v1 - v2) / float (v1+v2)
500 def calc_distance (self):
503 self.results[oldnew][m.group(1)] = float (m.group (2))
505 re.sub ('([a-z]+): ([-0-9.]+)\n',
506 note_info, self.contents[oldnew])
509 factor = {'time': 1.0 ,
513 for k in ('time', 'cells'):
514 dist += math.exp (self.get_ratio (k) * factor[k]) - 1
516 dist = min (dist, 100)
520 class MidiFileLink (FileCompareLink):
521 def get_content (self, f):
522 s = FileCompareLink.get_content (self, f)
523 s = re.sub ('LilyPond [0-9.]+', '', s)
526 def get_cell (self, oldnew):
528 if oldnew == 1 and self.distance () > 0:
533 class SignatureFileLink (FileLink):
534 def __init__ (self, f1, f2 ):
535 FileLink.__init__ (self, f1, f2)
536 self.system_links = {}
538 def add_system_link (self, link, number):
539 self.system_links[number] = link
541 def calc_distance (self):
544 orphan_distance = 0.0
545 for l in self.system_links.values ():
546 d = max (d, l.geometric_distance ())
547 orphan_distance += l.orphan_count ()
549 return d + orphan_distance
551 def source_file (self):
552 for ext in ('.ly', '.ly.txt'):
553 if os.path.exists (self.base_names[1] + ext):
554 return self.base_names[1] + ext
557 def add_file_compare (self, f1, f2):
560 def note_system_index (m):
561 system_index.append (int (m.group (1)))
564 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
565 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
567 self.base_names = (os.path.normpath (base1),
568 os.path.normpath (base2))
570 def note_original (match):
571 hash_to_original_name[os.path.basename (self.base_names[1])] = match.group (1)
574 ## ugh: drop the .ly.txt
575 for ext in ('.ly', '.ly.txt'):
577 re.sub (r'\\sourcefilename "([^"]+)"',
578 note_original, open (base1 + ext).read ())
582 s1 = read_signature_file (f1)
583 s2 = read_signature_file (f2)
585 link = SystemLink (s1, s2)
587 self.add_system_link (link, system_index[0])
590 def create_images (self, dest_dir):
592 files_created = [[], []]
593 for oldnew in (0, 1):
594 pat = self.base_names[oldnew] + '.eps'
596 for f in glob.glob (pat):
598 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
600 mkdir (os.path.split (outfile)[0])
601 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
603 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
604 ' %(infile)s -c quit ' % locals ())
606 files_created[oldnew].append (outfile)
611 def link_files_for_html (self, dest_dir):
612 FileLink.link_files_for_html (self, dest_dir)
613 to_compare = [[], []]
616 if options.create_images:
617 to_compare = self.create_images (dest_dir)
619 exts += ['.png', '-page*png']
623 for f in glob.glob (self.base_names[oldnew] + ext):
624 dst = dest_dir + '/' + f
627 if f.endswith ('.png'):
628 to_compare[oldnew].append (f)
630 if options.compare_images:
631 for (old, new) in zip (to_compare[0], to_compare[1]):
632 compare_png_images (old, new, dest_dir)
635 def get_cell (self, oldnew):
636 def img_cell (ly, img, name):
640 name = '<tt>%s</tt>' % name
644 <img src="%(img)s" style="border-style: none; max-width: 500px;">
647 def multi_img_cell (ly, imgs, name):
651 name = '<tt>%s</tt>' % name
653 imgs_str = '\n'.join (['''<a href="%s">
654 <img src="%s" style="border-style: none; max-width: 500px;">
655 </a><br>''' % (img, img)
665 def cell (base, name):
666 pat = base + '-page*.png'
667 pages = glob.glob (pat)
670 return multi_img_cell (base + '.ly', sorted (pages), name)
672 return img_cell (base + '.ly', base + '.png', name)
676 str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())
677 if options.compare_images and oldnew == 1:
678 str = str.replace ('.png', '.compare.jpeg')
683 def get_distance_details (self):
684 systems = self.system_links.items ()
688 for (c, link) in systems:
689 e = '<td>%d</td>' % c
690 for d in link.distance ():
691 e += '<td>%f</td>' % d
693 e = '<tr>%s</tr>' % e
697 e = '<td>%d</td>' % c
698 for s in (link.output_expression_details_string (),
699 link.orphan_details_string (),
700 link.geo_details_string ()):
701 e += "<td>%s</td>" % s
704 e = '<tr>%s</tr>' % e
707 original = self.name ()
710 <title>comparison details for %(original)s</title>
730 ################################################################
736 def compare_signature_files (f1, f2):
737 s1 = read_signature_file (f1)
738 s2 = read_signature_file (f2)
740 return SystemLink (s1, s2).distance ()
742 def paired_files (dir1, dir2, pattern):
744 Search DIR1 and DIR2 for PATTERN.
746 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
751 for d in (dir1,dir2):
752 found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
753 found = dict ((f, 1) for f in found)
758 for f in files[0].keys ():
765 return (pairs, files[1].keys (), missing)
767 class ComparisonData:
769 self.result_dict = {}
774 def compare_trees (self, dir1, dir2):
775 self.compare_directories (dir1, dir2)
777 (root, dirs, files) = os.walk (dir1).next ()
779 d1 = os.path.join (dir1, d)
780 d2 = os.path.join (dir2, d)
782 if os.path.islink (d1) or os.path.islink (d2):
785 if os.path.isdir (d2):
786 self.compare_trees (d1, d2)
788 def compare_directories (self, dir1, dir2):
789 for ext in ['signature', 'midi', 'log', 'profile', 'gittxt']:
790 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
792 self.missing += [(dir1, m) for m in m1]
793 self.added += [(dir2, m) for m in m2]
796 if (options.max_count
797 and len (self.file_links) > options.max_count):
802 self.compare_files (f1, f2)
804 def compare_files (self, f1, f2):
805 if f1.endswith ('signature'):
806 self.compare_signature_files (f1, f2)
808 ext = os.path.splitext (f1)[1]
810 '.midi': MidiFileLink,
811 '.log' : TextFileCompareLink,
812 '.profile': ProfileFileLink,
813 '.gittxt': GitFileCompareLink,
816 if klasses.has_key (ext):
817 self.compare_general_files (klasses[ext], f1, f2)
819 def compare_general_files (self, klass, f1, f2):
820 name = os.path.split (f1)[1]
822 file_link = klass (f1, f2)
823 self.file_links[name] = file_link
825 def compare_signature_files (self, f1, f2):
826 name = os.path.split (f1)[1]
827 name = re.sub ('-[0-9]+.signature', '', name)
831 file_link = self.file_links[name]
833 generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
834 generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
835 file_link = SignatureFileLink (generic_f1, generic_f2)
836 self.file_links[name] = file_link
838 file_link.add_file_compare (f1, f2)
840 def write_changed (self, dest_dir, threshold):
841 (changed, below, unchanged) = self.thresholded_results (threshold)
843 str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
844 for link in changed])
845 fn = dest_dir + '/changed.txt'
847 open_write_file (fn).write (str)
849 def thresholded_results (self, threshold):
850 ## todo: support more scores.
851 results = [(link.distance(), link)
852 for link in self.file_links.values ()]
856 unchanged = [r for (d,r) in results if d == 0.0]
857 below = [r for (d,r) in results if threshold >= d > 0.0]
858 changed = [r for (d,r) in results if d > threshold]
860 return (changed, below, unchanged)
862 def write_text_result_page (self, filename, threshold):
867 print 'writing "%s"' % filename
868 out = open_write_file (filename)
870 (changed, below, unchanged) = self.thresholded_results (threshold)
874 out.write (link.text_record_string ())
877 out.write ('%d below threshold\n' % len (below))
878 out.write ('%d unchanged\n' % len (unchanged))
880 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
881 self.write_text_result_page (dest_dir + '/index.txt', threshold)
883 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
884 dir1 = dir1.replace ('//', '/')
885 dir2 = dir2.replace ('//', '/')
887 (changed, below, unchanged) = self.thresholded_results (threshold)
891 old_prefix = os.path.split (dir1)[1]
893 html += link.html_record_string (dest_dir)
896 short_dir1 = shorten_string (dir1)
897 short_dir2 = shorten_string (dir2)
899 <table rules="rows" border bordercolor="blue">
902 <th>%(short_dir1)s</th>
903 <th>%(short_dir2)s</th>
907 </html>''' % locals()
910 below_count = len (below)
913 html += ('<p>%d below threshold</p>' % below_count)
915 html += ('<p>%d unchanged</p>' % len (unchanged))
917 dest_file = dest_dir + '/index.html'
918 open_write_file (dest_file).write (html)
920 def print_results (self, threshold):
921 self.write_text_result_page ('', threshold)
923 def compare_trees (dir1, dir2, dest_dir, threshold):
924 data = ComparisonData ()
925 data.compare_trees (dir1, dir2)
926 data.print_results (threshold)
928 if os.path.isdir (dest_dir):
929 system ('rm -rf %s '% dest_dir)
931 data.write_changed (dest_dir, threshold)
932 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
933 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
935 ################################################################
939 if not os.path.isdir (x):
943 def link_file (x, y):
944 mkdir (os.path.split (y)[0])
949 print 'OSError', x, y, z
952 def open_write_file (x):
953 d = os.path.split (x)[0]
965 def test_paired_files ():
966 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
967 os.environ["HOME"] + "/src/lilypond-stable/buildscripts/", '*.py')
970 def test_compare_trees ():
971 system ('rm -rf dir1 dir2')
972 system ('mkdir dir1 dir2')
973 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
974 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
975 system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
976 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
977 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
978 system ('cp 19-1.signature 19.sub-1.signature')
979 system ('cp 19.ly 19.sub.ly')
980 system ('cp 19.profile 19.sub.profile')
981 system ('cp 19.log 19.sub.log')
982 system ('cp 19.png 19.sub.png')
983 system ('cp 19.eps 19.sub.eps')
985 system ('cp 20multipage* dir1')
986 system ('cp 20multipage* dir2')
987 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
990 system ('mkdir -p dir1/subdir/ dir2/subdir/')
991 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
992 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
993 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
994 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
995 system ('echo HEAD is 1 > dir1/tree.gittxt')
996 system ('echo HEAD is 2 > dir2/tree.gittxt')
998 ## introduce differences
999 system ('cp 19-1.signature dir2/20-1.signature')
1000 system ('cp 19.profile dir2/20.profile')
1001 system ('cp 19.png dir2/20.png')
1002 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1003 system ('cp 20-1.signature dir2/subdir/19.sub-1.signature')
1004 system ('cp 20.png dir2/subdir/19.sub.png')
1005 system ("sed 's/: /: 1/g' 20.profile > dir2/subdir/19.sub.profile")
1008 system ('cp 19-1.signature dir2/20grob-1.signature')
1009 system ('cp 19-1.signature dir2/20grob-2.signature')
1010 system ('cp 19multipage.midi dir1/midi-differ.midi')
1011 system ('cp 20multipage.midi dir2/midi-differ.midi')
1012 system ('cp 19multipage.log dir1/log-differ.log')
1013 system ('cp 19multipage.log dir2/log-differ.log && echo different >> dir2/log-differ.log && echo different >> dir2/log-differ.log')
1015 compare_trees ('dir1', 'dir2', 'compare-dir1dir2', options.threshold)
1018 def test_basic_compare ():
1022 #(define default-toplevel-book-handler
1023 print-book-with-defaults-as-systems )
1025 #(ly:set-option (quote no-point-and-click))
1027 \sourcefilename "my-source.ly"
1030 \header { tagline = ##f }
1033 \new Staff \relative c {
1034 c4^"%(userstring)s" %(extragrob)s
1036 \new Staff \relative c {
1037 c4^"%(userstring)s" %(extragrob)s
1045 dicts = [{ 'papermod' : '',
1048 'userstring': 'test' },
1049 { 'papermod' : '#(set-global-staff-size 19.5)',
1052 'userstring': 'test' },
1056 'userstring': 'blabla' },
1059 'extragrob': 'r2. \\break c1',
1060 'userstring': 'test' },
1064 open (d['name'] + '.ly','w').write (ly_template % d)
1066 names = [d['name'] for d in dicts]
1068 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -b eps ' + ' '.join (names))
1071 multipage_str = r'''
1072 #(set-default-paper-size "a6")
1074 \relative {c1 \pageBreak c1 }
1080 open ('20multipage.ly', 'w').write (multipage_str.replace ('c1', 'd1'))
1081 open ('19multipage.ly', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1082 system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1084 test_compare_signatures (names)
1086 def test_compare_signatures (names, timing=False):
1097 for t in range (0, times):
1098 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1102 print 'elapsed', (time.clock() - t0)/count
1108 for (n1, s1) in sigs.items():
1109 for (n2, s2) in sigs.items():
1110 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1114 print 'elapsed', (time.clock() - t0)/count
1116 results = combinations.items ()
1119 print '%-20s' % k, v
1121 assert combinations['20-20'] == (0.0,0.0,0.0)
1122 assert combinations['20-20expr'][0] > 0.0
1123 assert combinations['20-19'][2] < 10.0
1124 assert combinations['20-19'][2] > 0.0
1128 dir = 'test-output-distance'
1130 do_clean = not os.path.exists (dir)
1132 print 'test results in ', dir
1134 system ('rm -rf ' + dir)
1135 system ('mkdir ' + dir)
1139 test_basic_compare ()
1141 test_compare_trees ()
1143 ################################################################
1147 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1148 p.usage = 'output-distance.py [options] tree1 tree2'
1150 p.add_option ('', '--test-self',
1152 action="store_true",
1153 help='run test method')
1155 p.add_option ('--max-count',
1161 help='only analyze COUNT signature pairs')
1163 p.add_option ('', '--threshold',
1168 help='threshold for geometric distance')
1170 p.add_option ('--no-compare-images',
1171 dest="compare_images",
1173 action="store_false",
1174 help="Don't run graphical comparisons")
1176 p.add_option ('--create-images',
1177 dest="create_images",
1179 action="store_true",
1180 help="Create PNGs from EPSes")
1182 p.add_option ('-o', '--output-dir',
1187 help='where to put the test results [tree2/compare-tree1tree2]')
1190 (options, a) = p.parse_args ()
1192 if options.run_test:
1200 name = options.output_dir
1202 name = a[0].replace ('/', '')
1203 name = os.path.join (a[1], 'compare-' + shorten_string (name))
1205 compare_trees (a[0], a[1], name, options.threshold)
1207 if __name__ == '__main__':