File: parse_test.py

package info (click to toggle)
auto-07p 0.9.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 16,200 kB
  • sloc: fortran: 22,644; f90: 19,340; python: 19,045; ansic: 11,116; sh: 1,079; makefile: 618; perl: 339
file content (351 lines) | stat: -rwxr-xr-x 12,608 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python
#global imports for the whole file
import re,sys,getopt,os
try:
    import cStringIO
except ImportError: # Python 3
    import io as cStringIO
try:
    from urllib import pathname2url
except ImportError: # Python 3
    from urllib.request import pathname2url
import parseB

#A few template strings which will be used later for reports, etc.

no_demo_string="""
Trial file does not have appropriate demo

Errors (if any) reported during compilation:

%s
"""

different_floats="""
======================
trial string:
======================
%s

======================
correct string:
======================
%s

"""

no_matching_float="""
Trial string has a non float where the correct string has a float:
demo:          %s
correct_value: %s
trial value:   %s

"""+different_floats

#All the demos in the AUTO distribution
all_demos=["pp2","exp","int","dd2","opt","lin","bvp","pp3","wav","plp",
           "ab","abc","brc","brf","bru","chu","cir","enz",
           "ext","ezp","frc","fsh","ivp","kar","kpr","lor","lrz",
           "mtn","nag","non","obv","ops","pd1","pd2","pen","phs",
           "ppp","pvl","rev","san","she","spb","stw","tim","tor"]

DEMO_OK=0
DEMO_MINOR_DATA_ERROR=1
DEMO_MAJOR_DATA_ERROR=2
DEMO_FAILED=4

def check_demo(demo,correct_filename,trial_filename,epsilon,abseps):
    # A regular expression for finding floating point numbers
    float_regex=re.compile('[ -][0-9]\.[0-9]+[-+eE][-+0-9][0-9]+',re.S)
    # A regular expression for finding each demo block
    demo_regex=re.compile("Demo %s is started.*Demo %s is done"%(demo,demo),re.S,)
    # A regular expression for finding a header
    header_regex=re.compile('BR',re.S)
    # A regular expression for finding each error block
    error_regex=re.compile("===%s start===.*===%s end==="%(demo,demo),re.S)

    # This is where the report get stored until it gets returned
    report = cStringIO.StringIO()

    # Search for all possible demos in each file
    correct_file=open(correct_filename,"r")
    correct_file=correct_file.read()
    trial_file=open(trial_filename,"r")
    trial_file=trial_file.read()

    # Use the regular expressions to find the appropriate blocks (if any)
    correct_result=demo_regex.search(correct_file)
    if correct_result is None:
        return (DEMO_FAILED,"Correct file does not have appropriate demo")
    else:
        correct_string=correct_result.group()

    trial_result=demo_regex.search(trial_file)
    if trial_result is None:
        error_file = open("%serrors"%trial_filename,"r")
        error_file = error_file.read()
        error_result=error_regex.search(error_file)
        if error_result is None:
            return (DEMO_FAILED,"Demo could not be found in trial file")
        else:
            return (DEMO_FAILED,no_demo_string%error_result.group())
    else:
        trial_string=trial_result.group()

    # Now that we have the corresponding blocks from each file we look at each
    # Floating point number is each and see if they are within epsilon
    # percentage of each other.
    end=0
    offset=1
    correct_item=header_regex.search(correct_string,0)
    trial_item=header_regex.search(trial_string,0)
    maxdiff = 0
    maxratio = 0
    if correct_item is not None and trial_item is not None:
        end=correct_item.end()
        offset=trial_item.end()-end
    while True:
        start=end
        correct_item=float_regex.search(correct_string,start)
        if correct_item is None:
            break
        start=correct_item.start()
        end=correct_item.end()
        trial_item=float_regex.search(trial_string[start+offset-1:end+offset+1])
        correct_data=parseB.AUTOatof(correct_item.group())
        try:
            trial_data=parseB.AUTOatof(trial_item.group())
            if trial_item.start() > 0:
                offset=trial_item.start()+offset-1
        except (ValueError, AttributeError):
            correct_string="%s<B><font color=Red>%s</font></B>%s"%(
                correct_string[:start],correct_string[start:end],
                correct_string[end:])
            trial_string="%s<B><font color=Red>%s</font></B>%s"%(
                trial_string[:start+offset],trial_string[start+offset:end+offset],
                trial_string[end+offset:])
            return (DEMO_MAJOR_DATA_ERROR,
                    no_matching_float%(demo,correct_item.group(),trial_item,
                                       trial_string,correct_string))

        if correct_string[start-7:start-3] == "Time":
            start=end
            correct_item=header_regex.search(correct_string,start)
            trial_item=header_regex.search(trial_string,start+offset)
            if correct_item is not None and trial_item is not None:
                start=correct_item.start()
                end=correct_item.end()
                offset=trial_item.end()-end
        else:
            diff = abs(trial_data-correct_data)
            if trial_data == 0.0:
                ratio1 = abs(correct_data)+epsilon
            else:
                ratio1 = abs(diff/trial_data)

            if correct_data == 0.0:
                ratio2 = abs(trial_data)+epsilon
            else:
                ratio2 = abs(diff/correct_data)
            ratio = max(ratio1, ratio2)

            if diff > abseps and ratio > epsilon:
                maxdiff = max(diff, maxdiff)
                maxratio = max(ratio, maxratio)
                report.write("Files do not match at the %dth character for demo %s\n"%(start,demo))
                report.write("Value of trial is %e\n"%trial_data)
                report.write("Value of correct file is %e\n\n"%correct_data)
                correct_string="%s<I><font color=Blue>%s</font></I>%s"%(
                    correct_string[:start],correct_string[start:end],
                    correct_string[end:])
                trial_string="%s<I><font color=Blue>%s</font></I>%s"%(
                    trial_string[:start+offset],trial_string[start+offset:end+offset],
                    trial_string[end+offset:])
                start += 31
                end += 31
    report_string = report.getvalue()
    if len(report_string)==0:
        return (DEMO_OK,"")
    else:
        return (DEMO_MINOR_DATA_ERROR,report_string+
                different_floats%(trial_string,correct_string),
                maxratio,maxdiff)

#====================== HTMLGen style class and functions ========

class BasicDocument(object):
    def __init__(self):
        self.header = ["""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>

<!-- This file generated using parse_test.py module. -->
<HEAD>
  <META NAME="GENERATOR" CONTENT="AUTO-07P">
        <TITLE></TITLE> </HEAD>
<BODY>"""]
        self.footer = ["\n</BODY> </HTML>\n"]
        self.lst = []

    def append(self, s):
        self.lst.append(str(s))

    def write(self, s):
        f = open(s,"w")
        f.write("\n".join(self.header+self.lst+self.footer))
        f.close()

class Table(object):
    def __init__(self, name, width="", cell_padding=""):
        header = ['<A NAME="%s"></A>\n'%name,
                '<P><TABLE border=2 cellpadding=%s cellspacing=1 width="%s">\n'%
                (cell_padding, width),
                '<CAPTION align=top><STRONG>%s</STRONG></CAPTION>\n'%name]
        self.header = header
        self.heading = []
        self.body = []
        self.footer = ['</TABLE><P>\n']

    def __str__(self):
        lst = self.header + ['<TR Align=center> ']
        for s in self.heading:
            lst.append('<TH ColSpan=1>%s</TH>'%s)
        lst.append('</TR>\n')
        for line in self.body:
            lst.append('<TR>')
            for cell in line:
                lst.append('<TD Align=left >%s</TD>\n'%cell)
            lst.append('</TR>\n')
        lst.extend(self.footer)
        return "".join(lst)

def H(sz, s):
    return "<H%d>%s</H%d>\n"%(sz,s,sz)

def Image(s, border=0):
    return '<IMG src="%s" alt="%s" border="%d">'%(s,s,border)

def Pre(s):
    return '<PRE>%s</PRE>\n'%(s)

def Href(text="", url=""):
    return '<A HREF="%s">%s</A>'%(url,text)

#====================== main program =============================

def parse(trial_file,epsilon=None, abseps=None, demo=None, html_dir=None,
          correct_file=None, demos=None):
    if isinstance(trial_file, str):
        trial_file = trial_file,
    if epsilon is None:
        epsilon = 0.01
    if abseps is None:
        abseps = 1e-7
    if demo is None:
        demo=""
    if demos is None:
        demos=all_demos
    if html_dir is None:
        html_dir="verification"
    if correct_file is None:
        correct_file = "hyper.all"
    report_list = { DEMO_OK: [],
                    DEMO_MINOR_DATA_ERROR: [],
                    DEMO_MAJOR_DATA_ERROR: [],
                    DEMO_FAILED: [] }

    print ("Comparing against file:  %s"%correct_file)
    print ("Putting results in directory:  %s"%html_dir)

    table = []
    if len(demo) == 0:
        top = BasicDocument()
        top.append(H(1,"Correct file %s"%correct_file))
        ok = Image("green_swatch.png",border=0)
        data_minor_error = Image("yellow_swatch.png",border=0)
        data_major_error = Image("orange_swatch.png",border=0)
        did_not_work = Image("red_swatch.png",border=0)
        dct = { DEMO_MINOR_DATA_ERROR: data_minor_error,
                DEMO_MAJOR_DATA_ERROR: data_major_error,
                DEMO_FAILED: did_not_work }
        for demo in demos:
            table_line = []
            i=0
            for fil in trial_file:
                if i%5 == 0:
                    table_line.append(demo)
                i = i + 1
                demofile = "%s_%s%d.html"%(os.path.basename(fil),
                                           demo.replace(os.sep,"_"),i)
                report = check_demo(demo,correct_file,fil,epsilon,abseps)
                if report[0]==DEMO_MINOR_DATA_ERROR:
                    report_list[report[0]].append((demo,)+report[2:])
                else:
                    report_list[report[0]].append(demo)
                if report[0]==DEMO_OK:
                    table_line.append(ok)
                else:
                    sub_page = BasicDocument()
                    sub_page.append(Pre(report[1]))
                    sub_page.write(os.path.join(html_dir,demofile))
                    table_line.append(Href(text=dct[report[0]],url=demofile))
            table.append(table_line)
        if len(html_dir) != 0:
            html_table =Table("Results of tests",width="30%",cell_padding="0")
            html_table.body = table

            i=0
            headings=[]
            for fil in trial_file:
                if i%5 == 0:
                    headings.append("Demo")
                i = i + 1
                headings.append(os.path.basename(os.path.dirname(fil))+"\n"
                                +os.path.basename(fil))
            html_table.heading = headings
            top.append(html_table)
            top.write("%s/index.html"%html_dir)
        dct = { DEMO_OK: "No errors found in:",
                DEMO_MINOR_DATA_ERROR: "Minor errors found in:",
                DEMO_MAJOR_DATA_ERROR: "Major errors found in:",
                DEMO_FAILED: "The following demos failed:" }
        for i in [DEMO_OK, DEMO_MINOR_DATA_ERROR,
                  DEMO_MAJOR_DATA_ERROR, DEMO_FAILED]:
            if len(report_list[i]) > 0:            
                if i==DEMO_MINOR_DATA_ERROR:
                    print(dct[i])
                    print("          Relative Error Absolute Error")
                    for lst in report_list[i]:
                        print("%-6s: %15.7e%15.7e"%(lst[0],lst[1],lst[2]))
                elif len(report_list[i]) > 0:
                    print(" ".join([dct[i]]+report_list[i]))
        print("Please point your web browser to the following URL "
              "for detailed results:\nfile:%s"%
              pathname2url(os.path.abspath("verification/index.html")))
    else:
        check_demo(demo,correct_file,trial_file,epsilon,abseps)

if __name__ == "__main__":
    opts_list,args = getopt.getopt(sys.argv[1:],"c:t:d:e:h:")
    epsilon = None
    demo = None
    html_dir = None
    correct_file = None
    trial_file = args
    for x in opts_list:
        if x[0]=="-a":
            abseps=float(x[1])
        if x[0]=="-c":
            correct_file=x[1]                         
        if x[0]=="-d":
            demo=x[1]
        if x[0]=="-e":
            epsilon=float(x[1])
        if x[0]=="-h":
            html_dir=x[1]
    parse(trial_file, correct_file, demo, epsilon, html_dir)