-
Notifications
You must be signed in to change notification settings - Fork 0
/
itemal.py
executable file
·1858 lines (1599 loc) · 85.9 KB
/
itemal.py
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# ITEM anALysis program
# Examination Services
#
# Changelog:
#
# 1966-04 WALTER DICK
# 1967-10-31 R. KOHR: REVISED FORTRAN IV VERSION
# 1968-01-26
# 1968-01-31 CHANGED STANDARD FORMAT
# 1968-02-05
# 1968-02-08 CORRECTIONS IN AVG. DIFFICULTY COMPUTATIONS
# 1968-02-24 ALLOWS 3-DIGIT SCORE FOR EACH OPT AVG
# 1970-01-12 R. KOHR: ADDED SUBROUTINE CONTRL
# 1985-08-09 R.S. SACHER: CONVERTED TO IBM VSFORTRAN
# 2022-03-05 J.T. FREY: CONVERTED TO PYTHON
#
import sys
import os
import errno
import re
import datetime
import functools
import argparse
import math
##
####
##
#
# File formats recognized by the program:
#
inputFormatsRecognized = {
'fortran': lambda *args, **kwargs:FortranIO(*args, **kwargs),
'json': lambda *args, **kwargs:JSONIO(*args, **kwargs),
'json+pretty': lambda *args, **kwargs:JSONIO(*args, shouldPrintPretty=True, **kwargs)
}
outputFormatsRecognized = {
'fortran': lambda *args, **kwargs:FortranIO(*args, **kwargs),
'json': lambda *args, **kwargs:JSONIO(*args, **kwargs),
'json+pretty': lambda *args, **kwargs:JSONIO(*args, shouldPrintPretty=True, **kwargs)
}
##
####
##
try:
stringTypes = (basestring)
except:
stringTypes = (str)
##
####
##
try:
import dateparser
def genericDateParse(dateString):
"""Wrapper around the dateparser.parse() function if that module is present in this Python instance."""
return dateparser.parse(dateString)
except:
def genericDateParse(dateString):
"""Attempt to parse a date given a set of expected formats for strptime(). Used if the dateparser module is not present in this Python instance."""
for dateFormat in [ '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d', '%m%d%y', '%x' ]:
try:
return datetime.datetime.strptime(dateString, dateFormat)
except:
pass
raise ValueError('Unable to parse "{:s}" with any known date-time format.'.format(dateString))
##
####
##
#
# To determine "is equal" for floating-point types, we need a function that calculates
# distance from zero -- anything within the given tolerance equates with equals.
#
# Python3 has a isclose() function in the math module. If it's there, we alias isclose
# to that function. If it's not present, we define our own isclose() function.
#
try:
math.isclose(1.0, 1.0)
isclose = math.isclose
except:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""Determine if a is within the given tolerance of b."""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
##
####
##
class SparseStorage(object):
"""The SparseStorage class implements a sparse multi-dimensional array. The array starts as an empty list. As data are added, the lists are filled-in to the necessary depth in each accessed dimension. When data are read, any set of indices not leading to a set value produce a default return value, not an error. This makes the multi-dimensional array essentially unbounded. While the Fortran ITEMAL code is written to limit to 5 groups and 160 questions, the statistical data class uses SparseStorage and is thus not bound to any specific maximum dimensionality."""
_allocIdx = 0
@classmethod
def allocIdx(cls):
cls._allocIdx += 1
return cls._allocIdx
def __init__(self, rank, fillInValue=0):
if rank < 1:
raise ValueError('Invalid SparseStorage rank {:d}'.format(rank))
self._storage = []
self._rank = rank
self._maxDimension = []
self._allocIdx = SparseStorage.allocIdx()
self._fillInValue = fillInValue
def __getitem__(self, key):
"""Allow the convenience of bracket notation for getting the value at a key. The key must be an list/tuple of the same dimension as the receiver's rank."""
return self.valueAtIndex(key)
def __setitem__(self, key, newValue):
"""Allow the convenience of bracket notation for setting the value at a key. The key must be an list/tuple of the same dimension as the receiver's rank."""
return self.setValueAtIndex(key, newValue)
def maxDimension(self):
return self._maxDimension
def fillInValue(self):
"""Returns the fill-in value associated with unset regions of the receiver."""
return self._fillInValue
def setFillInValue(self, fillInValue=0):
"""Sets the fill-in value associated with unset regions of the receiver to fillInValue."""
self._fillInValue = fillInValue
def clearAllValues(self):
"""Reset the receiver to be completely empty of all set values."""
self._storage = []
self._maxDimension = []
def valueAtIndex(self, key):
"""Return the value at the given key in the receiver. The key must be an list/tuple of the same dimension as the receiver's rank (an IndexError exception will be thrown otherwise). If the key is not set in the receiver, its fill-in value is returned."""
if len(key) != self._rank:
raise IndexError('Indices of rank {:d} where {:d} expected'.format(len(key), self._rank))
outValue = self._fillInValue
focus = self._storage
try:
for idx in key:
focus = focus[idx]
outValue = focus
except:
pass
return outValue
def setValueAtIndex(self, key, newValue=0):
"""Sets the value at the given key in the receiver to newValue. The key must be an list/tuple of the same dimension as the receiver's rank (an IndexError exception will be thrown otherwise). If the key is not set in the receiver, any intervening regions between the end of a list and the desired key will be filled with empty lists or the fill-in value (in the case of the final dimension)."""
if len(key) != self._rank:
raise IndexError('Indices of rank {:d} where {:d} expected'.format(len(key), self._rank))
dimIdx = 0
focus = self._storage
for idx in key[:-1]:
# Add a dimension?
if dimIdx >= len(self._maxDimension):
self._maxDimension.append(0)
if idx >= len(focus):
addEmptyLists = idx - len(focus) + 1
if idx + 1 > self._maxDimension[dimIdx]:
self._maxDimension[dimIdx] = idx + 1
for dummy in range(addEmptyLists):
focus.append([])
focus = focus[idx]
dimIdx += 1
idx = key[-1]
if idx >= len(focus):
if dimIdx >= len(self._maxDimension):
self._maxDimension.append(0)
addEmptyItems = idx - len(focus) + 1
if idx + 1 > self._maxDimension[dimIdx]:
self._maxDimension[dimIdx] = idx + 1
for dummy in range(addEmptyItems):
focus.append(self._fillInValue)
focus[idx] = newValue
def addValueAtIndex(self, key, deltaValue):
"""Convenience method that fetches the value at the given key, adds deltaValue to it, and sets the value at that key to the sum."""
self.setValueAtIndex(key, self.valueAtIndex(key) + deltaValue)
def scaleValueAtIndex(self, key, multiplier):
"""Convenience method that fetches the value at the given key, multiplies by multiplier, and sets the value at that key to the product."""
self.setValueAtIndex(key, self.valueAtIndex(key) * multiplier)
##
####
##
class ITEMALData(object):
"""This is an abstract base class for the ITEMAL in-memory data representation class hierarchy."""
def exportAsDict(self):
"""Package the object as a dictionary."""
return {}
##
####
##
class Options(ITEMALData):
"""An Options object (possibly) holds values for the optional attributes that can be associated with an Exam or ExamSection."""
def exportAsDict(self):
"""Add an 'options' key to the base export dictionary with any option attributes for the receiver."""
d = ITEMALData.exportAsDict(self)
d.update(self._values)
return d
#
# To add new attributes, simply augment this dictionary with the key and default value:
#
defaultValues = {
'is-order-reversed': False,
'number-of-copies': 1,
'should-eval-full-exam-only': False
}
def __init__(self, fromDict=None):
self._values = {}
if fromDict is not None:
src = fromDict._values if isinstance(fromDict, Options) else fromDict
for k in self.defaultValues:
if k in src:
self._values[k] = src[k]
def __repr__(self):
outStr = 'Options('
appended = False
for k in self.defaultValues:
if k in self._values:
outStr += ('{' if not appended else ',') + "'" + k + "':" + repr(self._values[k])
appended = True
return outStr + ('})' if appended else ')')
#
# Sequence magic methods are defined for read access to string-keyed option values:
#
def __iter__(self):
return self.defaultValues.__iter__()
def __len__(self):
return len(self.defaultValues)
def __getitem__(self, key):
return self._values.get(key, self.defaultValues[key])
def mergeWithOptions(self, otherOptions):
"""Any attributes with an assigned value in otherOptions are set to those values in the receiver."""
self._values.update(otherOptions._values)
def mergeWithOptionsDict(self, optionsDict):
"""Any attributes with a value in optionsDict are set to those values in the receiver."""
self._values.update(optionsDict)
##
####
##
class StudentAnswers(ITEMALData):
"""A StudentAnswers object holds the answer key, per-student scores, and per-student answer list. Each ExamSection will have zero or more instances of this class -- one for each group of students.
Scores can be provided on initialization from the dictionary, but can also be calculated if supplied with the answer key for the questions."""
def exportAsDict(self):
"""Add the receiver's fields to the export dict."""
d = ITEMALData.exportAsDict(self)
d.update({
'scores': self.scores(),
'answers': self.answers(),
'group-id': self.groupId(),
})
return d
lastGroupId = 0
@classmethod
def nextGroupId(cls):
cls.lastGroupId += 1
return str(cls.lastGroupId)
def __init__(self, fromDict=None):
self._scores = []
self._answers = []
if fromDict is not None:
self._groupId = str(fromDict['group-id']) if ('group-id' in fromDict) else StudentAnswers.nextGroupId()
if 'scores' in fromDict:
self._scores = [int(s) for s in fromDict['scores']]
if 'answers' in fromDict:
firstAnswers = None
for answers in fromDict['answers']:
theseAnswers = [int(a) for a in answers]
if firstAnswers is None:
firstAnswers = theseAnswers
elif len(theseAnswers) != len(firstAnswers):
raise ValueError('Answer set of dimension {:d} does not match first answers dimension {:d} for group {:s}.'.format(len(theseAnswers), len(firstAnswers), self._groupId))
self._answers.append(theseAnswers)
else:
self._groupId = StudentAnswers.nextGroupId()
def groupId(self):
return self._groupId
def setGroupId(self, groupId):
self._groupId = str(groupId)
def scores(self):
return self._scores
def answers(self):
return self._answers
def maxResponseCount(self):
return max([max([a for a in A]) for A in self._answers])
def answerCount(self):
return len(self._answers[0]) if (len(self._answers) > 0) else 0
def studentCount(self):
return len(self._answers)
def reset(self, groupId=None):
self._scores = []
self._answers = []
def appendStudentData(self, score, answers):
if len(self._answers) > 0 and len(answers) != len(self._answers[0]):
raise ValueError('Attempt to append student answers of mismatched dimension ({:d} vs {:d}).'.format(len(answers), len(self._answers)))
self._answers.append([int(a) for a in answers])
self._scores.append(int(score))
def calculateScoresForAnswerKey(self, answerKey):
if len(self._answers) > 0:
if len(answerKey) != len(self._answers[0]):
raise ValueError('Attempt to calculation scores from answer key of invalid dimension {:d}.'.format(len(answerKey)))
self._scores = [
functools.reduce(lambda a, b: a + b, [0 if (a != b) else 1 for (a, b) in zip(A, answerKey)])
for A in self._answers
]
def reverseAnswerOrdering(self, responsesPerAnswer):
if len(self._answers) > 0:
self._answers = [((responsesPerAnswer + 1 - i) if i else 0) for i in self._answers]
##
####
##
class ExamSection(ITEMALData):
def exportAsDict(self):
"""Add the receiver's fields to the export dict."""
d = ITEMALData.exportAsDict(self)
d.update({
'responses-per-question': self.responsesPerQuestion(),
'options': self.options().exportAsDict(),
'answer-key': self.answerKey(),
'responses': [A.exportAsDict() for A in self.studentAnswersGroups()]
})
statsData = self.statisticalSummary()
if statsData is not None:
d['statistics'] = statsData
return d
def __init__(self, fromDict=None, parentOptions=None):
self._responsesPerQuestion = 0
self._answerKey = []
self._studentAnswersGroups = []
self._options = Options(parentOptions)
self._fortranFormatString = None
self._fortranNewPageBadges = []
self._statisticalSummary = None
if fromDict is not None:
if 'responses-per-question' in fromDict:
self.setResponsesPerQuestion(int(fromDict['responses-per-question']))
if 'options' in fromDict:
self._options.mergeWithOptionsDict(fromDict['options'])
if 'answer-key' in fromDict:
self.setAnswerKey(fromDict['answer-key'])
if 'responses' in fromDict:
firstAnswers = None
for fromDict in fromDict['responses']:
self.addStudentAnswers(StudentAnswers(fromDict=fromDict))
else:
self._options = Options()
#
# Sequence magic methods are defined for read access to answers groups list:
#
def __len__(self):
return len(self._studentAnswersGroups)
def __getitem__(self, key):
if isinstance(key, stringTypes):
return self.studentAnswersForGroupId(key)
return self._studentAnswersGroups[key]
def options(self):
return self._options
def setOptions(self, options):
self._options = Options(options)
def responsesPerQuestion(self):
return self._responsesPerQuestion
def setResponsesPerQuestion(self, responsesPerQuestion):
if len(self._answerKey) > 0:
if max(self._answerKey) > responsesPerQuestion:
raise ValueError('Attempt to set responsesPerQuestion={:d} which is < maximum response in the answer key {:d}.'.format(responsesPerQuestion, max(self._answerKey)))
self._responsesPerQuestion = responsesPerQuestion
def answerKey(self):
return self._answerKey
def questionCount(self):
return len(self._answerKey)
def setAnswerKey(self, answerKey):
if len(answerKey) > 0:
if len(self._studentAnswersGroups) > 0:
firstAnswers = self._studentAnswersGroups[0]
if len(answerKey) != firstAnswers.answerCount():
raise ValueError('Answer key answer count {:d} differs from group {:s} count {:d}.'.format(theseAnswers.groupId(), firstAnswers.groupId()))
answerKey = [int(a) for a in answerKey]
if self._responsesPerQuestion == 0:
self._responsesPerQuestion = max(answerKey)
elif self._responsesPerQuestion > 0 and max(answerKey) > self._responsesPerQuestion:
raise ValueError('Items in answer key {:s} exceed configured maximum response count {:d}.'.format(''.join(answerKey), self._responsesPerQuestion))
self._answerKey = answerKey
self._fortranNewPageBadges = [False]*len(answerKey)
def studentCount(self):
return [g.studentCount() for g in self._studentAnswersGroups]
def totalStudentCount(self):
return functools.reduce(lambda a, b: a + b, self.studentCount())
def studentAnswersGroups(self):
return self._studentAnswersGroups
def studentAnswersGroupsCount(self):
return len(self._studentAnswersGroups)
def studentAnswersGroupAtIndex(self, groupIndex):
return self._studentAnswersGroups[groupIndex]
def studentAnswersGroupIds(self):
return [g.groupId() for g in self._studentAnswersGroups]
def studentAnswersForGroupId(self, groupId):
ids = self.studentAnswersGroupIds()
return self._studentAnswersGroups[ids.index(groupId)] if (groupId in ids) else None
def setStudentAnswersGroups(self, studentAnswersGroups):
self._studentAnswersGroups = []
for studentAnswers in studentAnswersGroups:
self.addStudentAnswers(studentAnswers)
def addStudentAnswers(self, studentAnswers):
if studentAnswers.groupId() in self._studentAnswersGroups:
raise KeyError('Group {:s} already exists in exam section.'.format(studentAnswers.groupId()))
if studentAnswers.answerCount() > 0:
# Does this incoming answers' dimension(s) match the extant answers groups?
if len(self._studentAnswersGroups) > 0:
# We'll examine the first element that's already been validated:
otherAnswers = self._studentAnswersGroups[0]
# Matching number of answers in both?
if studentAnswers.answerCount() != otherAnswers.answerCount():
raise ValueError('Attempt to add answer group with dimension {:d} to exam with existing groups of dimension {:d}.'.format(studentAnswers.answerCount(), otherAnswers.answerCount()))
# If a maximum number of responses per question is set, then we'll need to verify the
# new group of answers doesn't have any answer that exceeds that limit. But if our
# maximum is not yet set, we need to set it now to reflect the max of the new set:
if self._responsesPerQuestion == 0 or self._responsesPerQuestion < studentAnswers.maxResponseCount():
self._responsesPerQuestion = studentAnswers.maxResponseCount()
self._studentAnswersGroups.append(studentAnswers)
def fortranFormatString(self):
return self._fortranFormatString
def setFortranFormatString(self, formatString):
self._fortranFormatString = formatString
def fortranNewPageBadges(self):
return self._fortranNewPageBadges
def setFortranNewPageBadge(self, questionIndex, newPageState=True):
self._fortranNewPageBadges[questionIndex] = newPageState
def statisticalSummary(self):
return self._statisticalSummary
def setStatisticalSummary(self, statisticalSummary):
self._statisticalSummary = statisticalSummary
def reverseAnswerOrderingIfNecessary(self):
if self.options()['is-order-reversed']:
responsesPerQuestion = self.responsesPerQuestion()
if responsesPerQuestion <= 0:
raise RuntimeError('Unable to reorder answer indices since maximum response index per question is {:d}.'.format(responsesPerQuestion))
if len(self._answerKey) > 0:
self.setAnswerKey([(responsesPerQuestion + 1 - i) for i in responsesPerQuestion])
for studentAnswerGroup in self.studentAnswerGroups():
studentAnswerGroup.reverseAnswerOrdering(responsesPerQuestion)
def calculateScoresFromAnswerKey(self):
if len(self._answerKey) == 0:
raise RuntimeError('Exam section lacks an answer key from which to calculate student scores.')
for studentAnswers in self._studentAnswersGroups:
studentAnswers.calculateScoresForAnswerKey(self._answerKey)
##
####
##
class Exam(ITEMALData):
answerSymbolByIndex = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def exportAsDict(self):
"""Add the receiver's fields to the export dict."""
d = ITEMALData.exportAsDict(self)
d.update({
'exam-id': self.examId(),
'course-name': self.courseName(),
'instructor': self.instructor(),
'options': self.options().exportAsDict(),
'exam-date': self.examDate(),
'exam-sections': [S.exportAsDict() for S in self.examSections()]
})
statsData = self.statisticalSummary()
if statsData is not None:
d['statistics'] = statsData
return d
lastExamId = 0
@classmethod
def nextExamId(cls):
cls.lastExamId += 1
return str(cls.lastExamId)
def __init__(self, fromDict=None):
self._courseName = ''
self._instructor = ''
self._examDate = datetime.datetime.fromtimestamp(0)
self._examSections = []
self._statisticalSummary = None
self._options = Options()
if fromDict is not None:
self._examId = str(fromDict['exam-id']) if ('exam-id' in fromDict) else Exam.nextExamId()
self._courseName = fromDict.get('course-name', self._courseName)
self._instructor = fromDict.get('instructor', self._instructor)
if 'options' in fromDict:
self._options.mergeWithOptionsDict(fromDict['options'])
if 'exam-date' in fromDict:
if isinstance(fromDict['exam-date'], stringTypes):
self._examDate = genericDateParse(fromDict['exam-date'])
else:
self._examDate = fromDict['exam-date']
if 'exam-sections' in fromDict:
for sectionDict in fromDict['exam-sections']:
self.addExamSection(ExamSection(fromDict=sectionDict, parentOptions=self._options))
else:
self._examId = Exam.nextExamId()
#
# Sequence magic methods are defined for read access to examSections list:
#
def __len__(self):
return len(self._examSections)
def __getitem__(self, key):
return self._examSections[key]
def examId(self):
return self._examId
def setExamId(self, examId):
self._examId = str(examId)
def courseName(self):
return self._courseName
def setCourseName(self, courseName):
self._courseName = str(courseName)
def instructor(self):
return self._instructor
def setInstructor(self, instructor):
self._instructor = str(instructor)
def examDate(self):
return self._examDate
def setExamDate(self, examDate):
self._examDate = examDate
def totalQuestionCount(self):
return functools.reduce(lambda a, b: a + b.questionCount(), self._examSections, 0)
def examSections(self):
return self._examSections
def examSectionCount(self):
return len(self._examSections)
def examSectionAtIndex(self, sectionIndex):
return self._examSections[sectionIndex]
def setExamSections(self, examSections):
self._examSections = []
for examSection in examSections:
self.addExamSection(examSection)
def addExamSection(self, examSection):
if len(self._examSections) > 0:
# Student counts (in a by-group list) must be the same across exam sections:
if examSection.studentCount() != self._examSections[0].studentCount():
raise ValueError('Attempt to add exam section with {:s} students to exam with existing sections containing {:s} students.'.format(str(examSection.studentCount()), str(self._examSections[0].studentCount())))
# Groups should have the same ids:
if len(set(examSection.studentAnswersGroupIds()).symmetric_difference(self._examSections[0].studentAnswersGroupIds())) > 0:
raise ValueError('Attempt to add exam section with different group ids than existing sections.')
# Hand our options to the new exam section:
examSection.options().mergeWithOptions(self._options)
self._examSections.append(examSection)
def statisticalSummary(self):
return self._statisticalSummary
def setStatisticalSummary(self, statisticalSummary):
self._statisticalSummary = statisticalSummary
def options(self):
return self._options
def setOptions(self, options):
self._options = Options(options)
for examSection in self._examSections:
examSection.options().mergeWithOptions(self._options)
def calculateScoresFromAnswerKeys(self):
for examSection in self._examSections:
examSection.calculateScoresFromAnswerKey()
def totalStudentCount(self):
return self._examSections[0].totalStudentCount() if (len(self._examSections) > 0) else None
def reverseAnswerOrderingIfNecessary(self):
for examSection in self._examSections:
examSection.reverseAnswerOrderingIfNecessary()
##
####
##
class StatData(object):
"""Class that wraps all of the common blocks and data processing present in the original Fortran code."""
CHEK = [ 0.2, 0.2, 0.1, 0.07, 0.05, 0.04, 0.04, 0.04, 0.04 ]
def __init__(self):
"""Initialization of the statistical data object fields' that only change across input files."""
self.NNXYZ = 0
self.GITEMN = 0.0
self.VAR = 0.0
self.SBIS = 0.0
self.SDI = 0.0
self.IDO = 0
self.IDTW = 0
self.IDTH = 0
self.IDFO = 0
self.IDFI = 0
self.IDVP = 0
self.IDG = 0
self.IDP = 0
self.IDVG = 0
self.IDVVG = 0
self.IDEX = 0
self.CNTKEY = SparseStorage(rank=1, fillInValue=0.0)
self.PROSUM = SparseStorage(rank=1, fillInValue=0.0)
self.CNTCHO = SparseStorage(rank=1, fillInValue=0.0)
self.FKSUM = SparseStorage(rank=2, fillInValue=0.0)
self.CMEAN = SparseStorage(rank=2, fillInValue=0.0)
self.PROP = SparseStorage(rank=2, fillInValue=0.0)
self.TOT = SparseStorage(rank=2, fillInValue=0.0)
self.AVDIFF = SparseStorage(rank=1, fillInValue=0.0)
self.BIS = SparseStorage(rank=1, fillInValue=0.0)
self.DIFI = SparseStorage(rank=1, fillInValue=0.0)
self.FCOUNT = SparseStorage(rank=1, fillInValue=0.0)
self.FITC = SparseStorage(rank=1, fillInValue = 0.0)
self.FITIC = SparseStorage(rank=1, fillInValue = 0.0)
self.PBIS = SparseStorage(rank=1, fillInValue=0.0)
self.PCTCHO = SparseStorage(rank=1, fillInValue=0.0)
self.PCTKEY = SparseStorage(rank=1, fillInValue=0.0)
self.Q = SparseStorage(rank=1, fillInValue=0.0)
self.QCOUNT = SparseStorage(rank=1, fillInValue=0.0)
self.T = SparseStorage(rank=1, fillInValue=0.0)
self.Y = SparseStorage(rank=1, fillInValue=0.0)
self._messages = []
def processExamSection(self, exam, examSection):
"""Initialize statistical data object fields that get reset before student data are processed."""
# Stuff from the Fortran header:
self.KODE = 0 if exam.options()['should-eval-full-exam-only'] else 1
self.ICHO = examSection.responsesPerQuestion()
self.IDIG = 2 if examSection.options()['is-order-reversed'] else 1
self.NCOPY = examSection.options()['number-of-copies']
self.ITN = examSection.totalStudentCount()
self.FITN = float(self.ITN)
self.ITEMN = examSection.questionCount()
self.FITEMN = float(self.ITEMN)
self.GITEMN += self.FITEMN
# Initialize the rest of the per-section variables:
self.ISUMSQ = 0
self.ISUM = 0
self.SER = 0.0
self.SDEV = 0.0
self.ITAB = SparseStorage(rank=3, fillInValue=0)
self.KSUM = SparseStorage(rank=2, fillInValue=0)
self.JTOT = SparseStorage(rank=2, fillInValue=0)
self.IDIST = SparseStorage(rank=2, fillInValue=0)
self.KOUNT = SparseStorage(rank=1, fillInValue=0)
self.ICOUNT = SparseStorage(rank=1, fillInValue=0)
self.IBI = SparseStorage(rank=1, fillInValue=0)
self.IDI = SparseStorage(rank=1, fillInValue=0)
self.ITC = SparseStorage(rank=1, fillInValue=0)
self.FMNCO = SparseStorage(rank=1, fillInValue=0.0)
self.FMNIC = SparseStorage(rank=1, fillInValue=0.0)
self.ITIC = SparseStorage(rank=1, fillInValue=0)
self.KTOT = SparseStorage(rank=1, fillInValue=0)
self.JCHO = self.ICHO + 1
# Tally all student answers in the section:
answerKey = examSection.answerKey()
l = 0
while l < examSection.studentAnswersGroupsCount():
answerGroup = examSection.studentAnswersGroupAtIndex(l)
l += 1
scores = answerGroup.scores()
answers = answerGroup.answers()
self.KOUNT[[l]] += answerGroup.studentCount()
self.ISUM += functools.reduce(lambda a, b: a + b, scores, 0)
self.ISUMSQ += functools.reduce(lambda a, b: a + b**2, scores, 0)
a = 0
while a < len(answers):
studentAnswers = answers[a]
score = scores[a]
a += 1
i = 0
while i < len(answerKey):
if answerKey[i] == studentAnswers[i]:
self.ICOUNT[[i + 1]] += 1
self.ITC[[i + 1]] += score
else:
self.ITIC[[i + 1]] += score
if studentAnswers[i] < 0:
# 270 FORMAT (1H0,24HA RESPONSE FOR QUESTION ,I2,1X,10HFOR GROUP ,I1,1X,
# 116HREAD AS NEGATIVE)
self._messages.append('A RESPONSE FOR QUESTION {:2d} FOR GROUP {:1d} READ AS NEGATIVE'.format(i + 1, l))
continue
elif studentAnswers[i] > self.ICHO:
# 290 FORMAT (1H0,24HA RESPONSE FOR QUESTION ,I2,1X,10HFOR GROUP ,I1,1X,
# 121HREAD AS GREATER THAN ,I1)
self._messages.append('A RESPONSE FOR QUESTION {:2d} FOR GROUP {:1d} READ AS GREATER THAN {:1d}'.format(i + 1, l, self.ICHO))
continue
else:
j = studentAnswers[i] + 1
self.ITAB[[i + 1, j, l]] += 1
self.JTOT[[i + 1, j]] += 1
self.KSUM[[i + 1, j]] += score
i += 1
# Calculate statistical summary for the section:
for i in range(1, self.ITEMN + 1):
for j in range(1, self.JCHO + 1):
self.KTOT[[i]] += self.JTOT[[i, j]]
self.TOT[[i, j]] = self.JTOT[[i, j]]
self.FKSUM[[i, j]] = float(self.KSUM[[i, j]])
self.CMEAN[[i, j]] = 0.0 if (self.TOT[[i, j]] <= 0) else (float(self.FKSUM[[i, j]]) / float(self.TOT[[i, j]]))
self.PROP[[i, j]] = float(self.TOT[[i, j]]) / float(self.FITN)
self.FCOUNT[[i]] = float(self.ICOUNT[[i]])
self.DIFI[[i]] = self.FCOUNT[[i]] / float(self.FITN)
if self.DIFI[[i]] <= 0.19:
self.IDO += 1
elif self.DIFI[[i]] <= 0.39:
self.IDTW += 1
elif self.DIFI[[i]] <= 0.59:
self.IDTH += 1
elif self.DIFI[[i]] <= 0.79:
self.IDFO += 1
elif self.DIFI[[i]] <= 1.0:
self.IDFI += 1
else:
# '0DIFFICULTY OF ITEM', I2,' IS GREATER THAN ONE OR LESS THAN ZERO.'
#outputFPtr.write('0DIFFICULTY OF ITEM{:2d} IS GREATER THAN ONE OR LESS THAN ZERO.'.format(i))
self._messages.append('0DIFFICULTY OF ITEM{:2d} IS GREATER THAN ONE OR LESS THAN ZERO.'.format(i))
if self.KODE < 1:
for i in range(1, self.ITEMN + 1):
if self.DIFI[[i]] > 0.40 and self.DIFI[[i]] <= 0.61:
self.IDI[[i]] = 5
elif self.DIFI[[i]] > 0.30 and self.DIFI[[i]] <= 0.71:
self.IDI[[i]] = 4
elif self.DIFI[[i]] > 0.20 and self.DIFI[[i]] <= 0.81:
self.IDI[[i]] = 3
elif self.DIFI[[i]] > 0.10 and self.DIFI[[i]] <= 0.91:
self.IDI[[i]] = 2
else:
self.IDI[[i]] = 1
self.FSUM = float(self.ISUM)
self.FSUMSQ = float(self.ISUMSQ)
self.FMEAN = self.FSUM / self.FITN
self.FVAR = (self.FITN * self.FSUMSQ - self.FSUM**2) / (self.FITN * (self.FITN - 1.0))
self.SER = 1.0 / math.sqrt(self.FITN - 1.0)
self.SDEV = math.sqrt(self.FVAR)
for i in range(1, self.ITEMN + 1):
for j in range(1, self.JCHO + 1):
self.IDIST[[i, j]] = 2 if self.PROP[[i, j]] < self.CHEK[self.ICHO] else 1
k = answerKey[i - 1] + 1
self.IDIST[[i, k]] = 2 if (self.PROP[[i, k]] < 0.2 or self.PROP[[i, k]] > 0.8) else 1
for j in range(1, self.JCHO + 1):
if self.IDIST[[i, j]] != 2:
if self.CMEAN[[i, j]] > self.CMEAN[[i, k]] or self.CMEAN[[i, k]] < self.FMEAN:
self.IDIST[[i, j]] = 2
for i in range(1, self.ITEMN + 1):
if self.DIFI[[i]] < 0.0:
self.doLine570(i)
elif isclose(self.DIFI[[i]], 0.0):
self.FMNCO[[i]] = 0.0
self.FMNIC[[i]] = self.FMEAN
self.doLine570(i)
elif isclose(self.DIFI[[i]], 1.0):
self.FMNCO[[i]] = self.FMEAN
self.FMNIC[[i]] = 0.0
self.doLine570(i)
else:
if self.DIFI[[i]] < 0.5:
if self.DIFI[[i]] <= 0:
self.doLine620(i)
else:
self.doLine610(i, 1.0 - self.DIFI[[i]])
elif self.DIFI[[i]] > 0.5:
if self.DIFI[[i]] > 1.0:
self.doLine620(i)
else:
self.doLine610(i, self.DIFI[[i]])
else:
self.Y[[i]] = 0.39894
self.doLine620(i)
self.NNXYZ += self.ITEMN
for i in range(1, self.ITEMN + 1):
KEY = answerKey[i - 1]
self.CNTKEY[[KEY]] += 1.0
self.PROSUM[[KEY]] += self.PROP[[i, KEY + 1]]
for j in range(2, self.JCHO + 1):
self.CNTCHO[[j - 1]] += self.TOT[[i, j]]
self.KTN = self.ITN
self.KCHO = self.ICHO
self.MCOPY = examSection.options()['number-of-copies']
# What do we cram back into the exam section as results?
L1 = 0
L2 = 1
JUP = self.NNXYZ
questionSummaries = []
for i in range(1, self.ITEMN + 1):
JUP += 1
KAN = answerKey[i - 1]
KOR = KAN + 1
if self.IDIG == 2:
KAN = self.JCHO - KAN
L1 += 1
L2 += 1
shouldInsertNewPage = False
if i <= 2:
shouldInsertNewPage = False
elif self.ICHO <= 5:
if L2 <= 3:
shouldInsertNewPage = False
else:
shouldInsertNewPage = True
L1 = 1
L2 = 1
elif L1 > 2:
shouldInsertNewPage = True
L1 = 1
L2 = 1
else:
shouldInsertNewPage = False
j = 1
perQuestionSummary = {
'should-insert-new-page': shouldInsertNewPage,
'omitted': {
'is-correct-answer': (KOR == j),
'index': 0,
'count-by-group': [self.ITAB[[i, j, L]] for L in range(1, examSection.studentAnswersGroupsCount() + 1)],
'total-responses': self.JTOT[[i, j]],
'chosen-by-ratio': self.PROP[[i, j]],
'mean-score': self.CMEAN[[i, j]],
'is-questionable': False
},
'total': {
'count-by-group': [self.KOUNT[[L]] for L in range(1, examSection.studentAnswersGroupsCount() + 1)],
'total-responses': self.KTOT[[i]]
},
'by-answer': {},
'biserial-correlation': self.BIS[[i]],
'pointwise-biserial-correlation': self.PBIS[[i]],
't-value': self.T[[i]]
}
JK = self.JCHO
for j in range(2, self.JCHO + 1):
if self.IDIG == 2:
JK -= 1
K = JK
else:
K = j - 1
IDIS = self.IDIST[[i, j]]
perQuestionSummary['by-answer'][Exam.answerSymbolByIndex[j - 1]] = {
'is-correct-answer': (KOR == j),
'index': K,
'count-by-group': [self.ITAB[[i, j, L]] for L in range(1, examSection.studentAnswersGroupsCount() + 1)],
'total-responses': self.JTOT[[i, j]],
'chosen-by-ratio': self.PROP[[i, j]],
'mean-score': self.CMEAN[[i, j]],
'is-questionable': True if (IDIS == 2) else False
}
questionSummaries.append(perQuestionSummary)
# Attach the summaries to the exam section:
examSection.setStatisticalSummary(questionSummaries)
def doLine570(self, i):
"""Corresponds to GO TO line 570 in the original Fortran code."""
self.BIS[[i]] = 0.0
self.PBIS[[i]] = 0.0
self.T[[i]] = 0.0
def doLine610(self, i, area):
"""Corresponds to GO TO line 610 in the original Fortran code."""
eta = math.sqrt(math.log(1.0 / area**2))
abcissa = eta - ((2.30753 + 0.27061 * eta) / (1.0 + 0.99229 * eta + 0.04481 * eta**2))
self.Y[[i]] = 0.3989422 * (1.0 / (2.7182818**(abcissa**2 / 2.0)))
self.doLine620(i)
def doLine620(self, i):
"""Corresponds to GO TO line 620 in the original Fortran code."""
self.FITC[[i]] = self.ITC[[i]]
self.FITIC[[i]] = self.ITIC[[i]]
self.FMNCO[[i]] = self.FITC[[i]] / self.FCOUNT[[i]]
self.QCOUNT[[i]] = self.FITN - self.FCOUNT[[i]]
self.FMNIC[[i]] = self.FITIC[[i]] / self.QCOUNT[[i]]
self.Q[[i]] = 1.0 - self.DIFI[[i]]
self.VAR = self.VAR + (self.DIFI[[i]] * self.Q[[i]])
if isclose(self.SDEV, 0.0):
self.doLine632(i)
else:
self.BIS[[i]] = ((self.FMNCO[[i]] - self.FMNIC[[i]]) / self.SDEV) * self.DIFI[[i]] * self.Q[[i]] / self.Y[[i]]
self.PBIS[[i]] = self.BIS[[i]] * (self.Y[[i]] / math.sqrt(self.DIFI[[i]] * self.Q[[i]]))
self.T[[i]] = self.PBIS[[i]] * math.sqrt((self.FITN - 2.0) / (1.0 - self.PBIS[[i]]**2))
self.doLine630(i)
def doLine630(self, i):
"""Corresponds to GO TO line 630 in the original Fortran code."""
if self.BIS[[i]] > 0.11:
self.doLine640(i)
else:
self.IDVP += 1
self.IBI[[i]] = 1
self.doLine690(i)
def doLine632(self, i):
"""Corresponds to GO TO line 632 in the original Fortran code."""
self.BIS[[i]] = 0.0
self.PBIS[[i]] = 0.0
self.T[[i]] = 0.0
self.doLine630(i)
def doLine640(self, i):
"""Corresponds to GO TO line 640 in the original Fortran code."""
if self.BIS[[i]] <= 0.31:
self.IDP += 1
self.IBI[[i]] = 2
elif self.BIS[[i]] <= 0.51:
self.IDG += 1
self.IBI[[i]] = 3
elif self.BIS[[i]] <= 0.71:
self.IDVG += 1
self.IBI[[i]] = 4
elif self.BIS[[i]] <= 0.91:
self.IDVVG += 1
self.IBI[[i]] = 5
else: