Debian Codegraph @

07p/test/parse_test.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #global imports for the whole file
3 import re,sys,getopt,os
4 try:
5 import cStringIO
6 except ImportError: # Python 3
7 import io as cStringIO
8 try:
9 from urllib import pathname2url
10 except ImportError: # Python 3
11 from urllib.request import pathname2url
12 from auto import parseB
13
14 #A few template strings which will be used later for reports, etc.
15
16 no_demo_string="""
17 Trial file does not have appropriate demo
18
19 Errors (if any) reported during compilation:
20
21 %s
22 """
23
24 different_floats="""
25 ======================
26 trial string:
27 ======================
28 %s
29
30 ======================
31 correct string:
32 ======================
33 %s
34
35 """
36
37 no_matching_float="""
38 Trial string has a non float where the correct string has a float:
39 demo: %s
40 correct_value: %s
41 trial value: %s
42
43 """+different_floats
44
45 #All the demos in the AUTO distribution
46 all_demos=["pp2","exp","int","dd2","opt","lin","bvp","pp3","wav","plp",
47 "ab","abc","brc","brf","bru","chu","cir","enz",
48 "ext","ezp","frc","fsh","ivp","kar","kpr","lor","lrz",
49 "mtn","nag","non","obv","ops","pd1","pd2","pen","phs",
50 "ppp","pvl","rev","san","she","spb","stw","tim","tor"]
51
52 DEMO_OK=0
53 DEMO_MINOR_DATA_ERROR=1
54 DEMO_MAJOR_DATA_ERROR=2
55 DEMO_FAILED=4
56
57 def check_demo(demo,correct_filename,trial_filename,epsilon,abseps):
58 # A regular expression for finding floating point numbers
59 float_regex=re.compile('[ -][0-9]\.[0-9]+[-+eE][-+0-9][0-9]+',re.S)
60 # A regular expression for finding each demo block
61 demo_regex=re.compile("Demo %s is started.*Demo %s is done"%(demo,demo),re.S,)
62 # A regular expression for finding a header
63 header_regex=re.compile('BR',re.S)
64 # A regular expression for finding each error block
65 error_regex=re.compile("===%s start===.*===%s end==="%(demo,demo),re.S)
66
67 # This is where the report get stored until it gets returned
68 report = cStringIO.StringIO()
69
70 # Search for all possible demos in each file
71 correct_file=open(correct_filename,"r")
72 correct_file=correct_file.read()
73 trial_file=open(trial_filename,"r")
74 trial_file=trial_file.read()
75
76 # Use the regular expressions to find the appropriate blocks (if any)
77 correct_result=demo_regex.search(correct_file)
78 if correct_result is None:
79 return (DEMO_FAILED,"Correct file does not have appropriate demo")
80 else:
81 correct_string=correct_result.group()
82
83 trial_result=demo_regex.search(trial_file)
84 if trial_result is None:
85 error_file = open("%serrors"%trial_filename,"r")
86 error_file = error_file.read()
87 error_result=error_regex.search(error_file)
88 if error_result is None:
89 return (DEMO_FAILED,"Demo could not be found in trial file")
90 else:
91 return (DEMO_FAILED,no_demo_string%error_result.group())
92 else:
93 trial_string=trial_result.group()
94
95 # Now that we have the corresponding blocks from each file we look at each
96 # Floating point number is each and see if they are within epsilon
97 # percentage of each other.
98 end=0
99 offset=1
100 correct_item=header_regex.search(correct_string,0)
101 trial_item=header_regex.search(trial_string,0)
102 maxdiff = 0
103 maxratio = 0
104 if correct_item is not None and trial_item is not None:
105 end=correct_item.end()
106 offset=trial_item.end()-end
107 while True:
108 start=end
109 correct_item=float_regex.search(correct_string,start)
110 if correct_item is None:
111 break
112 start=correct_item.start()
113 end=correct_item.end()
114 trial_item=float_regex.search(trial_string[start+offset-1:end+offset+1])
115 correct_data=parseB.AUTOatof(correct_item.group())
116 try:
117 trial_data=parseB.AUTOatof(trial_item.group())
118 if trial_item.start() > 0:
119 offset=trial_item.start()+offset-1
120 except (ValueError, AttributeError):
121 correct_string="%s<B><font color=Red>%s</font></B>%s"%(
122 correct_string[:start],correct_string[start:end],
123 correct_string[end:])
124 trial_string="%s<B><font color=Red>%s</font></B>%s"%(
125 trial_string[:start+offset],trial_string[start+offset:end+offset],
126 trial_string[end+offset:])
127 return (DEMO_MAJOR_DATA_ERROR,
128 no_matching_float%(demo,correct_item.group(),trial_item,
129 trial_string,correct_string))
130
131 if correct_string[start-7:start-3] == "Time":
132 start=end
133 correct_item=header_regex.search(correct_string,start)
134 trial_item=header_regex.search(trial_string,start+offset)
135 if correct_item is not None and trial_item is not None:
136 start=correct_item.start()
137 end=correct_item.end()
138 offset=trial_item.end()-end
139 else:
140 diff = abs(trial_data-correct_data)
141 if trial_data == 0.0:
142 ratio1 = abs(correct_data)+epsilon
143 else:
144 ratio1 = abs(diff/trial_data)
145
146 if correct_data == 0.0:
147 ratio2 = abs(trial_data)+epsilon
148 else:
149 ratio2 = abs(diff/correct_data)
150 ratio = max(ratio1, ratio2)
151
152 if diff > abseps and ratio > epsilon:
153 maxdiff = max(diff, maxdiff)
154 maxratio = max(ratio, maxratio)
155 report.write("Files do not match at the %dth character for demo %s\n"%(start,demo))
156 report.write("Value of trial is %e\n"%trial_data)
157 report.write("Value of correct file is %e\n\n"%correct_data)
158 correct_string="%s<I><font color=Blue>%s</font></I>%s"%(
159 correct_string[:start],correct_string[start:end],
160 correct_string[end:])
161 trial_string="%s<I><font color=Blue>%s</font></I>%s"%(
162 trial_string[:start+offset],trial_string[start+offset:end+offset],
163 trial_string[end+offset:])
164 start += 31
165 end += 31
166 report_string = report.getvalue()
167 if len(report_string)==0:
168 return (DEMO_OK,"")
169 else:
170 return (DEMO_MINOR_DATA_ERROR,report_string+
171 different_floats%(trial_string,correct_string),
172 maxratio,maxdiff)
173
174 #====================== HTMLGen style class and functions ========
175
176 class BasicDocument(object):
177 def __init__(self):
178 self.header = ["""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
179 <HTML>
180
181 <!-- This file generated using parse_test.py module. -->
182 <HEAD>
183 <META NAME="GENERATOR" CONTENT="AUTO-07P">
184 <TITLE></TITLE> </HEAD>
185 <BODY>"""]
186 self.footer = ["\n</BODY> </HTML>\n"]
187 self.lst = []
188
189 def append(self, s):
190 self.lst.append(str(s))
191
192 def write(self, s):
193 f = open(s,"w")
194 f.write("\n".join(self.header+self.lst+self.footer))
195 f.close()
196
197 class Table(object):
198 def __init__(self, name, width="", cell_padding=""):
199 header = ['<A NAME="%s"></A>\n'%name,
200 '<P><TABLE border=2 cellpadding=%s cellspacing=1 width="%s">\n'%
201 (cell_padding, width),
202 '<CAPTION align=top><STRONG>%s</STRONG></CAPTION>\n'%name]
203 self.header = header
204 self.heading = []
205 self.body = []
206 self.footer = ['</TABLE><P>\n']
207
208 def __str__(self):
209 lst = self.header + ['<TR Align=center> ']
210 for s in self.heading:
211 lst.append('<TH ColSpan=1>%s</TH>'%s)
212 lst.append('</TR>\n')
213 for line in self.body:
214 lst.append('<TR>')
215 for cell in line:
216 lst.append('<TD Align=left >%s</TD>\n'%cell)
217 lst.append('</TR>\n')
218 lst.extend(self.footer)
219 return "".join(lst)
220
221 def H(sz, s):
222 return "<H%d>%s</H%d>\n"%(sz,s,sz)
223
224 def Image(s, border=0):
225 return '<IMG src="%s" alt="%s" border="%d">'%(s,s,border)
226
227 def Pre(s):
228 return '<PRE>%s</PRE>\n'%(s)
229
230 def Href(text="", url=""):
231 return '<A HREF="%s">%s</A>'%(url,text)
232
233 #====================== main program =============================
234
235 def parse(trial_file,epsilon=None, abseps=None, demo=None, html_dir=None,
236 correct_file=None, demos=None):
237 if isinstance(trial_file, str):
238 trial_file = trial_file,
239 if epsilon is None:
240 epsilon = 0.01
241 if abseps is None:
242 abseps = 1e-7
243 if demo is None:
244 demo=""
245 if demos is None:
246 demos=all_demos
247 if html_dir is None:
248 html_dir="verification"
249 if correct_file is None:
250 correct_file = "hyper.all"
251 report_list = { DEMO_OK: [],
252 DEMO_MINOR_DATA_ERROR: [],
253 DEMO_MAJOR_DATA_ERROR: [],
254 DEMO_FAILED: [] }
255
256 print ("Comparing against file: %s"%correct_file)
257 print ("Putting results in directory: %s"%html_dir)
258
259 table = []
260 retcode = 0
261 if len(demo) == 0:
262 top = BasicDocument()
263 top.append(H(1,"Correct file %s"%correct_file))
264 ok = Image("green_swatch.png",border=0)
265 data_minor_error = Image("yellow_swatch.png",border=0)
266 data_major_error = Image("orange_swatch.png",border=0)
267 did_not_work = Image("red_swatch.png",border=0)
268 dct = { DEMO_MINOR_DATA_ERROR: data_minor_error,
269 DEMO_MAJOR_DATA_ERROR: data_major_error,
270 DEMO_FAILED: did_not_work }
271 for demo in demos:
272 table_line = []
273 i=0
274 for fil in trial_file:
275 if i%5 == 0:
276 table_line.append(demo)
277 i = i + 1
278 demofile = "%s_%s%d.html"%(os.path.basename(fil),
279 demo.replace(os.sep,"_"),i)
280 report = check_demo(demo,correct_file,fil,epsilon,abseps)
281 if report[0]==DEMO_MINOR_DATA_ERROR:
282 report_list[report[0]].append((demo,)+report[2:])
283 else:
284 report_list[report[0]].append(demo)
285 if report[0]==DEMO_OK:
286 table_line.append(ok)
287 else:
288 sub_page = BasicDocument()
289 sub_page.append(Pre(report[1]))
290 sub_page.write(os.path.join(html_dir,demofile))
291 table_line.append(Href(text=dct[report[0]],url=demofile))
292 table.append(table_line)
293 if len(html_dir) != 0:
294 html_table =Table("Results of tests",width="30%",cell_padding="0")
295 html_table.body = table
296
297 i=0
298 headings=[]
299 for fil in trial_file:
300 if i%5 == 0:
301 headings.append("Demo")
302 i = i + 1
303 headings.append(os.path.basename(os.path.dirname(fil))+"\n"
304 +os.path.basename(fil))
305 html_table.heading = headings
306 top.append(html_table)
307 top.write("%s/index.html"%html_dir)
308 dct = { DEMO_OK: "No errors found in:",
309 DEMO_MINOR_DATA_ERROR: "Minor errors found in:",
310 DEMO_MAJOR_DATA_ERROR: "Major errors found in:",
311 DEMO_FAILED: "The following demos failed:" }
312 for i in [DEMO_OK, DEMO_MINOR_DATA_ERROR,
313 DEMO_MAJOR_DATA_ERROR, DEMO_FAILED]:
314 if len(report_list[i]) > 0:
315 if i==DEMO_MINOR_DATA_ERROR:
316 print(dct[i])
317 print(" Relative Error Absolute Error")
318 for lst in report_list[i]:
319 print("%-6s: %15.7e%15.7e"%(lst[0],lst[1],lst[2]))
320 elif len(report_list[i]) > 0:
321 if i != DEMO_OK:
322 retcode = 1
323 print(" ".join([dct[i]]+report_list[i]))
324 print("Please point your web browser to the following URL "
325 "for detailed results:\nfile:%s"%
326 pathname2url(os.path.abspath("verification/index.html")))
327 else:
328 check_demo(demo,correct_file,trial_file,epsilon,abseps)
329 return retcode
330
331 if __name__ == "__main__":
332 opts_list,args = getopt.getopt(sys.argv[1:],"c:t:d:e:h:")
333 epsilon = None
334 demo = None
335 html_dir = None
336 correct_file = None
337 trial_file = args
338 for x in opts_list:
339 if x[0]=="-a":
340 abseps=float(x[1])
341 if x[0]=="-c":
342 correct_file=x[1]
343 if x[0]=="-d":
344 demo=x[1]
345 if x[0]=="-e":
346 epsilon=float(x[1])
347 if x[0]=="-h":
348 html_dir=x[1]
349 sys.exit(parse(trial_file, correct_file, demo, epsilon, html_dir))
350
351
352
353
354
355