-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathBlackboardQuiz.py
executable file
·1302 lines (1097 loc) · 68.1 KB
/
BlackboardQuiz.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 python3
import itertools
import os
import random
import re
import time
import uuid
import zipfile
from io import BytesIO, StringIO
from xml.sax.saxutils import escape, unescape
import lxml.html as html
import scipy.stats
import sympy
from lxml import etree
from PIL import Image
def roundSF(val, sf):
return float('{:.{p}g}'.format(val, p=sf))
def regexSF(val, sf):
#This is not really functional. It will match floats but not with rounding restrictions!
#Match the start of the string and any initial whitespace
regex="^[ ]*"
#Match the sign of the variable
if val < 0:
regex = regex +'-' #negative is required
else:
regex = regex +'\+?' #plus is optional
#Round the figure to the required S.F.
val = str(roundSF(abs(val), sf))
didx=val.find('.')
if didx == -1:
didx = len(val)
if val[0]=='0':
regex += re.search('(0\.[0]*[0-9]{0,'+str(sf)+'})', val).group(0) + "[0-9]*[ ]*"
elif didx>=sf:
regex += val[:sf]+"[0-9]{"+str(didx-sf)+'}(.|($|[ ]+))'
else:
regex += val[:sf+1].replace('.', r'\.')
return regex
import subprocess
dn = os.path.dirname(os.path.realpath(__file__))
def render_latex(formula, display, *args, **kwargs):
"""Renders LaTeX expression to bitmap image data.
"""
# Set a default math environment to have amsmath
if 'preamble' not in kwargs:
kwargs['preamble'] = r"""\documentclass[varwidth]{standalone}
\usepackage{amsmath,amsfonts}
\begin{document}"""
try:
if display:
sympy.preview(r'\begin{align*}'+formula.strip()+r'\end{align*}', viewer='file', filename="out.png", euler=False, *args, **kwargs)
else:
sympy.preview('$'+formula+'$', viewer='file', filename="out.png", euler=False, *args, **kwargs)
except Exception as e:
print('ERROR: Failed rendering latex "'+formula.strip()+'"')
raise e
with open('out.png', 'rb') as f:
data = f.read()
im = Image.open(BytesIO(data))
width, height = im.size
del im
return data, width, height
class BlackBoardObject:
def setup_html(self, title):
self.htmlfile_head = "<html><head><style>li.correct {list-style-type:none; background-color: #e6ffcc;}\n li.incorrect{list-style-type:none; background-color:#ffcccc} li.correct:before{content:'\\2713\\0020'; color: darkgreen}\n li.incorrect:before{content:'\\2718\\0020'; color: red}\n li::marker { vertical-align: top; } .pool {border: 1px solid black; padding: 0.5em}\n .pool ul li {border-bottom:1px solid black; padding: 0.5em} </style></head><body>"
self.htmlfile_head += '<h1>'+title+'</h1><ol class="mainlist">'
self.htmlfile = ""
self.htmlfile_tail = '</ol></body></html>'
def material(self, node, text):
material = etree.SubElement(node, 'material')
mat_extension = etree.SubElement(material, 'mat_extension')
mat_formattedtext = etree.SubElement(mat_extension, 'mat_formattedtext', {'type':'HTML'})
mat_formattedtext.text = text
def metadata(self, node, name='Assessment', typename='Pool', qtype='Multiple Choice', scoremax=0, weight=0, sectiontype='Subsection', instructor_notes='', partialcredit='false'):
md = etree.SubElement(node, name.lower()+'metadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', name),
('bbmd_assessmenttype', typename),
('bbmd_sectiontype', sectiontype),
('bbmd_questiontype', qtype),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', partialcredit),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', str(scoremax)),
('qmd_weighting', str(weight)),
('qmd_instructornotes', instructor_notes),
]:
etree.SubElement(md, key).text = val
class Pool(BlackBoardObject):
def __init__(self, pool_name, package, description="Created by BlackboardQuiz!", instructions="", preview=False, test=None, points_per_q=10, questions_per_test=1):
"""Initialises a question pool
"""
self.package = package
self.pool_name = pool_name
self.preview = preview
self.question_counter = 0
self.test = test
self.points_per_q = points_per_q
self.questions_per_test = questions_per_test
#Create the question data file
self.questestinterop = etree.Element("questestinterop")
assessment = etree.SubElement(self.questestinterop, 'assessment', {'title':self.pool_name})
self.metadata(assessment, 'Assessment', 'Pool', weight=0)
rubric = etree.SubElement(assessment, 'rubric', {'view':'All'})
flow_mat = etree.SubElement(rubric, 'flow_mat', {'class':'Block'})
self.material(flow_mat, instructions)
presentation_material = etree.SubElement(assessment, 'presentation_material')
flow_mat = etree.SubElement(presentation_material, 'flow_mat', {'class':'Block'})
self.material(flow_mat, description)
self.section = etree.SubElement(assessment, 'section')
self.metadata(self.section, 'Section', 'Pool', weight=0)
self.setup_html('Pool:' + pool_name)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
if self.preview:
self.package.zf.writestr(self.pool_name+'_preview.html', self.htmlfile_head + self.htmlfile + self.htmlfile_tail)
ref = self.package.embed_resource(self.pool_name, "assessment/x-bb-qti-pool", '<?xml version="1.0" encoding="UTF-8"?>\n'+etree.tostring(self.questestinterop, pretty_print=False).decode('utf-8'))
if self.test is not None:
self.test.add_pool(self, ref)
def addNumQ(self, title, text, answer, errfrac=None, erramt=None, errlow=None, errhigh=None, positive_feedback="Good work", negative_feedback="That's not correct"):
if errfrac is None and erramt is None and (errlow is None or errhigh is None):
raise Exception("Numerical questions require an error amount, fraction, or bounds")
if errfrac != None:
#Min max are required here as some questions may have negative answers
errlow = min(answer * (1-errfrac), answer * (1+errfrac))
errhigh = max(answer * (1-errfrac), answer * (1+errfrac))
if erramt != None:
errlow = answer - abs(erramt)
errhigh = answer + abs(erramt)
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
self.metadata(item, 'Item', 'Pool', qtype='Numeric', scoremax=-1.0, weight=0)
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_num = etree.SubElement(flow2, 'response_num', {'ident':'response', 'rcardinality':'Single', 'rtiming':'No'})
etree.SubElement(response_num, 'render_fib', {'charset':'us-ascii', 'encoding':'UTF_8', 'rows':'0', 'columns':'0', 'maxchars':'0', 'prompt':'Box', 'fibtype':'Decimal', 'minnumber':'0', 'maxnumber':'0'})
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':uuid.uuid4().hex})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'vargte', {'respident':'response'}).text = repr(errlow)
etree.SubElement(conditionvar, 'varlte', {'respident':'response'}).text = repr(errhigh)
etree.SubElement(conditionvar, 'varequal', {'respident':'response', 'case':'No'}).text = repr(answer)
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
self.htmlfile += '<li class="correct"><b>'+repr(errlow)+' ≤ Answer ≤ '+repr(errhigh)+'</b>:'+html_pos_feedback_text+'</li>'
self.htmlfile += '<li class="incorrect"><b>Else</b>:'+html_neg_feedback_text+'</li>'
self.htmlfile += '</ul></li>'
print("Added NumQ "+repr(title))
def addMCQ(self, title, text, answers, correct=0, positive_feedback="Good work", negative_feedback="That's not correct", shuffle_ans=True):
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Multiple Choice'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', 'false'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '10.000000000000000'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_lid = etree.SubElement(flow2, 'response_lid', {'ident':'response', 'rcardinality':'Single', 'rtiming':'No'})
render_choice = etree.SubElement(response_lid, 'render_choice', {'shuffle':'Yes' if shuffle_ans else 'No', 'minnumber':'0', 'maxnumber':'0'})
a_uuids = []
for idx,text in enumerate(answers):
flow_label = etree.SubElement(render_choice, 'flow_label', {'class':'Block'})
a_uuids.append(uuid.uuid4().hex)
response_label = etree.SubElement(flow_label, 'response_label', {'ident':a_uuids[-1], 'shuffle':'Yes', 'rarea':'Ellipse', 'rrange':'Exact'})
bb_answer_text, html_answer_text = self.package.process_string(text)
self.flow_mat1(response_label, bb_answer_text)
classname="incorrect"
if idx == correct:
classname="correct"
self.htmlfile += '<li class="'+classname+'">'+html_answer_text+'</li>'
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'varequal', {'respident':'response', 'case':'No'}).text = a_uuids[correct]
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
for idx, luuid in enumerate(a_uuids):
respcondition = etree.SubElement(resprocessing, 'respcondition')
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'varequal', {'respident':luuid, 'case':'No'})
if idx == correct:
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '100'
else:
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':luuid, 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
for idx, luuid in enumerate(a_uuids):
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':luuid, 'view':'All'})
solution = etree.SubElement(itemfeedback, 'solution', {'view':'All', 'feedbackstyle':'Complete'})
solutionmaterial = etree.SubElement(solution, 'solutionmaterial')
self.flow_mat2(solutionmaterial, '')
self.htmlfile += '</ul>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added MCQ "+repr(title))
def addMAQ(self, title, text, answers, correct=[0], positive_feedback="Good work", negative_feedback="That's not correct", shuffle_ans=True, weights=None):
# BH: added this
# correct -> a list with the indices of the correct solutions
# weights -> optional argument for specifying partial marks
# Set sensible default weights if not specified
if weights is None:
na = len(answers)
nc = len(correct)
wc = +100/nc
wi = -100/(na-nc) if na != nc else 0
weights = [(wc if i in correct else wi) for i in range(na)]
else:
assert len(weights)==len(answers)
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Multiple Answer'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'Q'), # 'Q' allows negative within the question, but not in the final grade?
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', 'true'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'\n<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_lid = etree.SubElement(flow2, 'response_lid', {'ident':'response', 'rcardinality':'Multiple', 'rtiming':'No'})
render_choice = etree.SubElement(response_lid, 'render_choice', {'shuffle':'Yes' if shuffle_ans else 'No', 'minnumber':'0', 'maxnumber':'0'})
a_uuids = []
for idx,text in enumerate(answers):
flow_label = etree.SubElement(render_choice, 'flow_label', {'class':'Block'})
a_uuids.append(uuid.uuid4().hex)
response_label = etree.SubElement(flow_label, 'response_label', {'ident':a_uuids[-1], 'shuffle':'Yes', 'rarea':'Ellipse', 'rrange':'Exact'})
bb_answer_text, html_answer_text = self.package.process_string(text)
self.flow_mat1(response_label, bb_answer_text)
classname = "correct" if idx in correct else "incorrect"
self.htmlfile += '\n<li class="'+classname+'">'+html_answer_text+'</li>\n'
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
and_ = etree.SubElement(conditionvar, 'and')
for i in range(len(answers)):
if i in correct:
etree.SubElement(and_, 'varequal', {'respident':'response', 'case':'No'}).text = a_uuids[i]
else:
not_ = etree.SubElement(and_, 'not')
etree.SubElement(not_, 'varequal', {'respident':'response', 'case':'No'}).text = a_uuids[i]
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
for idx, luuid in enumerate(a_uuids):
respcondition = etree.SubElement(resprocessing, 'respcondition')
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'varequal', {'respident':luuid, 'case':'No'})
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '{:.3f}'.format(weights[idx])
#etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':luuid, 'feedbacktype':'Response'}) # leave out
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
for idx, luuid in enumerate(a_uuids):
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':luuid, 'view':'All'})
solution = etree.SubElement(itemfeedback, 'solution', {'view':'All', 'feedbackstyle':'Complete'})
solutionmaterial = etree.SubElement(solution, 'solutionmaterial')
self.flow_mat2(solutionmaterial, '')
self.htmlfile += '\n</ul>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '\n<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '\n<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '\n</li>'
print("Added MAQ "+repr(title))
def addSRQ(self, title, text, answer='', positive_feedback="Good work", negative_feedback="That's not correct", rows=3, maxchars=0):
# BH: added this, need thorough testing...
# answers - an optional sample answer
# rows - number of lines/rows to provide for text entry
# maxchars - limit the number of characters (0 means no limit)
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Short Response'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', 'false'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_str = etree.SubElement(flow2, 'response_str', {'ident':'response', 'rcardinality':'Single', 'rtiming':'No'})
render_fib = etree.SubElement(response_str, 'render_fib', {'charset':'us-ascii', 'encoding':'UTF_8', 'rows':'{:d}'.format(rows), 'columns':'127', 'maxchars':'{:d}'.format(maxchars), 'prompt':'Box', 'fibtype':'String', 'minnumber':'0', 'maxnumber':'0'})
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'solution', 'view':'All'})
solution = etree.SubElement(itemfeedback, 'solution', {'view':'All', 'feedbackstyle':'Complete'})
solutionmaterial = etree.SubElement(solution, 'solutionmaterial')
flow = etree.SubElement(solutionmaterial, 'flow_mat', {'class':'Block'})
bb_answer_text, html_answer_text = self.package.process_string(answer)
self.material(flow,bb_answer_text)
self.htmlfile += '<li class="correct">Sample answer: '+html_answer_text+'</li>'
self.htmlfile += '</ul>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added SRQ "+repr(title)) ## changed
def addTFQ(self, title, text, istrue=True, positive_feedback="Good work", negative_feedback="That's not correct"):
# BH: added this, need thorough testing...
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'True/False'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', 'false'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_lid = etree.SubElement(flow2, 'response_lid', {'ident':'response', 'rcardinality':'Single', 'rtiming':'No'})
render_choice = etree.SubElement(response_lid, 'render_choice', {'shuffle':'No', 'minnumber':'0', 'maxnumber':'0'})
flow_label = etree.SubElement(render_choice, 'flow_label', {'class':'Block'})
for response in ['true','false']:
response_label = etree.SubElement(flow_label, 'response_label', {'ident':response, 'shuffle':'Yes', 'rarea':'Ellipse', 'rrange':'Exact'})
flow_mat = etree.SubElement(response_label, 'flow_mat', {'class':'Block'})
material = etree.SubElement(flow_mat, 'material')
#mattext = etree.SubElement(material, 'mattext', {'charset':'us-ascii', 'texttype':'text/plain', 'xml:space':'default'}).text = response # 'xml:space' is an invalid attribute name, seems okay to omit though
mattext = etree.SubElement(material, 'mattext', {'charset':'us-ascii', 'texttype':'text/plain'}).text = response
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'varequal', {'respident':'response', 'case':'No'}).text = 'true' if istrue else 'false'
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
self.htmlfile += '<li class="correct">'+('True' if istrue else 'False')+'</li>'
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
self.htmlfile += '</ul>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added TFQ "+repr(title)) ## changed
def addOQ(self, title, text, answers, positive_feedback="Good work", negative_feedback="That's not correct", shuffle_inds=None):
# BH: added this, needs thorough testing...
# The provided order of answers is assumed to be the correct order.
# The display order will be shuffled here, unless shuffle_inds is specified.
# (shuffle_inds must be a permutation of the indices 0,1,...,len(answers)-1)
if shuffle_inds is None:
shuffle_inds = list(range(len(answers)))
random.shuffle(shuffle_inds) # in-place
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Ordering'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'letter_lower'), # other options may be desirable...
('bbmd_partialcredit', 'true'), # false may be preferable...
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ol>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
response_lid = etree.SubElement(flow2, 'response_lid', {'ident':'response', 'rcardinality':'Ordered', 'rtiming':'No'})
render_choice = etree.SubElement(response_lid, 'render_choice', {'shuffle':'No', 'minnumber':'0', 'maxnumber':'0'}) # can shuffle be changed to Yes?
a_uuids = [uuid.uuid4().hex for _ in range(len(answers))]
for idx in shuffle_inds:
flow_label = etree.SubElement(render_choice, 'flow_label', {'class':'Block'})
response_label = etree.SubElement(flow_label, 'response_label', {'ident':a_uuids[idx], 'shuffle':'Yes', 'rarea':'Ellipse', 'rrange':'Exact'})
bb_answer_text, html_answer_text = self.package.process_string(answers[idx])
self.flow_mat1(response_label, bb_answer_text)
self.htmlfile += '<li value='+str(idx+1)+'>'+html_answer_text+'</li>'
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
and_ = etree.SubElement(conditionvar, 'and')
for i in range(len(answers)):
etree.SubElement(and_, 'varequal', {'respident':'response', 'case':'No'}).text = a_uuids[i]
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
self.htmlfile += '</ol>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added OQ "+repr(title))
def addMQ(self, title, text, answer_pairs, unmatched=[], positive_feedback="Good work", negative_feedback="That's not correct", neg_weight=0):
# BH: added this, needs thorough testing... this is somewhat complex...
# TODO: consider how the question is displayed this in the html file
# neg_weight: can specify a penalty % for incorrect matches
pos_weight = 100/len(answer_pairs)
self.question_counter += 1
question_id = 'q'+str(self.question_counter)
#Add the question to the list of questions
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Matching'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'Q'), # negative allowed in question only
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'letter_upper'), # other options may be desirable...
('bbmd_partialcredit', 'true'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ol>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
a_uuids = []
sub_uuids = []
for idx,pair in enumerate(answer_pairs):
# need a uuid here (in place of 'response')
flow3 = etree.SubElement(flow2, 'flow', {'class':'Block'})
a_uuids.append(uuid.uuid4().hex)
response_lid = etree.SubElement(flow3, 'response_lid', {'ident':a_uuids[-1], 'rcardinality':'Single', 'rtiming':'No'})
render_choice = etree.SubElement(response_lid, 'render_choice', {'shuffle':'Yes', 'minnumber':'0', 'maxnumber':'0'})
flow_label = etree.SubElement(render_choice, 'flow_label', {'class':'Block'})
b_uuids = []
for _ in answer_pairs+unmatched:
b_uuids.append(uuid.uuid4().hex)
response_label = etree.SubElement(flow_label, 'response_label', {'ident':b_uuids[-1], 'shuffle':'Yes', 'rarea':'Ellipse', 'rrange':'Exact'})
sub_uuids.append(b_uuids)
bb_answer_text, html_answer_text = self.package.process_string(pair[0])
flow4 = etree.SubElement(flow3, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
self.material(flow4, bb_answer_text)
self.htmlfile += '<li value='+str(idx+1)+'>'+html_answer_text+'</li>'
bb_answer_text, html_answer_text = self.package.process_string(pair[1])
self.htmlfile += '<li class="correct">'+html_answer_text+'</li>'
flow2 = etree.SubElement(flow1, 'flow', {'class':'RIGHT_MATCH_BLOCK'})
for idx,pair in enumerate(answer_pairs):
bb_right_match_text, html_right_match_text = self.package.process_string(pair[1])
flow3 = etree.SubElement(flow2, 'flow', {'class':'Block'})
flow4 = etree.SubElement(flow3, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
self.material(flow4, bb_right_match_text)
for text in unmatched:
bb_right_match_text, html_right_match_text = self.package.process_string(text)
flow3 = etree.SubElement(flow2, 'flow', {'class':'Block'})
flow4 = etree.SubElement(flow3, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
self.material(flow4, bb_right_match_text)
self.htmlfile += '<li class="incorrect">'+html_right_match_text+'</li>'
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
for idx in range(len(answer_pairs)):
respcondition = etree.SubElement(resprocessing, 'respcondition')
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'varequal', {'respident':a_uuids[idx], 'case':'No'}).text = sub_uuids[idx][idx]
etree.SubElement(respcondition, 'setvar', {'PartialCreditPercent':'SCORE', 'action':'Set'}).text = '{:.2f}'.format(pos_weight)
etree.SubElement(respcondition, 'setvar', {'NegativeCreditPercent':'SCORE', 'action':'Set'}).text = '{:.2f}'.format(neg_weight)
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
# sample export had the above two lines repeated, probably redundant though
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
self.htmlfile += '</ol>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added MQ "+repr(title))
def addFITBQ(self, title, text, answers, positive_feedback="Good work", negative_feedback="That's not correct"):
"""Fill in the blank questions"""
item = etree.SubElement(self.section, 'item', {'title':title, 'maxattempts':'0'})
md = etree.SubElement(item, 'itemmetadata')
for key, val in [
('bbmd_asi_object_id', '_'+str(self.package.bbid())+'_1'),
('bbmd_asitype', 'Item'),
('bbmd_assessmenttype', 'Pool'),
('bbmd_sectiontype', 'Subsection'),
('bbmd_questiontype', 'Fill in the Blank Plus'),
('bbmd_is_from_cartridge', 'false'),
('bbmd_is_disabled', 'false'),
('bbmd_negative_points_ind', 'N'),
('bbmd_canvas_fullcrdt_ind', 'false'),
('bbmd_all_fullcredit_ind', 'false'),
('bbmd_numbertype', 'none'),
('bbmd_partialcredit', 'true'),
('bbmd_orientationtype', 'vertical'),
('bbmd_is_extracredit', 'false'),
('qmd_absolutescore_max', '-1.0'),
('qmd_weighting', '0'),
('qmd_instructornotes', ''),
]:
etree.SubElement(md, key).text = val
presentation = etree.SubElement(item, 'presentation')
flow1 = etree.SubElement(presentation, 'flow', {'class':'Block'})
flow2 = etree.SubElement(flow1, 'flow', {'class':'QUESTION_BLOCK'})
flow3 = etree.SubElement(flow2, 'flow', {'class':'FORMATTED_TEXT_BLOCK'})
bb_question_text, html_question_text = self.package.process_string(text)
self.htmlfile += '<li>'+html_question_text+'<ul>'
self.material(flow3, bb_question_text)
flow2 = etree.SubElement(flow1, 'flow', {'class':'RESPONSE_BLOCK'})
for ans_key in answers:
response_str = etree.SubElement(flow2, 'response_str', {'ident':ans_key, 'rcardinality':'Single', 'rtiming':'No'})
render_fib = etree.SubElement(response_str, 'render_choice', {'charset':'us-ascii', "columns":"0", 'encoding':'UTF_8', 'fibtype':'String', 'maxchars':'0', 'maxnumber':'0', 'minnumber':'0', 'prompt':'Box', 'rows':'0'})
resprocessing = etree.SubElement(item, 'resprocessing', {'scoremodel':'SumOfScores'})
outcomes = etree.SubElement(resprocessing, 'outcomes', {})
decvar = etree.SubElement(outcomes, 'decvar', {'varname':'SCORE', 'vartype':'Decimal', 'defaultval':'0', 'minvalue':'0'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'correct'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
and_tag = etree.SubElement(conditionvar, 'and')
for ans_key, regex_exprs in answers.items():
or_tag = etree.SubElement(and_tag, 'or')
for regex in regex_exprs:
etree.SubElement(or_tag, 'varsubset', {'respident':ans_key, 'setmatch':'Matches'}).text = regex
self.htmlfile += '<li class="correct">'+regex+'</li>'
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = 'SCORE.max'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'correct', 'feedbacktype':'Response'})
respcondition = etree.SubElement(resprocessing, 'respcondition', {'title':'incorrect'})
conditionvar = etree.SubElement(respcondition, 'conditionvar')
etree.SubElement(conditionvar, 'other')
etree.SubElement(respcondition, 'setvar', {'variablename':'SCORE', 'action':'Set'}).text = '0'
etree.SubElement(respcondition, 'displayfeedback', {'linkrefid':'incorrect', 'feedbacktype':'Response'})
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'correct', 'view':'All'})
bb_pos_feedback_text, html_pos_feedback_text = self.package.process_string(positive_feedback)
self.flow_mat2(itemfeedback, bb_pos_feedback_text)
itemfeedback = etree.SubElement(item, 'itemfeedback', {'ident':'incorrect', 'view':'All'})
bb_neg_feedback_text, html_neg_feedback_text = self.package.process_string(negative_feedback)
self.flow_mat2(itemfeedback, bb_neg_feedback_text)
self.htmlfile += '</ul>'
if len(positive_feedback)+len(negative_feedback)>0:
self.htmlfile += '<div>+:'+html_pos_feedback_text+'</div>'
self.htmlfile += '<div>-:'+html_neg_feedback_text+'</div>'
self.htmlfile += '</li>'
print("Added FITBQ "+repr(title))
def addCalcNumQ(self, title, text, xs, count, calc,
errfrac=None, erramt=None, errlow=None, errhigh=None,
positive_feedback="Good work", negative_feedback="That's not correct",
validation=None,
):
if validation is not None:
import copy
result = calc(copy.deepcopy(validation))
divisor = validation['answer'] if validation['answer'] != 0 else 1
err = abs((result['answer'] - validation['answer']) / divisor)
if err > 1e-3:
raise RuntimeError(f"Validation failed for question {title}\n result:{result}\n validation:{validation}\n")
#This fancy loop goes over all permutations of the variables in xs
i = 0
while True:
if i >= count:
break;
x = {}
# Calculate all random variables
for xk in xs:
if hasattr(xs[xk][0], 'rvs'):
x[xk] = roundSF(xs[xk][0].rvs(1)[0], xs[xk][1]) #round to given S.F.
elif isinstance(xs[xk][0], list):
x[xk] = random.choice(xs[xk][0]) #Random choice from list
else:
raise RuntimeError("Unrecognised distribution/list for the question")
# Run the calculation
x = calc(x)
if x is None:
continue
if 'erramt' in x:
erramt = x['erramt']
i += 1
t = text
pos = positive_feedback
neg = negative_feedback
for var, val in x.items():
if isinstance(val, sympy.Basic):
t = t.replace('['+var+']', sympy.latex(val))
pos = pos.replace('['+var+']', sympy.latex(val))
neg = neg.replace('['+var+']', sympy.latex(val))
else:
t = t.replace('['+var+']', str(val))
pos = pos.replace('['+var+']', str(val))
neg = neg.replace('['+var+']', str(val))
self.addNumQ(title=title, text=t, answer=x['answer'], errfrac=errfrac, erramt=erramt, errlow=errlow, errhigh=errhigh, positive_feedback=pos, negative_feedback=neg)
def flow_mat2(self, node, text):
flow = etree.SubElement(node, 'flow_mat', {'class':'Block'})
self.flow_mat1(flow, text)
def flow_mat1(self, node, text):
flow = etree.SubElement(node, 'flow_mat', {'class':'FORMATTED_TEXT_BLOCK'})
self.material(flow, text)
class Test(BlackBoardObject):
def __init__(self, test_name, package, description="Created by BlackboardQuiz!", instructions="", preview=True):
"""Initialises a question pool
"""
self.package = package
self.test_name = test_name
self.preview = preview
self.question_counter = 0
#Create the question data file
self.questestinterop = etree.Element("questestinterop")
assessment = etree.SubElement(self.questestinterop, 'assessment', {'title':self.test_name})
self.metadata(assessment, 'Assessment', 'Test', scoremax='20.000', partialcredit='')
rubric = etree.SubElement(assessment, 'rubric', {'view':'All'})
flow_mat = etree.SubElement(rubric, 'flow_mat', {'class':'Block'})
self.material(flow_mat, instructions)
presentation_material = etree.SubElement(assessment, 'presentation_material')
flow_mat = etree.SubElement(presentation_material, 'flow_mat', {'class':'Block'})
self.material(flow_mat, description)
self.section = etree.SubElement(assessment, 'section')
self.metadata(self.section, 'Section', 'Test', scoremax=20)
#Create the HTML file for preview
self.setup_html('Test: '+test_name)
self.htmlfile += '<p>Tests are composed of questions drawn from pools. Below are the pools from which questions are drawn.</p>'
self.htmlfile_example = ""
self.htmlfile_example_marks = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
if self.preview:
self.package.zf.writestr(self.test_name+'_preview.html', self.htmlfile_head + self.htmlfile + self.htmlfile_tail)
self.package.zf.writestr(
self.test_name+'_example_preview.html',
self.htmlfile_head
+ self.htmlfile_example
+ '</li><p><b>[Total test marks '+str(self.htmlfile_example_marks)+']</b></p><ul>'
+ self.htmlfile_tail)
self.package.embed_resource(self.test_name, "assessment/x-bb-qti-test", '<?xml version="1.0" encoding="UTF-8"?>\n'+etree.tostring(self.questestinterop, pretty_print=False).decode('utf-8'))
def add_pool(self, pool, pool_ref):
subsec = etree.SubElement(self.section, 'section')
self.metadata(subsec, 'Section', 'Test', sectiontype='Random Block', scoremax=pool.questions_per_test * pool.points_per_q, weight=pool.points_per_q)
selection_ordering = etree.SubElement(subsec, 'selection_ordering')
selection = etree.SubElement(selection_ordering, 'selection', {'seltype':'All'})
etree.SubElement(selection, 'selection_number', {}).text = str(pool.questions_per_test)
etree.SubElement(selection, 'sourcebank_ref', ).text = pool_ref
self.htmlfile += '<div class="pool">'
self.htmlfile += '<h2>'+pool.pool_name+'</h2>'
self.htmlfile += '<p> Students will be presented with '+str(pool.questions_per_test)+' questions selected randomly from the pool below.</p>'
self.htmlfile += '<p> Each question is worth '+str(pool.points_per_q)+' marks.</p>'
self.htmlfile += '<ul>'
self.htmlfile += pool.htmlfile
self.htmlfile += '</ul>'