-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
executable file
·330 lines (296 loc) · 8.35 KB
/
db.py
File metadata and controls
executable file
·330 lines (296 loc) · 8.35 KB
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
#!/usr/bin/python
from optparse import OptionParser
import ctypes, difflib, pickle, random, re, sys
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
try:
stdout = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
except:
stdout = None
# Colors for good, bad and good but badly ordered responses
COL_OK, COL_BAD, COL_SEMIOK = 10, 12, 14
# Match threshold to consider a good response
GOOD_THRESHOLD = 0.8
lincol = [37, 34, 32, 36, 31, 35, 33, 30]
def setcol(col):
if stdout:
return ctypes.windll.kernel32.SetConsoleTextAttribute(stdout, col)
else:
s = '\033['
if col & 8: s += '1;'
s += str(lincol[col & 7]) + 'm'
print s,
return False
def hilite(txt, col=15, nl=True):
""" Highlight a text with the provided color then go back to the normal one """
global opts
if opts.nocolor:
print txt,
if nl: print
return
# Set color, print text and go back to default color
setcol(col)
print txt,
if nl: print
setcol(7)
class Section:
def __init__(self, name):
self.name = name
self.kh = self.kpe = ''
self.diags = []
def __getitem__(self, n):
return self.diags[n]
def __len__(self):
return len(self.diags)
def __repr__(self):
return 'SEC: %s\nKH: %s\nKPE: %s\n%s' % (self.name, self.kh, self.kpe, repr(self.diags))
class MiniDiag:
crt = 0
def __init__(self):
MiniDiag.crt += 1
self.id = MiniDiag.crt
self.presentation = ''
self.dd = []
self.ww = []
def __repr__(self):
return '%d. %s\nDDD:\n%s\nWWW:\n%s' % (self.id, self.presentation, repr(self.dd), repr(self.ww))
def __str__(self):
str = '%d. %s\n\n' % (self.id, self.presentation)
for i,v in enumerate(self.dd):
str += ' D %d: %s\n' % (i+1, v)
str += '\n'
for i,v in enumerate(self.ww):
str += ' W %d: %s\n' % (i+1, v)
return str
class DB:
def __init__(self):
self.sections = []
self._read_db()
def __repr__(self):
return repr(self.sections)
def random_all(self):
""" Get a random test from all available """
sec = random.choice(self.sections)
t = random.choice(sec.diags)
return t
def get_test(self, id):
""" Get a test based on its id """
for s in self.sections:
if s.diags[0].id <= id <= s.diags[-1].id:
diag = filter(lambda d: d.id == id, s.diags)
if diag:
return diag[0]
break
#No diag found so throw an exception
raise Exception("Diag with id '%d' not found" % id)
def _read_db(self):
f = open('db.txt')
SEC, KH, KPE, P, D, W = range(6)
state = SEC
states = {'S':SEC, 'Key History':KH, 'Key Physical Exam':KPE, 'P':P, 'D':D, 'W':W}
minidiag = section = None
for l in f:
l = l.strip()
if not l or l[0]=='#': continue
if l[0] == ':':
#Command - change state
state = states[l[1:]]
if state == P:
if minidiag:
section.diags.append(minidiag)
minidiag = MiniDiag()
else:
#Add data to current state
if state == SEC:
if section:
self.sections.append(section)
section = Section(l)
minidiag = None
elif state == KH:
if len(section.kh):
section.kh += '\n'
section.kh += l
elif state == KPE:
if len(section.kpe):
section.kpe += '\n'
section.kpe += l
elif state == P:
if len(minidiag.presentation):
minidiag.presentation += '\n'
minidiag.presentation += l
elif state == D:
minidiag.dd.append(l)
elif state == W:
minidiag.ww.append(l)
f.close()
class Test:
#Cleaner expression to remove parenthesis
rg_cleaner = re.compile('\s*\(.*?\)\s*')
def __init__(self, md):
self.minidiag = md
self.dd = []
self.ww = []
def administer(self):
print '%d. %s' % (self.minidiag.id, self.minidiag.presentation)
print '-----'
for i in xrange(20):
res = raw_input('D %d: ' % (i+1))
if not res:
break
self.dd.append(res)
print '-----'
for i in xrange(20):
res = raw_input('W %d: ' % (i+1))
if not res:
break
self.ww.append(res)
def show(self, with_md=True):
"""
Show the results of a test.
with_md - if True show initial minidiag
Returns the calculated points for this md
"""
def show_resp(title, known, answered):
"""
Show a set of results for D or W
Returns the calculated points for this set
The points are calculated like this:
0.00 - bad
0.75 - good, but in bad position
1.00 - all good
"""
hilite(title, 9)
total = 0.0
for i,v in enumerate(answered):
col, points = COL_BAD, 0.0
sm = difflib.SequenceMatcher(None, v.lower(), '')
ratios = []
max_ratio = 0
for j,d in enumerate(known):
sm.set_seq2(Test.rg_cleaner.sub('', d.lower()))
r = sm.ratio()
ratios.append('%.2f' % r)
if r >= GOOD_THRESHOLD and r > max_ratio:
max_ratio = r
col, points = (COL_OK, 1.0) if i==j else (COL_SEMIOK, 0.75)
print ' ', (i+1),
chr = '-..+*'[int(points*4)]
hilite(chr, 11, nl=False)
hilite(v, col)
if opts.verbose:
print ' ', ' '.join(ratios)
# Update the total points
total += points/len(known)
print 'Total: %.2f' % total
return total
print '=================='
if with_md:
print self.minidiag
p1 = show_resp("Resp D", self.minidiag.dd, self.dd)
p2 = show_resp("Resp W", self.minidiag.ww, self.ww)
#Calculate points as mean between the two sets of answers
p = (p1+p2)/2
if p < 0.5: col = 12 #red
elif p < 0.8: col = 14 #yellow
else: col=10 #green
hilite('-- %.2f -- %s' % (p, '*' * int(p*20)), col)
return p
class Tester:
def __init__(self, db):
self.db = db
def init_session(self):
""" Init a testing session """
# Clear the screen (no peeking :))
print '\n' * 30
hilite('*** New session ***')
self.tests = []
self.seen_ids = []
def random_test(self):
""" Administer a random test """
while True:
md = self.db.random_all()
if not md.id in self.seen_ids:
break
self.seen_ids.append(md.id)
self._administer(md)
def id_test(self, id):
""" Administer a test based on id """
md = self.db.get_test(id)
self._administer(md)
def _administer(self, md):
tr = Test(md)
tr.administer()
self.tests.append(tr)
def results(self):
""" Print the results of the test """
hilite('*** Test results ***')
for i,t in enumerate(self.tests):
hilite('* Result %d of %d *' % (i+1, len(self.tests)))
t.show()
class Settings:
def __init__(self):
self.randseed = 20
def save(self):
f = open('db.dat', 'wb')
pickle.dump(self.randseed, f)
f.close()
def load(self):
try:
f = open('db.dat', 'rb')
self.randseed = pickle.load(f)
f.close()
except:
pass
def main():
parser = OptionParser()
parser.add_option("-r", "--randomize", dest="rand_seed", type="int", help="seed for randomizer")
parser.add_option("-k", "--key", dest="id", type="int", help="show a specific question based on its current number")
parser.add_option("-n", "--number", dest="number", type="int", default=1, help="number of tests to administer (default 1)")
parser.add_option("-i", "--info", dest="show_info", action='store_true', default=False, help="show DB info and exit")
parser.add_option("-v", "--verbose", dest="verbose", action='store_true', default=False, help="increase output verbosity")
parser.add_option("-c", "--continue", dest="cont", action='store_true', default=False, help="inc last saved number as rand seed")
parser.add_option("-s", "--same", dest="same", action='store_true', default=False, help="use last saved number as rand seed")
parser.add_option("", "--nocolor", dest="nocolor", action='store_true', default=False, help="don't use console coloring")
global opts
(opts, args) = parser.parse_args()
if opts.rand_seed:
#Use provided random seed
rs = int(opts.rand_seed)
s = Settings()
s.randseed = rs
s.save()
random.seed(rs)
elif opts.same or opts.cont:
#Use saved random seed
s = Settings()
s.load()
#If continuing we get the next random seed
if opts.cont:
s.randseed += 1
s.save()
opts.rand_seed = s.randseed
random.seed(s.randseed)
db = DB()
# If needed show DB info and exit
if opts.show_info:
for s in db.sections:
hilite('%3d - %3d: %s' % (s.diags[0].id, s.diags[-1].id, s.name))
if opts.verbose:
print s.kh
hilite('-------')
print s.kpe
hilite('-------')
return
tester = Tester(db)
tester.init_session()
hilite('Random seed: %d' % s.randseed, 3)
if opts.id:
tester.id_test(opts.id)
else:
for n in xrange(opts.number):
hilite('* Test %d of %d *' % (n+1, opts.number))
tester.random_test()
tester.results()
if __name__ == '__main__':
main()