8 ## so we can call directly as scripts/build/output-distance.py
9 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
10 sys.path.insert (0, me_path + '/../python/')
11 sys.path.insert (0, me_path + '/../python/out/')
18 OUTPUT_EXPRESSION_PENALTY = 1
19 ORPHAN_GROB_PENALTY = 1
22 ################################################################
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)
69 def compare_png_images (old, new, dest_dir):
71 m = re.search ('([0-9]+) x ([0-9]+)', read_pipe ('file %s' % f))
73 return tuple (map (int, m.groups ()))
75 dest = os.path.join (dest_dir, new.replace ('.png', '.compare.jpeg'))
77 dims1 = png_dims (old)
78 dims2 = png_dims (new)
79 except AttributeError:
81 system ('touch %(dest)s' % locals ())
84 dims = (min (dims1[0], dims2[0]),
85 min (dims1[1], dims2[1]))
88 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop1.png' % (dims + (old, dir)))
89 system ('convert -depth 8 -crop %dx%d+0+0 %s %s/crop2.png' % (dims + (new, dir)))
91 system ('compare -depth 8 -dissimilarity-threshold 1 %(dir)s/crop1.png %(dir)s/crop2.png %(dir)s/diff.png' % locals ())
93 system ("convert -depth 8 %(dir)s/diff.png -blur 0x3 -negate -channel alpha,blue -type TrueColorMatte -fx 'intensity' %(dir)s/matte.png" % locals ())
95 system ("composite -compose atop -quality 65 %(dir)s/matte.png %(new)s %(dest)s" % locals ())
98 ################################################################
99 # interval/bbox arithmetic.
101 empty_interval = (INFTY, -INFTY)
102 empty_bbox = (empty_interval, empty_interval)
104 def interval_is_empty (i):
107 def interval_length (i):
108 return max (i[1]-i[0], 0)
110 def interval_union (i1, i2):
111 return (min (i1[0], i2[0]),
114 def interval_intersect (i1, i2):
115 return (max (i1[0], i2[0]),
118 def bbox_is_empty (b):
119 return (interval_is_empty (b[0])
120 or interval_is_empty (b[1]))
122 def bbox_union (b1, b2):
123 return (interval_union (b1[X_AXIS], b2[X_AXIS]),
124 interval_union (b1[Y_AXIS], b2[Y_AXIS]))
126 def bbox_intersection (b1, b2):
127 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
128 interval_intersect (b1[Y_AXIS], b2[Y_AXIS]))
131 return interval_length (b[X_AXIS]) * interval_length (b[Y_AXIS])
133 def bbox_diameter (b):
134 return max (interval_length (b[X_AXIS]),
135 interval_length (b[Y_AXIS]))
138 def difference_area (a, b):
139 return bbox_area (a) - bbox_area (bbox_intersection (a,b))
142 def __init__ (self, exp_list):
143 (self.name, self.origin, bbox_x,
144 bbox_y, self.output_expression) = tuple (exp_list)
146 self.bbox = (bbox_x, bbox_y)
147 self.centroid = (bbox_x[0] + bbox_x[1], bbox_y[0] + bbox_y[1])
150 return '%s: (%.2f,%.2f), (%.2f,%.2f)\n' % (self.name,
156 def axis_centroid (self, axis):
157 return apply (sum, self.bbox[axis]) / 2
159 def centroid_distance (self, other, scale):
160 return max_distance (self.centroid, other.centroid) / scale
162 def bbox_distance (self, other):
163 divisor = bbox_area (self.bbox) + bbox_area (other.bbox)
166 return (difference_area (self.bbox, other.bbox) +
167 difference_area (other.bbox, self.bbox)) / divisor
171 def expression_distance (self, other):
172 if self.output_expression == other.output_expression:
177 ################################################################
180 class SystemSignature:
181 def __init__ (self, grob_sigs):
184 val = d.setdefault (g.name, [])
188 self.set_all_bbox (grob_sigs)
190 def set_all_bbox (self, grobs):
191 self.bbox = empty_bbox
193 self.bbox = bbox_union (g.bbox, self.bbox)
195 def closest (self, grob_name, centroid):
199 grobs = self.grob_dict[grob_name]
202 d = max_distance (g.centroid, centroid)
213 return reduce (lambda x,y: x+y, self.grob_dict.values(), [])
215 ################################################################
216 ## comparison of systems.
219 def __init__ (self, system1, system2):
220 self.system1 = system1
221 self.system2 = system2
223 self.link_list_dict = {}
224 self.back_link_dict = {}
231 self.geo_distances = {}
234 self.expression_changed = []
236 self._geometric_distance = None
237 self._expression_change_count = None
238 self._orphan_count = None
240 for g in system1.grobs ():
242 ## skip empty bboxes.
243 if bbox_is_empty (g.bbox):
246 closest = system2.closest (g.name, g.centroid)
248 self.link_list_dict.setdefault (closest, [])
249 self.link_list_dict[closest].append (g)
250 self.back_link_dict[g] = closest
253 def calc_geometric_distance (self):
255 for (g1,g2) in self.back_link_dict.items ():
257 d = g1.bbox_distance (g2)
259 self.geo_distances[(g1,g2)] = d
263 self._geometric_distance = total
265 def calc_orphan_count (self):
267 for (g1, g2) in self.back_link_dict.items ():
269 self.orphans.append ((g1, None))
273 self._orphan_count = count
275 def calc_output_exp_distance (self):
277 for (g1,g2) in self.back_link_dict.items ():
279 d += g1.expression_distance (g2)
281 self._expression_change_count = d
283 def output_expression_details_string (self):
284 return ', '.join ([g1.name for g1 in self.expression_changed])
286 def geo_details_string (self):
287 results = [(d, g1,g2) for ((g1, g2), d) in self.geo_distances.items()]
291 return ', '.join (['%s: %f' % (g1.name, d) for (d, g1, g2) in results])
293 def orphan_details_string (self):
294 return ', '.join (['%s-None' % g1.name for (g1,g2) in self.orphans if g2==None])
296 def geometric_distance (self):
297 if self._geometric_distance == None:
298 self.calc_geometric_distance ()
299 return self._geometric_distance
301 def orphan_count (self):
302 if self._orphan_count == None:
303 self.calc_orphan_count ()
305 return self._orphan_count
307 def output_expression_change_count (self):
308 if self._expression_change_count == None:
309 self.calc_output_exp_distance ()
310 return self._expression_change_count
313 return (self.output_expression_change_count (),
314 self.orphan_count (),
315 self.geometric_distance ())
317 def scheme_float (s) :
320 return float(s.split('.')[0])
322 def read_signature_file (name):
323 print 'reading', name
325 entries = open (name).read ().split ('\n')
326 def string_to_tup (s):
327 return tuple (map (scheme_float, s.split (' ')))
329 def string_to_entry (s):
330 fields = s.split('@')
331 fields[2] = string_to_tup (fields[2])
332 fields[3] = string_to_tup (fields[3])
334 return tuple (fields)
336 entries = [string_to_entry (e) for e in entries
337 if e and not e.startswith ('#')]
339 grob_sigs = [GrobSignature (e) for e in entries]
340 sig = SystemSignature (grob_sigs)
344 ################################################################
345 # different systems of a .ly file.
347 hash_to_original_name = {}
350 def __init__ (self, f1, f2):
351 self._distance = None
352 self.file_names = (f1, f2)
354 def text_record_string (self):
355 return '%-30f %-20s\n' % (self.distance (),
357 + os.path.splitext (self.file_names[1])[1]
360 def calc_distance (self):
364 if self._distance == None:
365 self._distance = self.calc_distance ()
367 return self._distance
369 def source_file (self):
370 for ext in ('.ly', '.ly.txt'):
371 base = os.path.splitext (self.file_names[1])[0]
373 if os.path.exists (f):
379 base = os.path.basename (self.file_names[1])
380 base = os.path.splitext (base)[0]
381 base = hash_to_original_name.get (base, base)
382 base = os.path.splitext (base)[0]
385 def extension (self):
386 return os.path.splitext (self.file_names[1])[1]
388 def link_files_for_html (self, dest_dir):
389 for f in self.file_names:
390 link_file (f, os.path.join (dest_dir, f))
392 def get_distance_details (self):
395 def get_cell (self, oldnew):
398 def get_file (self, oldnew):
399 return self.file_names[oldnew]
401 def html_record_string (self, dest_dir):
402 dist = self.distance()
404 details = self.get_distance_details ()
406 details_base = os.path.splitext (self.file_names[1])[0]
407 details_base += '.details.html'
408 fn = dest_dir + '/' + details_base
409 open_write_file (fn).write (details)
411 details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
413 cell1 = self.get_cell (0)
414 cell2 = self.get_cell (1)
416 name = self.name () + self.extension ()
417 file1 = self.get_file (0)
418 file2 = self.get_file (1)
425 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
426 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
430 class FileCompareLink (FileLink):
431 def __init__ (self, f1, f2):
432 FileLink.__init__ (self, f1, f2)
433 self.contents = (self.get_content (self.file_names[0]),
434 self.get_content (self.file_names[1]))
437 def calc_distance (self):
438 ## todo: could use import MIDI to pinpoint
439 ## what & where changed.
441 if self.contents[0] == self.contents[1]:
446 def get_content (self, f):
452 class GitFileCompareLink (FileCompareLink):
453 def get_cell (self, oldnew):
454 str = self.contents[oldnew]
456 # truncate long lines
457 str = '\n'.join ([l[:80] for l in str.split ('\n')])
460 str = '<font size="-2"><pre>%s</pre></font>' % str
463 def calc_distance (self):
464 if self.contents[0] == self.contents[1]:
467 d = 1.0001 *options.threshold
472 snippet_fn_re = re.compile (r"`\./([0-9a-f]{2}/lily-[0-9a-f]{8}).eps'");
473 class TextFileCompareLink (FileCompareLink):
474 def calc_distance (self):
476 # Extract the old and the new hashed snippet names from the log file
477 # and replace the old by the new, so file name changes don't show
478 # up as log differences...
479 cont0 = self.contents[0].strip();
480 cont1 = self.contents[1].strip();
481 m0 = re.search (snippet_fn_re, cont0);
482 m1 = re.search (snippet_fn_re, cont1);
483 if (m0 and m1 and (m0.group(1) != m1.group(1))):
484 cont0 = cont0.replace (m0.group(1), m1.group(1));
486 diff = difflib.unified_diff (cont0.split ('\n'),
488 fromfiledate = self.file_names[0],
489 tofiledate = self.file_names[1]
492 self.diff_lines = [l for l in diff]
493 self.diff_lines = self.diff_lines[2:]
495 return math.sqrt (float (len ([l for l in self.diff_lines if l[0] in '-+'])))
497 def get_cell (self, oldnew):
500 str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
501 str = '<font size="-2"><pre>%s</pre></font>' % str
504 class LogFileCompareLink (TextFileCompareLink):
505 def get_content (self, f):
506 c = TextFileCompareLink.get_content (self, f)
507 c = re.sub ("\nProcessing `[^\n]+'\n", '', c)
510 class ProfileFileLink (FileCompareLink):
511 def __init__ (self, f1, f2):
512 FileCompareLink.__init__ (self, f1, f2)
513 self.results = [{}, {}]
515 def get_cell (self, oldnew):
517 for k in ('time', 'cells'):
519 str += '%-8s: %d\n' % (k, int (self.results[oldnew][k]))
521 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
524 return '<pre>%s</pre>' % str
526 def get_ratio (self, key):
527 (v1,v2) = (self.results[0].get (key, -1),
528 self.results[1].get (key, -1))
530 if v1 <= 0 or v2 <= 0:
533 return (v1 - v2) / float (v1+v2)
535 def calc_distance (self):
538 self.results[oldnew][m.group(1)] = float (m.group (2))
540 re.sub ('([a-z]+): ([-0-9.]+)\n',
541 note_info, self.contents[oldnew])
549 for k in ('time', 'cells'):
550 real_val = math.tan (self.get_ratio (k) * 0.5 * math.pi)
551 dist += math.exp (math.fabs (real_val) * factor[k]) - 1
553 dist = min (dist, 100)
557 class MidiFileLink (TextFileCompareLink):
558 def get_content (self, oldnew):
561 data = FileCompareLink.get_content (self, oldnew)
562 midi = midi.parse (data)
568 str += 'track %d' % j
573 if re.search ('LilyPond [0-9.]+', ev_str):
576 str += ' ev %s\n' % `e`
581 class SignatureFileLink (FileLink):
582 def __init__ (self, f1, f2 ):
583 FileLink.__init__ (self, f1, f2)
584 self.system_links = {}
586 def add_system_link (self, link, number):
587 self.system_links[number] = link
589 def calc_distance (self):
592 orphan_distance = 0.0
593 for l in self.system_links.values ():
594 d = max (d, l.geometric_distance ())
595 orphan_distance += l.orphan_count ()
597 return d + orphan_distance
599 def add_file_compare (self, f1, f2):
602 def note_system_index (m):
603 system_index.append (int (m.group (1)))
606 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
607 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
609 self.base_names = (os.path.normpath (base1),
610 os.path.normpath (base2))
612 s1 = read_signature_file (f1)
613 s2 = read_signature_file (f2)
615 link = SystemLink (s1, s2)
617 self.add_system_link (link, system_index[0])
620 def create_images (self, dest_dir):
622 files_created = [[], []]
623 for oldnew in (0, 1):
624 pat = self.base_names[oldnew] + '.eps'
626 for f in glob.glob (pat):
628 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
630 if options.local_data_dir:
631 data_option = ('-slilypond-datadir=%s/share/lilypond/current '
632 % os.path.dirname(infile))
634 mkdir (os.path.split (outfile)[0])
635 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
638 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
639 ' %(infile)s -c quit ') % locals ()
641 files_created[oldnew].append (outfile)
646 def link_files_for_html (self, dest_dir):
647 FileLink.link_files_for_html (self, dest_dir)
648 to_compare = [[], []]
651 if options.create_images:
652 to_compare = self.create_images (dest_dir)
654 exts += ['.png', '-page*png']
658 for f in glob.glob (self.base_names[oldnew] + ext):
659 dst = dest_dir + '/' + f
662 if f.endswith ('.png'):
663 to_compare[oldnew].append (f)
665 if options.compare_images:
666 for (old, new) in zip (to_compare[0], to_compare[1]):
667 compare_png_images (old, new, dest_dir)
670 def get_cell (self, oldnew):
671 def img_cell (ly, img, name):
675 name = '<tt>%s</tt>' % name
679 <img src="%(img)s" style="border-style: none; max-width: 500px;">
682 def multi_img_cell (ly, imgs, name):
686 name = '<tt>%s</tt>' % name
688 imgs_str = '\n'.join (['''<a href="%s">
689 <img src="%s" style="border-style: none; max-width: 500px;">
690 </a><br>''' % (img, img)
700 def cell (base, name):
701 pat = base + '-page*.png'
702 pages = glob.glob (pat)
705 return multi_img_cell (base + '.ly', sorted (pages), name)
707 return img_cell (base + '.ly', base + '.png', name)
711 str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())
712 if options.compare_images and oldnew == 1:
713 str = str.replace ('.png', '.compare.jpeg')
718 def get_distance_details (self):
719 systems = self.system_links.items ()
723 for (c, link) in systems:
724 e = '<td>%d</td>' % c
725 for d in link.distance ():
726 e += '<td>%f</td>' % d
728 e = '<tr>%s</tr>' % e
732 e = '<td>%d</td>' % c
733 for s in (link.output_expression_details_string (),
734 link.orphan_details_string (),
735 link.geo_details_string ()):
736 e += "<td>%s</td>" % s
739 e = '<tr>%s</tr>' % e
742 original = self.name ()
745 <title>comparison details for %(original)s</title>
765 ################################################################
770 def compare_signature_files (f1, f2):
771 s1 = read_signature_file (f1)
772 s2 = read_signature_file (f2)
774 return SystemLink (s1, s2).distance ()
776 def paired_files (dir1, dir2, pattern):
778 Search DIR1 and DIR2 for PATTERN.
780 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
785 for d in (dir1,dir2):
786 found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
787 found = dict ((f, 1) for f in found)
799 return (pairs, files[1].keys (), missing)
801 class ComparisonData:
803 self.result_dict = {}
808 def read_sources (self):
810 ## ugh: drop the .ly.txt
811 for (key, val) in self.file_links.items ():
813 def note_original (match, ln=val):
815 hash_to_original_name[key] = match.group (1)
818 sf = val.source_file ()
820 re.sub (r'\\sourcefilename "([^"]+)"',
821 note_original, open (sf).read ())
823 print 'no source for', val
825 def compare_trees (self, dir1, dir2):
826 self.compare_directories (dir1, dir2)
828 (root, dirs, files) = os.walk (dir1).next ()
830 d1 = os.path.join (dir1, d)
831 d2 = os.path.join (dir2, d)
833 if os.path.islink (d1) or os.path.islink (d2):
836 if os.path.isdir (d2):
837 self.compare_trees (d1, d2)
839 def compare_directories (self, dir1, dir2):
840 for ext in ['signature',
845 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
847 self.missing += [(dir1, m) for m in m1]
848 self.added += [(dir2, m) for m in m2]
851 if (options.max_count
852 and len (self.file_links) > options.max_count):
857 self.compare_files (f1, f2)
859 def compare_files (self, f1, f2):
860 if f1.endswith ('signature'):
861 self.compare_signature_files (f1, f2)
863 ext = os.path.splitext (f1)[1]
865 '.midi': MidiFileLink,
866 '.log' : LogFileCompareLink,
867 '.profile': ProfileFileLink,
868 '.gittxt': GitFileCompareLink,
871 if klasses.has_key (ext):
872 self.compare_general_files (klasses[ext], f1, f2)
874 def compare_general_files (self, klass, f1, f2):
875 name = os.path.split (f1)[1]
877 file_link = klass (f1, f2)
878 self.file_links[name] = file_link
880 def compare_signature_files (self, f1, f2):
881 name = os.path.split (f1)[1]
882 name = re.sub ('-[0-9]+.signature', '', name)
886 file_link = self.file_links[name]
888 generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
889 generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
890 file_link = SignatureFileLink (generic_f1, generic_f2)
891 self.file_links[name] = file_link
893 file_link.add_file_compare (f1, f2)
895 def write_changed (self, dest_dir, threshold):
896 (changed, below, unchanged) = self.thresholded_results (threshold)
898 str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
899 for link in changed])
900 fn = dest_dir + '/changed.txt'
902 open_write_file (fn).write (str)
904 def thresholded_results (self, threshold):
905 ## todo: support more scores.
906 results = [(link.distance(), link)
907 for link in self.file_links.values ()]
911 unchanged = [r for (d,r) in results if d == 0.0]
912 below = [r for (d,r) in results if threshold >= d > 0.0]
913 changed = [r for (d,r) in results if d > threshold]
915 return (changed, below, unchanged)
917 def write_text_result_page (self, filename, threshold):
922 print 'writing "%s"' % filename
923 out = open_write_file (filename)
925 (changed, below, unchanged) = self.thresholded_results (threshold)
929 out.write (link.text_record_string ())
932 out.write ('%d below threshold\n' % len (below))
933 out.write ('%d unchanged\n' % len (unchanged))
935 def create_text_result_page (self, dir1, dir2, dest_dir, threshold):
936 self.write_text_result_page (dest_dir + '/index.txt', threshold)
938 def create_html_result_page (self, dir1, dir2, dest_dir, threshold):
939 dir1 = dir1.replace ('//', '/')
940 dir2 = dir2.replace ('//', '/')
942 (changed, below, unchanged) = self.thresholded_results (threshold)
946 old_prefix = os.path.split (dir1)[1]
948 html += link.html_record_string (dest_dir)
951 short_dir1 = shorten_string (dir1)
952 short_dir2 = shorten_string (dir2)
954 <table rules="rows" border bordercolor="blue">
957 <th>%(short_dir1)s</th>
958 <th>%(short_dir2)s</th>
962 </html>''' % locals()
965 below_count = len (below)
968 html += ('<p>%d below threshold</p>' % below_count)
970 html += ('<p>%d unchanged</p>' % len (unchanged))
972 dest_file = dest_dir + '/index.html'
973 open_write_file (dest_file).write (html)
977 link.link_files_for_html (dest_dir)
980 def print_results (self, threshold):
981 self.write_text_result_page ('', threshold)
983 def compare_tree_pairs (tree_pairs, dest_dir, threshold):
984 data = ComparisonData ()
985 for dir1, dir2 in tree_pairs:
986 data.compare_trees (dir1, dir2)
989 data.print_results (threshold)
991 if os.path.isdir (dest_dir):
992 system ('rm -rf %s '% dest_dir)
994 data.write_changed (dest_dir, threshold)
995 data.create_html_result_page (dir1, dir2, dest_dir, threshold)
996 data.create_text_result_page (dir1, dir2, dest_dir, threshold)
998 ################################################################
1002 if not os.path.isdir (x):
1006 def link_file (x, y):
1007 mkdir (os.path.split (y)[0])
1012 print 'OSError', x, y, z
1015 def open_write_file (x):
1016 d = os.path.split (x)[0]
1018 return open (x, 'w')
1024 stat = os.system (x)
1028 def test_paired_files ():
1029 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
1030 os.environ["HOME"] + "/src/lilypond-stable/scripts/build/", '*.py')
1033 def test_compare_tree_pairs ():
1034 system ('rm -rf dir1 dir2')
1035 system ('mkdir dir1 dir2')
1036 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1037 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
1038 system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1039 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1040 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1041 system ('cp 19-1.signature 19.sub-1.signature')
1042 system ('cp 19.ly 19.sub.ly')
1043 system ('cp 19.profile 19.sub.profile')
1044 system ('cp 19.log 19.sub.log')
1045 system ('cp 19.png 19.sub.png')
1046 system ('cp 19.eps 19.sub.eps')
1048 system ('cp 20multipage* dir1')
1049 system ('cp 20multipage* dir2')
1050 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
1053 system ('mkdir -p dir1/subdir/ dir2/subdir/')
1054 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
1055 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
1056 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1057 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1058 system ('echo HEAD is 1 > dir1/tree.gittxt')
1059 system ('echo HEAD is 2 > dir2/tree.gittxt')
1061 ## introduce differences
1062 system ('cp 19-1.signature dir2/20-1.signature')
1063 system ('cp 19.profile dir2/20.profile')
1064 system ('cp 19.png dir2/20.png')
1065 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1066 system ('cp 20-1.signature dir2/subdir/19.sub-1.signature')
1067 system ('cp 20.png dir2/subdir/19.sub.png')
1068 system ("sed 's/: /: 1/g' 20.profile > dir2/subdir/19.sub.profile")
1071 system ('cp 19-1.signature dir2/20grob-1.signature')
1072 system ('cp 19-1.signature dir2/20grob-2.signature')
1073 system ('cp 19multipage.midi dir1/midi-differ.midi')
1074 system ('cp 20multipage.midi dir2/midi-differ.midi')
1075 system ('cp 19multipage.log dir1/log-differ.log')
1076 system ('cp 19multipage.log dir2/log-differ.log && echo different >> dir2/log-differ.log && echo different >> dir2/log-differ.log')
1078 compare_tree_pairs (['dir1', 'dir2'], 'compare-dir1dir2', options.threshold)
1081 def test_basic_compare ():
1085 #(define default-toplevel-book-handler
1086 print-book-with-defaults-as-systems )
1088 #(ly:set-option (quote no-point-and-click))
1090 \sourcefilename "my-source.ly"
1093 \header { tagline = ##f }
1096 \new Staff \relative c {
1097 c4^"%(userstring)s" %(extragrob)s
1099 \new Staff \relative c {
1100 c4^"%(userstring)s" %(extragrob)s
1108 dicts = [{ 'papermod' : '',
1111 'userstring': 'test' },
1112 { 'papermod' : '#(set-global-staff-size 19.5)',
1115 'userstring': 'test' },
1119 'userstring': 'blabla' },
1122 'extragrob': 'r2. \\break c1',
1123 'userstring': 'test' },
1127 open (d['name'] + '.ly','w').write (ly_template % d)
1129 names = [d['name'] for d in dicts]
1131 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -dbackend=eps ' + ' '.join (names))
1134 multipage_str = r'''
1135 #(set-default-paper-size "a6")
1137 \relative c' { c1 \pageBreak c1 }
1143 open ('20multipage.ly', 'w').write (multipage_str.replace ('c1', 'd1'))
1144 open ('19multipage.ly', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1145 system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1147 test_compare_signatures (names)
1149 def test_compare_signatures (names, timing=False):
1159 for t in range (0, times):
1160 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1164 print 'elapsed', (time.clock() - t0)/count
1170 for (n1, s1) in sigs.items():
1171 for (n2, s2) in sigs.items():
1172 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1176 print 'elapsed', (time.clock() - t0)/count
1178 results = combinations.items ()
1181 print '%-20s' % k, v
1183 assert combinations['20-20'] == (0.0,0.0,0.0)
1184 assert combinations['20-20expr'][0] > 0.0
1185 assert combinations['20-19'][2] < 10.0
1186 assert combinations['20-19'][2] > 0.0
1190 dir = 'test-output-distance'
1192 do_clean = not os.path.exists (dir)
1194 print 'test results in ', dir
1196 system ('rm -rf ' + dir)
1197 system ('mkdir ' + dir)
1201 test_basic_compare ()
1203 test_compare_tree_pairs ()
1205 ################################################################
1209 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1210 p.usage = 'output-distance.py [options] tree1 tree2 [tree3 tree4]...'
1212 p.add_option ('', '--test-self',
1214 action="store_true",
1215 help='run test method')
1217 p.add_option ('--max-count',
1223 help='only analyze COUNT signature pairs')
1225 p.add_option ('', '--threshold',
1230 help='threshold for geometric distance')
1232 p.add_option ('--no-compare-images',
1233 dest="compare_images",
1235 action="store_false",
1236 help="Don't run graphical comparisons")
1238 p.add_option ('--create-images',
1239 dest="create_images",
1241 action="store_true",
1242 help="Create PNGs from EPSes")
1245 p.add_option ('--local-datadir',
1246 dest="local_data_dir",
1248 action="store_true",
1249 help='whether to use the share/lilypond/ directory in the test directory')
1251 p.add_option ('-o', '--output-dir',
1256 help='where to put the test results [tree2/compare-tree1tree2]')
1259 (options, args) = p.parse_args ()
1261 if options.run_test:
1269 out = options.output_dir
1271 out = args[0].replace ('/', '')
1272 out = os.path.join (args[1], 'compare-' + shorten_string (out))
1274 compare_tree_pairs (zip (args[0::2], args[1::2]), out, options.threshold)
1276 if __name__ == '__main__':