10 ## so we can call directly as scripts/build/output-distance.py
11 me_path = os.path.abspath (os.path.split (sys.argv[0])[0])
12 sys.path.insert (0, me_path + '/../python/')
13 sys.path.insert (0, me_path + '/../python/out/')
20 OUTPUT_EXPRESSION_PENALTY = 1
21 ORPHAN_GROB_PENALTY = 1
24 ################################################################
30 self.dir = tempfile.mkdtemp ()
31 print 'dir is', self.dir
33 print 'rm -rf %s' % self.dir
34 os.system ('rm -rf %s' % self.dir)
42 temp_dir = TempDirectory ()
47 return os.popen (c).read ()
53 raise Exception ("failed")
56 def shorten_string (s, threshold = 15):
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 system1 ('compare -depth 8 -dissimilarity-threshold 1 %(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 -compose atop -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 (b1[Y_AXIS], b2[Y_AXIS]))
127 def bbox_intersection (b1, b2):
128 return (interval_intersect (b1[X_AXIS], b2[X_AXIS]),
129 interval_intersect (b1[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 scheme_float (s) :
321 return float(s.split('.')[0])
323 def read_signature_file (name):
324 print 'reading', name
326 entries = open (name).read ().split ('\n')
327 def string_to_tup (s):
328 return tuple (map (scheme_float, s.split (' ')))
330 def string_to_entry (s):
331 fields = s.split('@')
332 fields[2] = string_to_tup (fields[2])
333 fields[3] = string_to_tup (fields[3])
335 return tuple (fields)
337 entries = [string_to_entry (e) for e in entries
338 if e and not e.startswith ('#')]
340 grob_sigs = [GrobSignature (e) for e in entries]
341 sig = SystemSignature (grob_sigs)
345 ################################################################
346 # different systems of a .ly file.
348 hash_to_original_name = {}
351 def __init__ (self, f1, f2):
352 self._distance = None
353 self.file_names = (f1, f2)
355 def text_record_string (self):
356 return '%-30f %-20s\n' % (self.distance (),
358 + os.path.splitext (self.file_names[1])[1]
361 def calc_distance (self):
365 if self._distance == None:
366 self._distance = self.calc_distance ()
368 return self._distance
370 def source_file (self):
371 for ext in ('.ly', '.ly.txt'):
372 base = os.path.splitext (self.file_names[1])[0]
374 if os.path.exists (f):
379 def directories (self):
380 return map (os.path.dirname, self.file_names)
383 base = os.path.basename (self.file_names[1])
384 base = os.path.splitext (base)[0]
385 base = hash_to_original_name.get (base, base)
386 base = os.path.splitext (base)[0]
387 return os.path.join (self.prefix (), base)
390 return os.path.dirname (os.path.commonprefix (self.file_names))
392 def extension (self):
393 return os.path.splitext (self.file_names[1])[1]
395 def link_files_for_html (self, dest_dir):
396 for f in self.file_names:
397 link_file (f, os.path.join (dest_dir, f))
399 def get_distance_details (self):
402 def get_cell (self, oldnew):
405 def get_file (self, oldnew):
406 return self.file_names[oldnew]
408 def html_record_string (self, dest_dir):
409 dist = self.distance()
411 details = self.get_distance_details ()
413 details_base = os.path.splitext (self.file_names[1])[0]
414 details_base += '.details.html'
415 fn = dest_dir + '/' + details_base
416 open_write_file (fn).write (details)
418 details = '<br>(<a href="%(details_base)s">details</a>)' % locals ()
420 cell1 = self.get_cell (0)
421 cell2 = self.get_cell (1)
423 name = self.name () + self.extension ()
424 file1 = self.get_file (0)
425 file2 = self.get_file (1)
432 <td>%(cell1)s<br><font size=-2><a href="%(file1)s"><tt>%(name)s</tt></font></td>
433 <td>%(cell2)s<br><font size=-2><a href="%(file2)s"><tt>%(name)s</tt></font></td>
437 class FileCompareLink (FileLink):
438 def __init__ (self, f1, f2):
439 FileLink.__init__ (self, f1, f2)
440 self.contents = (self.get_content (self.file_names[0]),
441 self.get_content (self.file_names[1]))
444 def calc_distance (self):
445 ## todo: could use import MIDI to pinpoint
446 ## what & where changed.
448 if self.contents[0] == self.contents[1]:
453 def get_content (self, f):
459 class GitFileCompareLink (FileCompareLink):
460 def get_cell (self, oldnew):
461 str = self.contents[oldnew]
463 # truncate long lines
464 str = '\n'.join ([l[:80] for l in str.split ('\n')])
467 str = '<font size="-2"><pre>%s</pre></font>' % cgi.escape (str)
470 def calc_distance (self):
471 if self.contents[0] == self.contents[1]:
474 d = 1.0001 *options.threshold
479 snippet_fn_re = re.compile (r"`\./([0-9a-f]{2}/lily-[0-9a-f]{8}).eps'");
480 class TextFileCompareLink (FileCompareLink):
481 def calc_distance (self):
483 # Extract the old and the new hashed snippet names from the log file
484 # and replace the old by the new, so file name changes don't show
485 # up as log differences...
486 cont0 = self.contents[0].strip();
487 cont1 = self.contents[1].strip();
488 m0 = re.search (snippet_fn_re, cont0);
489 m1 = re.search (snippet_fn_re, cont1);
490 if (m0 and m1 and (m0.group(1) != m1.group(1))):
491 cont0 = cont0.replace (m0.group(1), m1.group(1));
493 diff = difflib.unified_diff (cont0.split ('\n'),
495 fromfiledate = self.file_names[0],
496 tofiledate = self.file_names[1]
499 self.diff_lines = [l for l in diff]
500 self.diff_lines = self.diff_lines[2:]
502 return math.sqrt (float (len ([l for l in self.diff_lines if l[0] in '-+'])))
504 def get_cell (self, oldnew):
507 str = '\n'.join ([d.replace ('\n','') for d in self.diff_lines])
508 str = '<font size="-2"><pre>%s</pre></font>' % cgi.escape (str)
511 class LogFileCompareLink (TextFileCompareLink):
512 def get_content (self, f):
513 c = TextFileCompareLink.get_content (self, f)
514 c = re.sub ("\nProcessing `[^\n]+'\n", '', c)
517 class ProfileFileLink (FileCompareLink):
518 def __init__ (self, f1, f2):
519 FileCompareLink.__init__ (self, f1, f2)
520 self.results = [{}, {}]
522 def get_cell (self, oldnew):
524 for k in ('time', 'cells'):
526 str += '%-8s: %d\n' % (k, int (self.results[oldnew][k]))
528 str += '%-8s: %8d (%5.3f)\n' % (k, int (self.results[oldnew][k]),
531 return '<pre>%s</pre>' % cgi.escape (str)
533 def get_ratio (self, key):
534 (v1,v2) = (self.results[0].get (key, -1),
535 self.results[1].get (key, -1))
537 if v1 <= 0 or v2 <= 0:
540 return (v1 - v2) / float (v1+v2)
542 def calc_distance (self):
545 self.results[oldnew][m.group(1)] = float (m.group (2))
547 re.sub ('([a-z]+): ([-0-9.]+)\n',
548 note_info, self.contents[oldnew])
556 for k in ('time', 'cells'):
557 real_val = math.tan (self.get_ratio (k) * 0.5 * math.pi)
558 dist += math.exp (math.fabs (real_val) * factor[k]) - 1
560 dist = min (dist, 100)
564 class MidiFileLink (TextFileCompareLink):
565 def get_content (self, oldnew):
568 data = FileCompareLink.get_content (self, oldnew)
569 midi = midi.parse (data)
575 str += 'track %d' % j
580 if re.search ('LilyPond [0-9.]+', ev_str):
583 str += ' ev %s\n' % `e`
588 class SignatureFileLink (FileLink):
589 def __init__ (self, f1, f2 ):
590 FileLink.__init__ (self, f1, f2)
591 self.system_links = {}
593 def add_system_link (self, link, number):
594 self.system_links[number] = link
596 def calc_distance (self):
599 orphan_distance = 0.0
600 for l in self.system_links.values ():
601 d = max (d, l.geometric_distance ())
602 orphan_distance += l.orphan_count ()
604 return d + orphan_distance
606 def add_file_compare (self, f1, f2):
609 def note_system_index (m):
610 system_index.append (int (m.group (1)))
613 base1 = re.sub ("-([0-9]+).signature", note_system_index, f1)
614 base2 = re.sub ("-([0-9]+).signature", note_system_index, f2)
616 self.base_names = (os.path.normpath (base1),
617 os.path.normpath (base2))
619 s1 = read_signature_file (f1)
620 s2 = read_signature_file (f2)
622 link = SystemLink (s1, s2)
624 self.add_system_link (link, system_index[0])
627 def create_images (self, dest_dir):
629 files_created = [[], []]
630 for oldnew in (0, 1):
631 pat = self.base_names[oldnew] + '.eps'
633 for f in glob.glob (pat):
635 outfile = (dest_dir + '/' + f).replace ('.eps', '.png')
637 if options.local_data_dir:
638 data_option = ('-slilypond-datadir=%s/share/lilypond/current '
639 % os.path.dirname(infile))
641 mkdir (os.path.split (outfile)[0])
642 cmd = ('gs -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 '
645 ' -dAutoRotatePages=/None '
646 ' -sOutputFile=%(outfile)s -dNOSAFER -dEPSCrop -q -dNOPAUSE '
647 ' %(infile)s -c quit ') % locals ()
649 files_created[oldnew].append (outfile)
654 def link_files_for_html (self, dest_dir):
655 FileLink.link_files_for_html (self, dest_dir)
656 to_compare = [[], []]
659 if options.create_images:
660 to_compare = self.create_images (dest_dir)
662 exts += ['.png', '-page*png']
666 for f in glob.glob (self.base_names[oldnew] + ext):
667 dst = dest_dir + '/' + f
670 if f.endswith ('.png'):
671 to_compare[oldnew].append (f)
673 if options.compare_images:
674 for (old, new) in zip (to_compare[0], to_compare[1]):
675 compare_png_images (old, new, dest_dir)
678 def get_cell (self, oldnew):
679 def img_cell (ly, img, name):
683 name = '<tt>%s</tt>' % name
687 <img src="%(img)s" style="border-style: none; max-width: 500px;">
690 def multi_img_cell (ly, imgs, name):
694 name = '<tt>%s</tt>' % name
696 imgs_str = '\n'.join (['''<a href="%s">
697 <img src="%s" style="border-style: none; max-width: 500px;">
698 </a><br>''' % (img, img)
708 def cell (base, name):
709 pat = base + '-page*.png'
710 pages = glob.glob (pat)
713 return multi_img_cell (base + '.ly', sorted (pages), name)
715 return img_cell (base + '.ly', base + '.png', name)
719 str = cell (os.path.splitext (self.file_names[oldnew])[0], self.name ())
720 if options.compare_images and oldnew == 1:
721 str = str.replace ('.png', '.compare.jpeg')
726 def get_distance_details (self):
727 systems = self.system_links.items ()
731 for (c, link) in systems:
732 e = '<td>%d</td>' % c
733 for d in link.distance ():
734 e += '<td>%f</td>' % d
736 e = '<tr>%s</tr>' % e
740 e = '<td>%d</td>' % c
741 for s in (link.output_expression_details_string (),
742 link.orphan_details_string (),
743 link.geo_details_string ()):
744 e += "<td>%s</td>" % s
747 e = '<tr>%s</tr>' % e
750 original = self.name ()
753 <title>comparison details for %(original)s</title>
773 ################################################################
778 def compare_signature_files (f1, f2):
779 s1 = read_signature_file (f1)
780 s2 = read_signature_file (f2)
782 return SystemLink (s1, s2).distance ()
784 def paired_files (dir1, dir2, pattern):
786 Search DIR1 and DIR2 for PATTERN.
788 Return (PAIRED, MISSING-FROM-2, MISSING-FROM-1)
793 for d in (dir1,dir2):
794 found = [os.path.split (f)[1] for f in glob.glob (d + '/' + pattern)]
795 found = dict ((f, 1) for f in found)
807 return (pairs, files[1].keys (), missing)
809 class ComparisonData:
811 self.result_dict = {}
816 def read_sources (self):
818 ## ugh: drop the .ly.txt
819 for (key, val) in self.file_links.items ():
821 def note_original (match, ln=val):
823 hash_to_original_name[key] = match.group (1)
826 sf = val.source_file ()
828 re.sub (r'\\sourcefilename "([^"]+)"',
829 note_original, open (sf).read ())
831 print 'no source for', val.file_names[1]
833 def compare_trees (self, dir1, dir2):
834 self.compare_directories (dir1, dir2)
837 (root, dirs, files) = os.walk (dir1).next ()
838 except StopIteration:
839 if dir1.endswith("-baseline"):
840 sys.stderr.write("Failed to walk through %s. This can be caused by forgetting to run make test-baseline.\n" % dir1)
842 sys.stderr.write("Failed to walk through %s; please check it exists.\n" % dir1)
846 # don't walk the share folders
847 if d.startswith("share"):
850 d1 = os.path.join (dir1, d)
851 d2 = os.path.join (dir2, d)
853 if os.path.islink (d1) or os.path.islink (d2):
856 if os.path.isdir (d2):
857 self.compare_trees (d1, d2)
859 def compare_directories (self, dir1, dir2):
860 for ext in ['signature',
865 (paired, m1, m2) = paired_files (dir1, dir2, '*.' + ext)
867 self.missing += [(dir1, m) for m in m1]
868 self.added += [(dir2, m) for m in m2]
871 if (options.max_count
872 and len (self.file_links) > options.max_count):
877 self.compare_files (f1, f2)
879 def compare_files (self, f1, f2):
880 if f1.endswith ('signature'):
881 self.compare_signature_files (f1, f2)
883 ext = os.path.splitext (f1)[1]
885 '.midi': MidiFileLink,
886 '.log' : LogFileCompareLink,
887 '.profile': ProfileFileLink,
888 '.gittxt': GitFileCompareLink,
891 if klasses.has_key (ext):
892 self.compare_general_files (klasses[ext], f1, f2)
894 def compare_general_files (self, klass, f1, f2):
895 prefix = os.path.commonprefix ([f1, f2])
896 name = os.path.split (f1)[1]
897 name = os.path.join (prefix, name)
899 file_link = klass (f1, f2)
900 self.file_links[name] = file_link
902 def compare_signature_files (self, f1, f2):
903 prefix = os.path.commonprefix ([f1, f2])
904 name = os.path.split (f1)[1]
905 name = re.sub ('-[0-9]+.signature', '', name)
906 name = os.path.join (prefix, name)
910 file_link = self.file_links[name]
912 generic_f1 = re.sub ('-[0-9]+.signature', '.ly', f1)
913 generic_f2 = re.sub ('-[0-9]+.signature', '.ly', f2)
914 file_link = SignatureFileLink (generic_f1, generic_f2)
915 self.file_links[name] = file_link
917 file_link.add_file_compare (f1, f2)
919 def write_changed (self, dest_dir, threshold):
920 (changed, below, unchanged) = self.thresholded_results (threshold)
922 str = '\n'.join ([os.path.splitext (link.file_names[1])[0]
923 for link in changed])
924 fn = dest_dir + '/changed.txt'
926 open_write_file (fn).write (str)
928 def thresholded_results (self, threshold):
929 ## todo: support more scores.
930 results = [(link.distance(), link)
931 for link in self.file_links.values ()]
935 unchanged = [r for (d,r) in results if d == 0.0]
936 below = [r for (d,r) in results if threshold >= d > 0.0]
937 changed = [r for (d,r) in results if d > threshold]
939 return (changed, below, unchanged)
941 def write_text_result_page (self, filename, threshold):
946 print 'writing "%s"' % filename
947 out = open_write_file (filename)
949 (changed, below, unchanged) = self.thresholded_results (threshold)
953 out.write (link.text_record_string ())
956 out.write ('%d below threshold\n' % len (below))
957 out.write ('%d unchanged\n' % len (unchanged))
959 def create_text_result_page (self, dest_dir, threshold):
960 self.write_text_result_page (dest_dir + '/index.txt', threshold)
962 def create_html_result_page (self, dest_dir, threshold):
963 (changed, below, unchanged) = self.thresholded_results (threshold)
968 <th>%(short_dir1)s</th>
969 <th>%(short_dir2)s</th>
976 this_prefix = link.prefix ()
977 if (old_prefix != this_prefix):
978 old_prefix = this_prefix
979 short_dir1 = shorten_string (link.directories ()[0], 30)
980 short_dir2 = shorten_string (link.directories ()[1], 30)
981 table_rows += header_row % locals()
982 table_rows += link.html_record_string (dest_dir)
985 below_count = len (below)
988 summary += '<p>%d below threshold</p>' % below_count
990 summary += '<p>%d unchanged</p>' % len (unchanged)
996 <title>LilyPond regression test results</title>
997 <meta name="author" content="This file was autogenerated by %(me)s">
998 <script language="javascript" type="text/javascript">
1000 var rows = document.getElementsByTagName("tr");
1001 function showOnlyMatchingRows(substring) {
1002 var rowcount = rows.length;
1003 for (var i = 0; i < rowcount; i++) {
1005 html = row.innerHTML;
1007 ((html.indexOf('>distance<') != -1) ||
1008 (html.indexOf(substring + '">') != -1)) ? "" : "none";
1016 click to filter rows by type:
1017 <a href="#" onClick="showOnlyMatchingRows('.ly')">ly</a> /
1018 <a href="#" onClick="showOnlyMatchingRows('.profile')">profiling</a> /
1019 <a href="#" onClick="showOnlyMatchingRows('.signature')">signature</a> /
1020 <a href="#" onClick="showOnlyMatchingRows('.midi')">midi</a> /
1021 <a href="#" onClick="showOnlyMatchingRows('.log')">log</a> /
1022 <a href="#" onClick="showOnlyMatchingRows('.gittxt')">gittxt</a> /
1023 <a href="#" onClick="showOnlyMatchingRows('')">reset to all</a>
1032 <table rules="rows" border bordercolor="blue">
1036 </html>''' % locals()
1038 dest_file = dest_dir + '/index.html'
1039 open_write_file (dest_file).write (html)
1042 for link in changed:
1043 link.link_files_for_html (dest_dir)
1046 def print_results (self, threshold):
1047 self.write_text_result_page ('', threshold)
1049 def compare_tree_pairs (tree_pairs, dest_dir, threshold):
1050 data = ComparisonData ()
1051 for dir1, dir2 in tree_pairs:
1052 data.compare_trees (dir1, dir2)
1053 data.read_sources ()
1055 data.print_results (threshold)
1057 if os.path.isdir (dest_dir):
1058 system ('rm -rf %s '% dest_dir)
1060 data.write_changed (dest_dir, threshold)
1061 data.create_html_result_page (dest_dir, threshold)
1062 data.create_text_result_page (dest_dir, threshold)
1064 ################################################################
1068 if not os.path.isdir (x):
1072 def link_file (x, y):
1073 mkdir (os.path.split (y)[0])
1078 print 'OSError', x, y, z
1081 def open_write_file (x):
1082 d = os.path.split (x)[0]
1084 return open (x, 'w')
1090 stat = os.system (x)
1094 # Allow exit status 0 and 1
1096 stat = os.system (x)
1097 assert (stat == 0) or (stat == 256) # This return value convention is sick.
1100 def test_paired_files ():
1101 print paired_files (os.environ["HOME"] + "/src/lilypond/scripts/",
1102 os.environ["HOME"] + "/src/lilypond-stable/scripts/build/", '*.py')
1105 def test_compare_tree_pairs ():
1106 system ('rm -rf dir1 dir2')
1107 system ('mkdir dir1 dir2')
1108 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1109 system ('cp 20{-*.signature,.ly,.png,.eps,.log,.profile} dir2')
1110 system ('cp 20expr{-*.signature,.ly,.png,.eps,.log,.profile} dir1')
1111 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1112 system ('cp 19{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1113 system ('cp 19-1.signature 19.sub-1.signature')
1114 system ('cp 19.ly 19.sub.ly')
1115 system ('cp 19.profile 19.sub.profile')
1116 system ('cp 19.log 19.sub.log')
1117 system ('cp 19.png 19.sub.png')
1118 system ('cp 19.eps 19.sub.eps')
1120 system ('cp 20multipage* dir1')
1121 system ('cp 20multipage* dir2')
1122 system ('cp 19multipage-1.signature dir2/20multipage-1.signature')
1125 system ('mkdir -p dir1/subdir/ dir2/subdir/')
1126 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir1/subdir/')
1127 system ('cp 19.sub{-*.signature,.ly,.png,.eps,.log,.profile} dir2/subdir/')
1128 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir2/')
1129 system ('cp 20grob{-*.signature,.ly,.png,.eps,.log,.profile} dir1/')
1130 system ('echo HEAD is 1 > dir1/tree.gittxt')
1131 system ('echo HEAD is 2 > dir2/tree.gittxt')
1133 ## introduce differences
1134 system ('cp 19-1.signature dir2/20-1.signature')
1135 system ('cp 19.profile dir2/20.profile')
1136 system ('cp 19.png dir2/20.png')
1137 system ('cp 19multipage-page1.png dir2/20multipage-page1.png')
1138 system ('cp 20-1.signature dir2/subdir/19.sub-1.signature')
1139 system ('cp 20.png dir2/subdir/19.sub.png')
1140 system ("sed 's/: /: 1/g' 20.profile > dir2/subdir/19.sub.profile")
1143 system ('cp 19-1.signature dir2/20grob-1.signature')
1144 system ('cp 19-1.signature dir2/20grob-2.signature')
1145 system ('cp 19multipage.midi dir1/midi-differ.midi')
1146 system ('cp 20multipage.midi dir2/midi-differ.midi')
1147 system ('cp 19multipage.log dir1/log-differ.log')
1148 system ('cp 19multipage.log dir2/log-differ.log && echo different >> dir2/log-differ.log && echo different >> dir2/log-differ.log')
1150 compare_tree_pairs (['dir1', 'dir2'], 'compare-dir1dir2', options.threshold)
1153 def test_basic_compare ():
1157 #(define default-toplevel-book-handler
1158 print-book-with-defaults-as-systems )
1160 #(ly:set-option (quote no-point-and-click))
1162 \sourcefilename "my-source.ly"
1165 \header { tagline = ##f }
1168 \new Staff \relative c {
1169 c4^"%(userstring)s" %(extragrob)s
1171 \new Staff \relative c {
1172 c4^"%(userstring)s" %(extragrob)s
1180 dicts = [{ 'papermod' : '',
1183 'userstring': 'test' },
1184 { 'papermod' : '#(set-global-staff-size 19.5)',
1187 'userstring': 'test' },
1191 'userstring': 'blabla' },
1194 'extragrob': 'r2. \\break c1',
1195 'userstring': 'test' },
1199 open (d['name'] + '.ly','w').write (ly_template % d)
1201 names = [d['name'] for d in dicts]
1203 system ('lilypond -ddump-profile -dseparate-log-files -ddump-signatures --png -dbackend=eps ' + ' '.join (names))
1206 multipage_str = r'''
1207 #(set-default-paper-size "a6")
1209 \relative c' { c1 \pageBreak c1 }
1215 open ('20multipage.ly', 'w').write (multipage_str.replace ('c1', 'd1'))
1216 open ('19multipage.ly', 'w').write ('#(set-global-staff-size 19.5)\n' + multipage_str)
1217 system ('lilypond -dseparate-log-files -ddump-signatures --png 19multipage 20multipage ')
1219 test_compare_signatures (names)
1221 def test_compare_signatures (names, timing=False):
1231 for t in range (0, times):
1232 sigs = dict ((n, read_signature_file ('%s-1.signature' % n)) for n in names)
1236 print 'elapsed', (time.clock() - t0)/count
1242 for (n1, s1) in sigs.items():
1243 for (n2, s2) in sigs.items():
1244 combinations['%s-%s' % (n1, n2)] = SystemLink (s1,s2).distance ()
1248 print 'elapsed', (time.clock() - t0)/count
1250 results = combinations.items ()
1253 print '%-20s' % k, v
1255 assert combinations['20-20'] == (0.0,0.0,0.0)
1256 assert combinations['20-20expr'][0] > 0.0
1257 assert combinations['20-19'][2] < 10.0
1258 assert combinations['20-19'][2] > 0.0
1262 dir = 'test-output-distance'
1264 do_clean = not os.path.exists (dir)
1266 print 'test results in ', dir
1268 system ('rm -rf ' + dir)
1269 system ('mkdir ' + dir)
1273 test_basic_compare ()
1275 test_compare_tree_pairs ()
1277 ################################################################
1281 p = optparse.OptionParser ("output-distance - compare LilyPond formatting runs")
1282 p.usage = 'output-distance.py [options] tree1 tree2 [tree3 tree4]...'
1284 p.add_option ('', '--test-self',
1286 action="store_true",
1287 help='run test method')
1289 p.add_option ('--max-count',
1295 help='only analyze COUNT signature pairs')
1297 p.add_option ('', '--threshold',
1302 help='threshold for geometric distance')
1304 p.add_option ('--no-compare-images',
1305 dest="compare_images",
1307 action="store_false",
1308 help="Don't run graphical comparisons")
1310 p.add_option ('--create-images',
1311 dest="create_images",
1313 action="store_true",
1314 help="Create PNGs from EPSes")
1317 p.add_option ('--local-datadir',
1318 dest="local_data_dir",
1320 action="store_true",
1321 help='whether to use the share/lilypond/ directory in the test directory')
1323 p.add_option ('-o', '--output-dir',
1328 help='where to put the test results [tree2/compare-tree1tree2]')
1331 (options, args) = p.parse_args ()
1333 if options.run_test:
1337 if len (args) % 2 == 1:
1341 out = options.output_dir
1343 out = args[0].replace ('/', '')
1344 out = os.path.join (args[1], 'compare-' + shorten_string (out))
1346 compare_tree_pairs (zip (args[0::2], args[1::2]), out, options.threshold)
1348 if __name__ == '__main__':