7 ## so we can call directly as scripts/build/output-distance.py
8 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
9 sys.path.insert (0, me_path + '/../python/')
10 sys.path.insert (0, me_path + '/../python/out/')
17 OUTPUT_EXPRESSION_PENALTY = 1
18 ORPHAN_GROB_PENALTY = 1
21 ################################################################
27 self.dir = tempfile.mkdtemp ()
28 print 'dir is', self.dir
30 print 'rm -rf %s' % self.dir
31 os.system ('rm -rf %s' % self.dir)
39 temp_dir = TempDirectory ()
44 return os.popen (c).read ()
50 raise Exception ("failed")
53 def shorten_string (s):
55 if len (s) > 2*threshold:
56 s = s[:threshold] + '..' + s[-threshold:]
59 def max_distance (x1, x2):
62 for (p,q) in zip (x1, x2):
63 dist = max (abs (p-q), dist)
68 def compare_png_images (old, new, dest_dir):
70 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
72 return tuple (map (int, m.groups ()))
74 dest = os.path.join (dest_dir, new.replace ('.png', '.compare.jpeg'))
76 dims1 = png_dims (old)
77 dims2 = png_dims (new)
78 except AttributeError:
80 system ('touch %(dest)s' % locals ())
83 dims = (min (dims1[0], dims2[0]),
84 min (dims1[1], dims2[1]))
87 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop1.png' % (dims + (old, dir)))
88 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop2.png' % (dims + (new, dir)))
90 system ('compare -depth 8 -dissimilarity-threshold 1 %(dir)s/crop1.png %(dir)s/crop2.png %(dir)s/diff.png' % locals ())
92 system ("convert -depth 8 %(dir)s/diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' %(dir)s/matte.png" % locals ())
94 system ("composite -compose atop -quality 65 %(dir)s/matte.png %(new)s %(dest)s" % locals ())
97 ################################################################
98 # interval/bbox arithmetic.
100 empty_interval = (INFTY, -INFTY)
101 empty_bbox = (empty_interval, empty_interval)
103 def interval_is_empty (i):
106 def interval_length (i):
107 return max (i[1]-i[0], 0)
109 def interval_union (i1, i2):
110 return (min (i1[0], i2[0]),
113 def interval_intersect (i1, i2):
114 return (max (i1[0], i2[0]),
117 def bbox_is_empty (b):
118 return (interval_is_empty (b[0])
119 or interval_is_empty (b[1]))
121 def bbox_union (b1, b2):
122 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
123 interval_union (b1[Y_AXIS], b2[Y_AXIS]))
125 def bbox_intersection (b1, b2):
126 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
127 interval_intersect (b1[Y_AXIS], b2[Y_AXIS]))
130 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
132 def bbox_diameter (b):
133 return max (interval_length (b[X_AXIS]),
134 interval_length (b[Y_AXIS]))
137 def difference_area (a, b):
138 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
141 def __init__ (self, exp_list):
142 (self.name, self.origin, bbox_x,
143 bbox_y, self.output_expression) = tuple (exp_list)
145 self.bbox = (bbox_x, bbox_y)
146 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
149 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
155 def axis_centroid (self, axis):
156 return apply (sum, self.bbox[axis]) / 2
158 def centroid_distance (self, other, scale):
159 return max_distance (self.centroid, other.centroid) / scale
161 def bbox_distance (self, other):
162 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
165 return (difference_area (self.bbox, other.bbox) +
166 difference_area (other.bbox, self.bbox)) / divisor
170 def expression_distance (self, other):
171 if self.output_expression == other.output_expression:
176 ################################################################
179 class SystemSignature:
180 def __init__ (self, grob_sigs):
183 val = d.setdefault (g.name, [])
187 self.set_all_bbox (grob_sigs)
189 def set_all_bbox (self, grobs):
190 self.bbox = empty_bbox
192 self.bbox = bbox_union (g.bbox, self.bbox)
194 def closest (self, grob_name, centroid):
198 grobs = self.grob_dict[grob_name]
201 d = max_distance (g.centroid, centroid)
212 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
214 ################################################################
215 ## comparison of systems.
218 def __init__ (self, system1, system2):
219 self.system1 = system1
220 self.system2 = system2
222 self.link_list_dict = {}
223 self.back_link_dict = {}
230 self.geo_distances = {}
233 self.expression_changed = []
235 self._geometric_distance = None
236 self._expression_change_count = None
237 self._orphan_count = None
239 for g in system1.grobs ():
241 ## skip empty bboxes.
242 if bbox_is_empty (g.bbox):
245 closest = system2.closest (g.name, g.centroid)
247 self.link_list_dict.setdefault (closest, [])
248 self.link_list_dict[closest].append (g)
249 self.back_link_dict[g] = closest
252 def calc_geometric_distance (self):
254 for (g1,g2) in self.back_link_dict.items ():
256 d = g1.bbox_distance (g2)
258 self.geo_distances[(g1,g2)] = d
262 self._geometric_distance = total
264 def calc_orphan_count (self):
266 for (g1, g2) in self.back_link_dict.items ():
268 self.orphans.append ((g1, None))
272 self._orphan_count = count
274 def calc_output_exp_distance (self):
276 for (g1,g2) in self.back_link_dict.items ():
278 d += g1.expression_distance (g2)
280 self._expression_change_count = d
282 def output_expression_details_string (self):
283 return ', '.join ([g1.name for g1 in self.expression_changed])
285 def geo_details_string (self):
286 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
290 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
292 def orphan_details_string (self):
293 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
295 def geometric_distance (self):
296 if self._geometric_distance == None:
297 self.calc_geometric_distance ()
298 return self._geometric_distance
300 def orphan_count (self):
301 if self._orphan_count == None:
302 self.calc_orphan_count ()
304 return self._orphan_count
306 def output_expression_change_count (self):
307 if self._expression_change_count == None:
308 self.calc_output_exp_distance ()
309 return self._expression_change_count
312 return (self.output_expression_change_count (),
313 self.orphan_count (),
314 self.geometric_distance ())
316 def scheme_float (s) :
319 return float(s.split('.')[0])
321 def read_signature_file (name):
322 print 'reading', name
324 entries = open (name).read ().split ('\n')
325 def string_to_tup (s):
326 return tuple (map (scheme_float, s.split (' ')))
328 def string_to_entry (s):
329 fields = s.split('@')
330 fields[2] = string_to_tup (fields[2])
331 fields[3] = string_to_tup (fields[3])
333 return tuple (fields)
335 entries = [string_to_entry (e) for e in entries
336 if e and not e.startswith ('#')]
338 grob_sigs = [GrobSignature (e) for e in entries]
339 sig = SystemSignature (grob_sigs)
343 ################################################################
344 # different systems of a .ly file.
346 hash_to_original_name = {}
349 def __init__ (self, f1, f2):
350 self._distance = None
351 self.file_names = (f1, f2)
353 def text_record_string (self):
354 return '%-30f %-20s\n' % (self.distance (),
356 + os.path.splitext (self.file_names[1])[1]
359 def calc_distance (self):
363 if self._distance == None:
364 self._distance = self.calc_distance ()
366 return self._distance
368 def source_file (self):
369 for ext in ('.ly', '.ly.txt'):
370 base = os.path.splitext (self.file_names[1])[0]
372 if os.path.exists (f):
378 base = os.path.basename (self.file_names[1])
379 base = os.path.splitext (base)[0]
380 base = hash_to_original_name.get (base, base)
381 base = os.path.splitext (base)[0]
384 def extension (self):
385 return os.path.splitext (self.file_names[1])[1]
387 def link_files_for_html (self, dest_dir):
388 for f in self.file_names:
389 link_file (f, os.path.join (dest_dir, f))
391 def get_distance_details (self):
394 def get_cell (self, oldnew):
397 def get_file (self, oldnew):
398 return self.file_names[oldnew]
400 def html_record_string (self, dest_dir):
401 dist = self.distance()
403 details = self.get_distance_details ()
405 details_base = os.path.splitext (self.file_names[1])[0]
406 details_base += '.details.html'
407 fn = dest_dir + '/' + details_base
408 open_write_file (fn).write (details)
410 details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
412 cell1 = self.get_cell (0)
413 cell2 = self.get_cell (1)
415 name = self.name () + self.extension ()
416 file1 = self.get_file (0)
417 file2 = self.get_file (1)
424 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
425 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
429 class FileCompareLink (FileLink):
430 def __init__ (self, f1, f2):
431 FileLink.__init__ (self, f1, f2)
432 self.contents = (self.get_content (self.file_names[0]),
433 self.get_content (self.file_names[1]))
436 def calc_distance (self):
437 ## todo: could use import MIDI to pinpoint
438 ## what & where changed.
440 if self.contents[0] == self.contents[1]:
445 def get_content (self, f):
451 class GitFileCompareLink (FileCompareLink):
452 def get_cell (self, oldnew):
453 str = self.contents[oldnew]
455 # truncate long lines
456 str = '\n'.join ([l[:80] for l in str.split ('\n')])
459 str = '<font size="-2"><pre>%s</pre></font>' % str
462 def calc_distance (self):
463 if self.contents[0] == self.contents[1]:
466 d = 1.0001 *options.threshold
471 class TextFileCompareLink (FileCompareLink):
472 def calc_distance (self):
474 diff = difflib.unified_diff (self.contents[0].strip().split ('\n'),
475 self.contents[1].strip().split ('\n'),
476 fromfiledate = self.file_names[0],
477 tofiledate = self.file_names[1]
480 self.diff_lines = [l for l in diff]
481 self.diff_lines = self.diff_lines[2:]
483 return math.sqrt (float (len ([l for l in self.diff_lines if l[0] in '-+'])))
485 def get_cell (self, oldnew):
488 str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
489 str = '<font size="-2"><pre>%s</pre></font>' % str
492 class LogFileCompareLink (TextFileCompareLink):
493 def get_content (self, f):
494 c = TextFileCompareLink.get_content (self, f)
495 c = re.sub ("\nProcessing `[^\n]+'\n", '', c)
498 class ProfileFileLink (FileCompareLink):
499 def __init__ (self, f1, f2):
500 FileCompareLink.__init__ (self, f1, f2)
501 self.results = [{}, {}]
503 def get_cell (self, oldnew):
505 for k in ('time', 'cells'):
507 str += '%-8s: %d\n' % (k, int (self.results[oldnew][k]))
509 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
512 return '<pre>%s</pre>' % str
514 def get_ratio (self, key):
515 (v1,v2) = (self.results[0].get (key, -1),
516 self.results[1].get (key, -1))
518 if v1 <= 0 or v2 <= 0:
521 return (v1 - v2) / float (v1+v2)
523 def calc_distance (self):
526 self.results[oldnew][m.group(1)] = float (m.group (2))
528 re.sub ('([a-z]+): ([-0-9.]+)\n',
529 note_info, self.contents[oldnew])
537 for k in ('time', 'cells'):
538 real_val = math.tan (self.get_ratio (k) * 0.5 * math.pi)
539 dist += math.exp (math.fabs (real_val) * factor[k]) - 1
541 dist = min (dist, 100)
545 class MidiFileLink (TextFileCompareLink):
546 def get_content (self, oldnew):
549 data = FileCompareLink.get_content (self, oldnew)
550 midi = midi.parse (data)
556 str += 'track %d' % j
561 if re.search ('LilyPond [0-9.]+', ev_str):
564 str += ' ev %s\n' % `e`
569 class SignatureFileLink (FileLink):
570 def __init__ (self, f1, f2 ):
571 FileLink.__init__ (self, f1, f2)
572 self.system_links = {}
574 def add_system_link (self, link, number):
575 self.system_links[number] = link
577 def calc_distance (self):
580 orphan_distance = 0.0
581 for l in self.system_links.values ():
582 d = max (d, l.geometric_distance ())
583 orphan_distance += l.orphan_count ()
585 return d + orphan_distance
587 def add_file_compare (self, f1, f2):
590 def note_system_index (m):
591 system_index.append (int (m.group (1)))
594 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
595 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
597 self.base_names = (os.path.normpath (base1),
598 os.path.normpath (base2))
600 s1 = read_signature_file (f1)
601 s2 = read_signature_file (f2)
603 link = SystemLink (s1, s2)
605 self.add_system_link (link, system_index[0])
608 def create_images (self, dest_dir):
610 files_created = [[], []]
611 for oldnew in (0, 1):
612 pat = self.base_names[oldnew] + '.eps'
614 for f in glob.glob (pat):
616 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
618 if options.local_data_dir:
619 data_option = ('-slilypond-datadir=%s/share/lilypond/current '
620 % os.path.dirname(infile))
622 mkdir (os.path.split (outfile)[0])
623 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
626 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
627 ' %(infile)s -c quit ') % locals ()
629 files_created[oldnew].append (outfile)
634 def link_files_for_html (self, dest_dir):
635 FileLink.link_files_for_html (self, dest_dir)
636 to_compare = [[], []]
639 if options.create_images:
640 to_compare = self.create_images (dest_dir)
642 exts += ['.png', '-page*png']
646 for f in glob.glob (self.base_names[oldnew] + ext):
647 dst = dest_dir + '/' + f
650 if f.endswith ('.png'):
651 to_compare[oldnew].append (f)
653 if options.compare_images:
654 for (old, new) in zip (to_compare[0], to_compare[1]):
655 compare_png_images (old, new, dest_dir)
658 def get_cell (self, oldnew):
659 def img_cell (ly, img, name):
663 name = '<tt>%s</tt>' % name
667 <img src="%(img)s" style="border-style: none; max-width: 500px;">
670 def multi_img_cell (ly, imgs, name):
674 name = '<tt>%s</tt>' % name
676 imgs_str = '\n'.join (['''<a href="%s">
677 <img src="%s" style="border-style: none; max-width: 500px;">
678 </a><br>''' % (img, img)
688 def cell (base, name):
689 pat = base + '-page*.png'
690 pages = glob.glob (pat)
693 return multi_img_cell (base + '.ly', sorted (pages), name)
695 return img_cell (base + '.ly', base + '.png', name)
699 str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())
700 if options.compare_images and oldnew == 1:
701 str = str.replace ('.png', '.compare.jpeg')
706 def get_distance_details (self):
707 systems = self.system_links.items ()
711 for (c, link) in systems:
712 e = '<td>%d</td>' % c
713 for d in link.distance ():
714 e += '<td>%f</td>' % d
716 e = '<tr>%s</tr>' % e
720 e = '<td>%d</td>' % c
721 for s in (link.output_expression_details_string (),
722 link.orphan_details_string (),
723 link.geo_details_string ()):
724 e += "<td>%s</td>" % s
727 e = '<tr>%s</tr>' % e
730 original = self.name ()
733 <title>comparison details for %(original)s</title>
753 ################################################################
759 def compare_signature_files (f1, f2):
760 s1 = read_signature_file (f1)
761 s2 = read_signature_file (f2)
763 return SystemLink (s1, s2).distance ()
765 def paired_files (dir1, dir2, pattern):
767 Search DIR1 and DIR2 for PATTERN.
769 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
774 for d in (dir1,dir2):
775 found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
776 found = dict ((f, 1) for f in found)
788 return (pairs, files[1].keys (), missing)
790 class ComparisonData:
792 self.result_dict = {}
797 def read_sources (self):
799 ## ugh: drop the .ly.txt
800 for (key, val) in self.file_links.items ():
802 def note_original (match, ln=val):
804 hash_to_original_name[key] = match.group (1)
807 sf = val.source_file ()
809 re.sub (r'\\sourcefilename "([^"]+)"',
810 note_original, open (sf).read ())
812 print 'no source for', val
814 def compare_trees (self, dir1, dir2):
815 self.compare_directories (dir1, dir2)
817 (root, dirs, files) = os.walk (dir1).next ()
819 d1 = os.path.join (dir1, d)
820 d2 = os.path.join (dir2, d)
822 if os.path.islink (d1) or os.path.islink (d2):
825 if os.path.isdir (d2):
826 self.compare_trees (d1, d2)
828 def compare_directories (self, dir1, dir2):
829 for ext in ['signature',
834 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
836 self.missing += [(dir1, m) for m in m1]
837 self.added += [(dir2, m) for m in m2]
840 if (options.max_count
841 and len (self.file_links) > options.max_count):
846 self.compare_files (f1, f2)
848 def compare_files (self, f1, f2):
849 if f1.endswith ('signature'):
850 self.compare_signature_files (f1, f2)
852 ext = os.path.splitext (f1)[1]
854 '.midi': MidiFileLink,
855 '.log' : LogFileCompareLink,
856 '.profile': ProfileFileLink,
857 '.gittxt': GitFileCompareLink,
860 if klasses.has_key (ext):
861 self.compare_general_files (klasses[ext], f1, f2)
863 def compare_general_files (self, klass, f1, f2):
864 name = os.path.split (f1)[1]
866 file_link = klass (f1, f2)
867 self.file_links[name] = file_link
869 def compare_signature_files (self, f1, f2):
870 name = os.path.split (f1)[1]
871 name = re.sub ('-[0-9]+.signature', '', name)
875 file_link = self.file_links[name]
877 generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
878 generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
879 file_link = SignatureFileLink (generic_f1, generic_f2)
880 self.file_links[name] = file_link
882 file_link.add_file_compare (f1, f2)
884 def write_changed (self, dest_dir, threshold):
885 (changed, below, unchanged) = self.thresholded_results (threshold)
887 str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
888 for link in changed])
889 fn = dest_dir + '/changed.txt'
891 open_write_file (fn).write (str)
893 def thresholded_results (self, threshold):
894 ## todo: support more scores.
895 results = [(link.distance(), link)
896 for link in self.file_links.values ()]
900 unchanged = [r for (d,r) in results if d == 0.0]
901 below = [r for (d,r) in results if threshold >= d > 0.0]
902 changed = [r for (d,r) in results if d > threshold]
904 return (changed, below, unchanged)
906 def write_text_result_page (self, filename, threshold):
911 print 'writing "%s"' % filename
912 out = open_write_file (filename)
914 (changed, below, unchanged) = self.thresholded_results (threshold)
918 out.write (link.text_record_string ())
921 out.write ('%d below threshold\n' % len (below))
922 out.write ('%d unchanged\n' % len (unchanged))
924 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
925 self.write_text_result_page (dest_dir + '/index.txt', threshold)
927 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
928 dir1 = dir1.replace ('//', '/')
929 dir2 = dir2.replace ('//', '/')
931 (changed, below, unchanged) = self.thresholded_results (threshold)
935 old_prefix = os.path.split (dir1)[1]
937 html += link.html_record_string (dest_dir)
940 short_dir1 = shorten_string (dir1)
941 short_dir2 = shorten_string (dir2)
943 <table rules="rows" border bordercolor="blue">
946 <th>%(short_dir1)s</th>
947 <th>%(short_dir2)s</th>
951 </html>''' % locals()
954 below_count = len (below)
957 html += ('<p>%d below threshold</p>' % below_count)
959 html += ('<p>%d unchanged</p>' % len (unchanged))
961 dest_file = dest_dir + '/index.html'
962 open_write_file (dest_file).write (html)
966 link.link_files_for_html (dest_dir)
969 def print_results (self, threshold):
970 self.write_text_result_page ('', threshold)
972 def compare_tree_pairs (tree_pairs, dest_dir, threshold):
973 data = ComparisonData ()
974 for dir1, dir2 in tree_pairs:
975 data.compare_trees (dir1, dir2)
978 data.print_results (threshold)
980 if os.path.isdir (dest_dir):
981 system ('rm -rf %s '% dest_dir)
983 data.write_changed (dest_dir, threshold)
984 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
985 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
987 ################################################################
991 if not os.path.isdir (x):
995 def link_file (x, y):
996 mkdir (os.path.split (y)[0])
1001 print 'OSError', x, y, z
1004 def open_write_file (x):
1005 d = os.path.split (x)[0]
1007 return open (x, 'w')
1013 stat = os.system (x)
1017 def test_paired_files ():
1018 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
1019 os.environ["HOME"] + "/src/lilypond-stable/scripts/build/", '*.py')
1022 def test_compare_tree_pairs ():
1023 system ('rm -rf dir1 dir2')
1024 system ('mkdir dir1 dir2')
1025 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1026 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
1027 system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1028 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1029 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1030 system ('cp 19-1.signature 19.sub-1.signature')
1031 system ('cp 19.ly 19.sub.ly')
1032 system ('cp 19.profile 19.sub.profile')
1033 system ('cp 19.log 19.sub.log')
1034 system ('cp 19.png 19.sub.png')
1035 system ('cp 19.eps 19.sub.eps')
1037 system ('cp 20multipage* dir1')
1038 system ('cp 20multipage* dir2')
1039 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
1042 system ('mkdir -p dir1/subdir/ dir2/subdir/')
1043 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
1044 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
1045 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1046 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1047 system ('echo HEAD is 1 > dir1/tree.gittxt')
1048 system ('echo HEAD is 2 > dir2/tree.gittxt')
1050 ## introduce differences
1051 system ('cp 19-1.signature dir2/20-1.signature')
1052 system ('cp 19.profile dir2/20.profile')
1053 system ('cp 19.png dir2/20.png')
1054 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1055 system ('cp 20-1.signature dir2/subdir/19.sub-1.signature')
1056 system ('cp 20.png dir2/subdir/19.sub.png')
1057 system ("sed 's/: /: 1/g' 20.profile > dir2/subdir/19.sub.profile")
1060 system ('cp 19-1.signature dir2/20grob-1.signature')
1061 system ('cp 19-1.signature dir2/20grob-2.signature')
1062 system ('cp 19multipage.midi dir1/midi-differ.midi')
1063 system ('cp 20multipage.midi dir2/midi-differ.midi')
1064 system ('cp 19multipage.log dir1/log-differ.log')
1065 system ('cp 19multipage.log dir2/log-differ.log && echo different >> dir2/log-differ.log && echo different >> dir2/log-differ.log')
1067 compare_tree_pairs (['dir1', 'dir2'], 'compare-dir1dir2', options.threshold)
1070 def test_basic_compare ():
1074 #(define default-toplevel-book-handler
1075 print-book-with-defaults-as-systems )
1077 #(ly:set-option (quote no-point-and-click))
1079 \sourcefilename "my-source.ly"
1082 \header { tagline = ##f }
1085 \new Staff \relative c {
1086 c4^"%(userstring)s" %(extragrob)s
1088 \new Staff \relative c {
1089 c4^"%(userstring)s" %(extragrob)s
1097 dicts = [{ 'papermod' : '',
1100 'userstring': 'test' },
1101 { 'papermod' : '#(set-global-staff-size 19.5)',
1104 'userstring': 'test' },
1108 'userstring': 'blabla' },
1111 'extragrob': 'r2. \\break c1',
1112 'userstring': 'test' },
1116 open (d['name'] + '.ly','w').write (ly_template % d)
1118 names = [d['name'] for d in dicts]
1120 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -dbackend=eps ' + ' '.join (names))
1123 multipage_str = r'''
1124 #(set-default-paper-size "a6")
1126 \relative c' { c1 \pageBreak c1 }
1132 open ('20multipage.ly', 'w').write (multipage_str.replace ('c1', 'd1'))
1133 open ('19multipage.ly', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1134 system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1136 test_compare_signatures (names)
1138 def test_compare_signatures (names, timing=False):
1148 for t in range (0, times):
1149 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1153 print 'elapsed', (time.clock() - t0)/count
1159 for (n1, s1) in sigs.items():
1160 for (n2, s2) in sigs.items():
1161 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1165 print 'elapsed', (time.clock() - t0)/count
1167 results = combinations.items ()
1170 print '%-20s' % k, v
1172 assert combinations['20-20'] == (0.0,0.0,0.0)
1173 assert combinations['20-20expr'][0] > 0.0
1174 assert combinations['20-19'][2] < 10.0
1175 assert combinations['20-19'][2] > 0.0
1179 dir = 'test-output-distance'
1181 do_clean = not os.path.exists (dir)
1183 print 'test results in ', dir
1185 system ('rm -rf ' + dir)
1186 system ('mkdir ' + dir)
1190 test_basic_compare ()
1192 test_compare_tree_pairs ()
1194 ################################################################
1198 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1199 p.usage = 'output-distance.py [options] tree1 tree2 [tree3 tree4]...'
1201 p.add_option ('', '--test-self',
1203 action="store_true",
1204 help='run test method')
1206 p.add_option ('--max-count',
1212 help='only analyze COUNT signature pairs')
1214 p.add_option ('', '--threshold',
1219 help='threshold for geometric distance')
1221 p.add_option ('--no-compare-images',
1222 dest="compare_images",
1224 action="store_false",
1225 help="Don't run graphical comparisons")
1227 p.add_option ('--create-images',
1228 dest="create_images",
1230 action="store_true",
1231 help="Create PNGs from EPSes")
1234 p.add_option ('--local-datadir',
1235 dest="local_data_dir",
1237 action="store_true",
1238 help='whether to use the share/lilypond/ directory in the test directory')
1240 p.add_option ('-o', '--output-dir',
1245 help='where to put the test results [tree2/compare-tree1tree2]')
1248 (options, args) = p.parse_args ()
1250 if options.run_test:
1258 out = options.output_dir
1260 out = args[0].replace ('/', '')
1261 out = os.path.join (args[1], 'compare-' + shorten_string (out))
1263 compare_tree_pairs (zip (args[0::2], args[1::2]), out, options.threshold)
1265 if __name__ == '__main__':