Download envs/class_test/gen.py from RenaissanceLabsEU/practice: direct link, hf CLI and curl.
- Browser
- Download file 33.9 kB
-
https://huggingface.co/datasets/RenaissanceLabsEU/practice/resolve/main/envs/class_test/gen.py
- Command line
-
hf download hf://datasets/RenaissanceLabsEU/practice/envs/class_test/gen.py
-
curl -L -o gen.py https://huggingface.co/datasets/RenaissanceLabsEU/practice/resolve/main/envs/class_test/gen.py
33.9 kB
| """Class Test (ISCED-F 0111 Education science: educational assessment). | |
| Four task families, all on synthetic classes (student ids only): | |
| marking mark multiple-choice answer sheets against a key: per-item marks, negative marking, | |
| withdrawn items, percentages and grades from grade boundaries | |
| item-analysis item facility, upper-lower discrimination index (27% groups), KR-20, point-biserial | |
| distractors option counts per item, non-functioning distractors, items where a distractor beats the key | |
| moderation rescale marks to a target mean and SD, per teaching group, and adjust markers after | |
| a moderation sample | |
| Methods and sources | |
| Facility (p value) = proportion correct. Discrimination index D = (U - L) / n with upper and lower | |
| groups of 27% of the class: Kelley, T. L. (1939). The selection of upper and lower groups for the | |
| validation of test items. J. Educ. Psychol. 30, 17-24. | |
| KR-20 = k/(k-1) * (1 - sum(p*q) / variance of totals), population variance: Kuder, G. F. & | |
| Richardson, M. W. (1937). The theory of the estimation of test reliability. Psychometrika 2, 151-160. | |
| Point-biserial r = (M1 - M0) / s * sqrt(p*q), s the population SD of the totals (equal to the Pearson | |
| correlation between the 0/1 item score and the total). | |
| A distractor chosen by under 5% of candidates is non-functioning: Haladyna, T. M. & Downing, S. M. | |
| (1993). How many options is enough for a multiple-choice test item? Educ. Psychol. Meas. 53, 999-1010. | |
| Linear rescaling to a target mean and SD: scaled = target mean + (x - mean) / SD * target SD. | |
| The flagging thresholds, grade boundaries and the marker-adjustment rule are stated in each task's | |
| notes file; they are conventions chosen for these tasks. | |
| """ | |
| import math | |
| from practice.core import Task, rng_for, to_csv, c_int, c_num, c_str, c_set, c_list, clear_of | |
| ENV = "class-test" | |
| def sid_list(r, n): return ["S%03d" % i for i in sorted(r.sample(range(1, 400), n))] | |
| # ---------------------------------------------------------------- marking | |
| def mark_sheet(resp, key, marks, penalty=0.0): | |
| """resp: one answer per item ('' = blank). key: the correct option per item, or 'VOID' for a withdrawn item. | |
| penalty: fraction of the item's marks lost for a wrong answer. Returns the total, never below 0.""" | |
| total = 0.0 | |
| for a, k, m in zip(resp, key, marks): | |
| if k == "VOID" or a == "": continue | |
| total += m if a == k else -penalty * m | |
| return max(0.0, total) | |
| def max_marks(key, marks): return sum(m for k, m in zip(key, marks) if k != "VOID") | |
| def grade_for(percent, bounds): | |
| """bounds: list of (grade, minimum percent), highest first. Below the last minimum the grade is U.""" | |
| for g, lo in bounds: | |
| if percent >= lo: return g | |
| return "U" | |
| def marking_scheme(d, bounds, penalty): | |
| L = ["# Marking scheme", "", "Each item has one correct option, given in `answer_key.csv` with the marks it carries.", "", | |
| "- A correct answer earns the item's marks."] | |
| if d == 1: | |
| L += ["- A wrong answer or an unanswered item (empty cell) earns 0."] | |
| else: | |
| L += ["- A wrong answer loses %s of the item's marks (negative marking)." % {0.25: "one quarter", 0.5: "one half"}[penalty], | |
| "- An unanswered item (empty cell) earns 0 and loses nothing.", | |
| "- If a student's total comes out below 0, it is recorded as 0."] | |
| if d >= 3: | |
| L += ["- A cell with more than one letter (for example `BD`) means the student marked more than one option: treat it as a wrong answer.", | |
| "- An item whose key is `VOID` has been withdrawn. It earns and loses nothing for anyone, and its marks are not part of the maximum."] | |
| L += ["", "The maximum is the sum of the marks of all items%s. The percentage is the student's total divided by the maximum, times 100." % (" that have not been withdrawn" if d >= 3 else ""), | |
| "", "## Grade boundaries", "", "The grade is decided on the exact percentage, before any rounding.", "", "| Grade | Percentage |", "|---|---|"] | |
| for g, lo in bounds: L.append("| %s | %d or more |" % (g, lo)) | |
| L.append("| U | under %d |" % bounds[-1][1]) | |
| return "\n".join(L) + "\n" | |
| def gen_marking(seed, d): | |
| r = rng_for(ENV + "/marking", seed, d) | |
| k, n = {1: (20, 6), 2: (24, 9), 3: (30, 10)}[d] | |
| penalty = 0.0 if d == 1 else r.choice([0.25, 0.5]) | |
| key = [r.choice("ABCD") for _ in range(k)] | |
| marks = [1] * k if d == 1 else [r.choice([1, 1, 2, 2, 3]) for _ in range(k)] | |
| if d >= 3: | |
| for j in r.sample(range(k), r.randint(1, 2)): key[j] = "VOID" | |
| bounds = [("A", r.choice([75, 80])), ("B", r.choice([60, 65])), ("C", r.choice([50, 55])), ("D", r.choice([35, 40, 45]))] | |
| top = max_marks(key, marks) | |
| sids = sid_list(r, n) | |
| sheets, res = {}, {} | |
| for i, s in enumerate(sids): | |
| while True: | |
| p = r.choice([0.3, 0.45, 0.55, 0.65, 0.75, 0.85, 0.93]) if i else 0.15 # the first student mostly guesses | |
| resp = [] | |
| for j in range(k): | |
| right = key[j] if key[j] != "VOID" else r.choice("ABCD") | |
| u = r.random() | |
| if u < p: a = right | |
| elif u < p + (1 - p) * (0.15 if d == 1 else 0.3): a = "" | |
| else: a = r.choice([x for x in "ABCD" if x != right]) | |
| if d >= 3 and a and r.random() < 0.04: a = "".join(sorted(set([a, r.choice("ABCD")]) | set(r.choice("ABCD")))) | |
| resp.append(a) | |
| total = mark_sheet(resp, key, marks, penalty) | |
| pct = 100.0 * total / top | |
| if clear_of(pct, [b for _, b in bounds], 0.5): break | |
| sheets[s] = resp; res[s] = (total, pct, grade_for(pct, bounds)) | |
| order = sids[:]; r.shuffle(order) | |
| rows = [] | |
| for s in order: | |
| row = {"student_id": s, "form": r.choice(["9A", "9B"])} | |
| for j in range(k): row["Q%d" % (j + 1)] = sheets[s][j] | |
| rows.append(row) | |
| krows = [{"item": "Q%d" % (j + 1), "key": key[j], "marks": marks[j]} for j in range(k)] | |
| checks = [c_int("max_marks", top)] | |
| for s in sids: | |
| total, pct, g = res[s] | |
| checks.append(c_int("students.%s.marks" % s, total) if d == 1 else c_num("students.%s.marks" % s, total, 2)) | |
| checks += [c_num("students.%s.percent" % s, pct, 1), c_str("students.%s.grade" % s, g)] | |
| checks.append(c_set("grade_u", [s for s in sids if res[s][2] == "U"], weight=2)) | |
| lines = ["- `max_marks`: the maximum total, an integer.", | |
| "- `students`: an object keyed by student id. Each value has", | |
| " - `marks`: the student's total, %s." % ("an integer" if d == 1 else "2 decimals"), | |
| " - `percent`: the percentage, 1 decimal.", | |
| " - `grade`: one of `A`, `B`, `C`, `D`, `U`.", | |
| "- `grade_u`: list of the student ids with grade `U` (any order; an empty list if none)."] | |
| if d >= 3: | |
| for g in "ABCDU": checks.append(c_int("grade_counts.%s" % g, sum(1 for s in sids if res[s][2] == g))) | |
| checks.append(c_num("mean_percent", sum(res[s][1] for s in sids) / n, 1)) | |
| lines += ["- `grade_counts`: an object with the keys `A`, `B`, `C`, `D`, `U`, each the number of students with that grade (0 if none).", | |
| "- `mean_percent`: the mean of the students' unrounded percentages, 1 decimal."] | |
| inst = """# Class test: marking | |
| `answer_sheets.csv` holds the answer sheets of %d students for a %d-item multiple-choice test. `answer_key.csv` gives the key and the marks for each item. `marking_scheme.md` gives the marking rules and the grade boundaries: follow it exactly. | |
| Write `answer.json` in this folder, a JSON object with: | |
| %s | |
| Numbers are accepted within one unit of the last decimal place asked for. | |
| """ % (n, k, "\n".join(lines)) | |
| files = {"answer_sheets.csv": to_csv(rows, ["student_id", "form"] + ["Q%d" % (j + 1) for j in range(k)]), | |
| "answer_key.csv": to_csv(krows, ["item", "key", "marks"]), "marking_scheme.md": marking_scheme(d, bounds, penalty)} | |
| return Task(ENV, "marking", seed, d, "Mark a %d-item test for %d students" % (k, n), inst, files, checks, {"students": n, "items": k}) | |
| # ---------------------------------------------------------------- item analysis | |
| def facility(matrix, j): | |
| return sum(row[j] for row in matrix) / float(len(matrix)) | |
| def group_size(n): | |
| """27% of the class, rounded to the nearest whole number (half up).""" | |
| return int(math.floor(0.27 * n + 0.5)) | |
| def ranked(ids, matrix): | |
| """Indices of the students, highest total first; equal totals in ascending order of student id.""" | |
| return sorted(range(len(ids)), key=lambda i: (-sum(matrix[i]), ids[i])) | |
| def discrimination(ids, matrix, j): | |
| g = group_size(len(ids)); order = ranked(ids, matrix) | |
| up = sum(matrix[i][j] for i in order[:g]); low = sum(matrix[i][j] for i in order[-g:]) | |
| return (up - low) / float(g) | |
| def var_p(xs): | |
| """Population variance (N in the denominator).""" | |
| m = sum(xs) / float(len(xs)) | |
| return sum((x - m) ** 2 for x in xs) / float(len(xs)) | |
| def kr20(matrix): | |
| k = len(matrix[0]) | |
| pq = sum(facility(matrix, j) * (1 - facility(matrix, j)) for j in range(k)) | |
| return k / (k - 1.0) * (1.0 - pq / var_p([sum(row) for row in matrix])) | |
| def point_biserial(matrix, j): | |
| tot = [sum(row) for row in matrix] | |
| one = [t for t, row in zip(tot, matrix) if row[j] == 1]; zero = [t for t, row in zip(tot, matrix) if row[j] == 0] | |
| p = len(one) / float(len(matrix)) | |
| return (sum(one) / float(len(one)) - sum(zero) / float(len(zero))) / math.sqrt(var_p(tot)) * math.sqrt(p * (1 - p)) | |
| def item_notes(d): | |
| t = """# Item analysis: definitions | |
| A student's item score is 1 if the answer is correct and 0 otherwise%s. A student's total is the sum of the item scores. `N` is the number of students%s. | |
| ## Facility | |
| The facility of an item is the proportion of the `N` students who got it right. | |
| ## Discrimination index | |
| 1. Put the students in order of total, highest first. Students with the same total are ordered by student id, ascending (`S012` before `S105`). | |
| 2. The group size `n_group` is 27%% of `N`, rounded to the nearest whole number (round half up). | |
| 3. The upper group is the first `n_group` students in that order and the lower group is the last `n_group` students. | |
| 4. Discrimination = (number in the upper group who got the item right - number in the lower group who got it right) / `n_group`. | |
| An item has poor discrimination if its discrimination index is below 0.20. | |
| """ % ("" if d == 1 else " (an empty cell is an unanswered item and counts as wrong)", "" if d < 3 else " who sat the test. Rows with status `absent` are not part of the analysis") | |
| if d >= 2: | |
| t += """ | |
| ## Easy and hard items | |
| An item is too easy if its facility is above 0.85 and too hard if its facility is below 0.30. | |
| ## KR-20 reliability | |
| With `k` items, facility `p_j` for item `j`, and `var` the variance of the students' totals computed with `N` in the denominator (population variance): | |
| KR-20 = k / (k - 1) * (1 - sum over items of p_j * (1 - p_j) / var) | |
| (the sum is taken first, then divided by `var`). | |
| """ | |
| if d >= 3: | |
| t += """ | |
| ## Point-biserial correlation | |
| For an item with facility `p`, let `M1` be the mean total of the students who got it right, `M0` the mean total of the students who got it wrong, and `s` the standard deviation of all `N` totals (square root of the population variance above). The total includes the item itself. | |
| r_pb = (M1 - M0) / s * sqrt(p * (1 - p)) | |
| An item needs review if its point-biserial is below 0.20. | |
| """ | |
| return t | |
| def gen_items(seed, d): | |
| r = rng_for(ENV + "/item-analysis", seed, d) | |
| k = {1: 8, 2: 10, 3: 10}[d] | |
| while True: | |
| n = r.randint(18, 26) if d == 1 else r.randint(30, 45) | |
| if abs((0.27 * n) % 1 - 0.5) > 0.1: break | |
| ids = sid_list(r, n) | |
| while True: | |
| b = [r.uniform(-1.2, 1.2) for _ in range(k)]; a = [r.uniform(0.8, 2.0) for _ in range(k)] | |
| special = r.sample(range(k), 3) | |
| b[special[0]] = -2.6 # an easy item | |
| if d >= 2: b[special[1]] = 2.2 # a hard item | |
| a[special[2]] = r.choice([0.0, 0.1, -0.5]) # an item that does not discriminate | |
| matrix = [] | |
| for _ in ids: | |
| th = r.gauss(0, 1) | |
| matrix.append([1 if r.random() < 1.0 / (1.0 + math.exp(-a[j] * (th - b[j]))) else 0 for j in range(k)]) | |
| fac = [facility(matrix, j) for j in range(k)] | |
| if not all(0 < f < 1 and clear_of(f, [0.30, 0.85], 0.012) for f in fac): continue | |
| dis = [discrimination(ids, matrix, j) for j in range(k)] | |
| if not all(clear_of(x, [0.20], 0.02) for x in dis): continue | |
| if var_p([sum(row) for row in matrix]) < 1.0: continue | |
| pb = [point_biserial(matrix, j) for j in range(k)] | |
| if d >= 3 and not all(clear_of(x, [0.20], 0.02) for x in pb): continue | |
| if not any(x < 0.20 for x in dis): continue | |
| break | |
| items = ["Q%d" % (j + 1) for j in range(k)] | |
| files = {"item_analysis_notes.md": item_notes(d)} | |
| if d == 1: | |
| rows = [dict([("student_id", s)] + list(zip(items, matrix[i]))) for i, s in enumerate(ids)] | |
| r.shuffle(rows) | |
| files["scores.csv"] = to_csv(rows, ["student_id"] + items) | |
| else: | |
| key = [r.choice("ABCD") for _ in range(k)] | |
| rows = [] | |
| for i, s in enumerate(ids): | |
| row = {"student_id": s, "class": r.choice(["8X", "8Y"]), "status": "present"} | |
| for j in range(k): | |
| row[items[j]] = key[j] if matrix[i][j] else ("" if r.random() < 0.08 else r.choice([x for x in "ABCD" if x != key[j]])) | |
| rows.append(row) | |
| if d >= 3: | |
| for s in ["S%03d" % x for x in r.sample(range(400, 500), r.randint(2, 4))]: | |
| row = {"student_id": s, "class": r.choice(["8X", "8Y"]), "status": "absent"} | |
| for q in items: row[q] = "" | |
| rows.append(row) | |
| r.shuffle(rows) | |
| files["responses.csv"] = to_csv(rows, ["student_id", "class"] + (["status"] if d >= 3 else []) + items) | |
| files["key.csv"] = to_csv([{"item": q, "key": key[j]} for j, q in enumerate(items)], ["item", "key"]) | |
| checks = [c_int("n_group", group_size(n))] | |
| for j, q in enumerate(items): | |
| checks += [c_num("items.%s.facility" % q, fac[j], 3), c_num("items.%s.discrimination" % q, dis[j], 3)] | |
| if d >= 3: checks.append(c_num("items.%s.point_biserial" % q, pb[j], 3)) | |
| checks.append(c_set("poor_discrimination", [q for j, q in enumerate(items) if dis[j] < 0.20], weight=2)) | |
| lines = ["- `n_group`: the size of the upper group (and of the lower group), an integer.", | |
| "- `items`: an object keyed by item (`Q1` to `Q%d`). Each value has" % k, | |
| " - `facility`: 3 decimals.", " - `discrimination`: the discrimination index, 3 decimals."] | |
| if d >= 3: lines.append(" - `point_biserial`: 3 decimals.") | |
| lines.append("- `poor_discrimination`: list of the items with poor discrimination (any order; an empty list if none).") | |
| if d >= 2: | |
| checks += [c_set("too_easy", [q for j, q in enumerate(items) if fac[j] > 0.85], weight=2), | |
| c_set("too_hard", [q for j, q in enumerate(items) if fac[j] < 0.30], weight=2), c_num("kr20", kr20(matrix), 3, weight=2)] | |
| lines += ["- `too_easy`: list of the items that are too easy (any order; an empty list if none).", | |
| "- `too_hard`: list of the items that are too hard (any order; an empty list if none).", | |
| "- `kr20`: the KR-20 reliability of the test, 3 decimals."] | |
| if d >= 3: | |
| checks += [c_int("n_students", n), c_set("needs_review", [q for j, q in enumerate(items) if pb[j] < 0.20], weight=2)] | |
| lines += ["- `n_students`: the number of students in the analysis, an integer.", | |
| "- `needs_review`: list of the items whose point-biserial is below 0.20 (any order; an empty list if none)."] | |
| src = "`scores.csv` holds the item scores (1 right, 0 wrong) of %d students on a %d-item test" % (n, k) if d == 1 else \ | |
| "`responses.csv` holds the options chosen by the students of two classes on a %d-item multiple-choice test, and `key.csv` the correct options" % k | |
| inst = """# Class test: item analysis | |
| %s. The rows are in no particular order. `item_analysis_notes.md` defines every statistic: follow it exactly.%s | |
| Write `answer.json` in this folder, a JSON object with: | |
| %s | |
| Numbers are accepted within one unit of the last decimal place asked for. | |
| """ % (src, " Analyse the two classes together as one group." if d >= 2 else "", "\n".join(lines)) | |
| return Task(ENV, "item-analysis", seed, d, "Item analysis of a %d-item test" % k, inst, files, checks, {"students": n, "items": k}) | |
| # ---------------------------------------------------------------- distractors | |
| def option_counts(responses, options): | |
| """responses: one string per student ('' = omitted). Returns the count for each option, in order.""" | |
| return [sum(1 for a in responses if a == o) for o in options] | |
| def non_functioning(counts, options, key, n): | |
| """Distractors chosen by under 5% of the n students.""" | |
| return [o for o, c in zip(options, counts) if o != key and 20 * c < n] | |
| def beaten(counts, options, key): | |
| kc = counts[options.index(key)] | |
| return any(c > kc for o, c in zip(options, counts) if o != key) | |
| def distractor_notes(d): | |
| t = """# Distractor analysis: definitions | |
| For each item, the key is the correct option and the other options are its distractors. `N` is the number of students who sat the test%s. | |
| - The count of an option is the number of students who chose it. | |
| - A distractor is non-functioning if it was chosen by under 5%% of the `N` students (count divided by `N` below 0.05). | |
| - A distractor beats the key if it was chosen by more students than the key was. | |
| """ % (" (an empty cell means the student left the item out; such students still count in `N`)" if d >= 2 else "") | |
| if d >= 3: | |
| t += "- Rows with status `absent` did not sit the test: they are not part of `N` or of any count.\n- Some items have five options (A to E); `key.csv` gives the number of options of each item.\n" | |
| return t | |
| def gen_distractors(seed, d): | |
| r = rng_for(ENV + "/distractors", seed, d) | |
| k = {1: 6, 2: 8, 3: 7}[d] | |
| while True: | |
| n = r.randint(32, 58) if d == 1 else r.randint(45, 95) | |
| if n % 20: break | |
| items = ["Q%d" % (j + 1) for j in range(k)] | |
| while True: | |
| spec, cols, ok = [], [], True | |
| for j in range(k): | |
| opts = "ABCDE" if (d >= 3 and r.random() < 0.4) else "ABCD" | |
| key = r.choice(opts) | |
| dist = [o for o in opts if o != key]; r.shuffle(dist) | |
| kind = r.choice(["normal", "normal", "dead", "dead", "beaten", "two-dead"]) | |
| w = {key: r.uniform(0.5, 0.75)} | |
| rest = [r.uniform(0.5, 1.5) for _ in dist] | |
| if kind in ("dead", "two-dead"): rest[0] = r.choice([0.0, 0.03, 0.06]) | |
| if kind == "two-dead": rest[1] = r.choice([0.0, 0.04]) | |
| if kind == "beaten": w[key] = r.uniform(0.2, 0.3); rest[0] = 3.5 | |
| for o, x in zip(dist, rest): w[o] = (1 - w[key]) * x / sum(rest) | |
| omit = 0.0 if d == 1 else r.choice([0.0, 0.03, 0.08]) | |
| col = [] | |
| for _ in range(n): | |
| u = r.random() | |
| if u < omit: col.append(""); continue | |
| u = r.random(); acc = 0.0; pick = opts[-1] | |
| for o in opts: | |
| acc += w[o] | |
| if u < acc: pick = o; break | |
| col.append(pick) | |
| cnt = option_counts(col, opts) | |
| dc = sorted([c for o, c in zip(opts, cnt) if o != key], reverse=True) | |
| if dc[0] == cnt[opts.index(key)] or (d >= 3 and dc[0] == dc[1]): ok = False | |
| spec.append((opts, key)); cols.append(col) | |
| if not ok: continue | |
| nf = [non_functioning(option_counts(cols[j], spec[j][0]), spec[j][0], spec[j][1], n) for j in range(k)] | |
| bt = [beaten(option_counts(cols[j], spec[j][0]), spec[j][0], spec[j][1]) for j in range(k)] | |
| if 1 <= sum(1 for x in nf if x) < k and 1 <= sum(bt) < k and (d == 1 or any("" in c for c in cols)): break | |
| ids = sid_list(r, n) | |
| rows = [] | |
| for i, s in enumerate(ids): | |
| row = {"student_id": s, "class": r.choice(["10P", "10Q", "10R"]), "status": "present"} | |
| for j, q in enumerate(items): row[q] = cols[j][i] | |
| rows.append(row) | |
| if d >= 3: | |
| for s in ["S%03d" % x for x in r.sample(range(400, 500), r.randint(2, 5))]: | |
| row = {"student_id": s, "class": r.choice(["10P", "10Q", "10R"]), "status": "absent"} | |
| for q in items: row[q] = "" | |
| rows.append(row) | |
| r.shuffle(rows) | |
| krows = [{"item": q, "key": spec[j][1], "n_options": len(spec[j][0])} for j, q in enumerate(items)] | |
| checks = [] | |
| for j, q in enumerate(items): | |
| opts, key = spec[j]; cnt = option_counts(cols[j], opts) | |
| checks += [c_list("items.%s.counts" % q, cnt, item="int"), c_set("items.%s.non_functioning" % q, nf[j])] | |
| if d >= 2: | |
| checks += [c_int("items.%s.omitted" % q, cols[j].count("")), c_num("items.%s.key_pct" % q, 100.0 * cnt[opts.index(key)] / n, 1)] | |
| if d >= 3: | |
| best = max((c, o) for o, c in zip(opts, cnt) if o != key)[1] | |
| checks.append(c_str("items.%s.top_distractor" % q, best)) | |
| checks += [c_set("has_non_functioning", [q for j, q in enumerate(items) if nf[j]], weight=2), | |
| c_set("key_beaten", [q for j, q in enumerate(items) if bt[j]], weight=2)] | |
| lines = ["- `items`: an object keyed by item (`Q1` to `Q%d`). Each value has" % k, | |
| " - `counts`: a list of integers, the count of each option in the order A, B, C, D%s." % (" (and E for a five-option item)" if d >= 3 else ""), | |
| " - `non_functioning`: a list of the option letters of the item's non-functioning distractors (any order; an empty list if none)."] | |
| if d >= 2: | |
| lines += [" - `omitted`: the number of students who left the item out, an integer.", | |
| " - `key_pct`: the percentage of the `N` students who chose the key, 1 decimal."] | |
| if d >= 3: lines.append(" - `top_distractor`: the letter of the distractor chosen by the most students.") | |
| lines += ["- `has_non_functioning`: list of the items that have at least one non-functioning distractor (any order).", | |
| "- `key_beaten`: list of the items where at least one distractor beats the key (any order)."] | |
| if d >= 3: | |
| checks.append(c_int("n_students", n)); lines.append("- `n_students`: `N`, an integer.") | |
| inst = """# Class test: distractor analysis | |
| `responses.csv` holds the option each student chose on each of the %d items of a multiple-choice test (three classes, rows in no particular order). `key.csv` gives the correct option of each item. `distractor_notes.md` gives the definitions: follow them exactly. Analyse all classes together. | |
| Write `answer.json` in this folder, a JSON object with: | |
| %s | |
| Numbers are accepted within one unit of the last decimal place asked for. | |
| """ % (k, "\n".join(lines)) | |
| files = {"responses.csv": to_csv(rows, ["student_id", "class"] + (["status"] if d >= 3 else []) + items), | |
| "key.csv": to_csv(krows, ["item", "key"] + (["n_options"] if d >= 3 else [])), "distractor_notes.md": distractor_notes(d)} | |
| return Task(ENV, "distractors", seed, d, "Distractor analysis of a %d-item test" % k, inst, files, checks, {"students": n, "items": k}) | |
| # ---------------------------------------------------------------- moderation | |
| def pmean(xs): return sum(xs) / float(len(xs)) | |
| def psd(xs): return math.sqrt(var_p(xs)) | |
| def rescale(x, mean, sd, target_mean, target_sd, top=None): | |
| """Linear rescaling; if `top` is given the result is limited to the range 0 to top.""" | |
| y = target_mean + (x - mean) / sd * target_sd | |
| if top is not None: y = min(float(top), max(0.0, y)) | |
| return y | |
| def marker_adjustment(pairs, tolerance): | |
| """pairs: (marker's mark, moderator's mark) for the sampled scripts of one marker. | |
| Returns (mean difference moderator - marker, amount added to all that marker's marks).""" | |
| diff = pmean([m - x for x, m in pairs]) | |
| return diff, (diff if abs(diff) > tolerance else 0.0) | |
| def moderation_notes(d, top, tm, ts, tol): | |
| t = """# Standardising marks | |
| The test is marked out of %d. | |
| ## Rescaling to a target mean and standard deviation | |
| The target mean is %d and the target standard deviation is %d. For a set of marks with mean `M` and standard deviation `SD`, a mark `x` becomes | |
| scaled = %d + (x - M) / SD * %d | |
| `SD` is the population standard deviation: the square root of the mean squared deviation from `M`, with the number of marks in the denominator (not one less). | |
| """ % (top, tm, ts, tm, ts) | |
| if d == 2: | |
| t += """ | |
| Each teaching group is rescaled separately, with its own `M` and `SD`. A student with no mark was absent and is left out of everything. | |
| A scaled mark above %d is set to %d, and a scaled mark below 0 is set to 0. | |
| """ % (top, top) | |
| if d >= 3: | |
| t += """ | |
| ## Step 1: moderation of markers | |
| A moderator has re-marked a sample of each marker's scripts (`moderation_sample.csv`). For each marker: | |
| 1. For each sampled script of that marker, take the moderator's mark minus the marker's mark. | |
| 2. The marker's mean difference is the mean of these differences. | |
| 3. If the mean difference is more than %.1f marks in either direction (above %.1f or below -%.1f), add the unrounded mean difference to **every** mark given by that marker, sampled or not. Otherwise leave that marker's marks as they are. | |
| Do not limit or round the marks at this step. The moderator's own marks are used only to work out the mean difference. | |
| ## Step 2: rescaling | |
| Take the marks of all students after step 1 as one set (all markers together), and rescale them to the target mean and standard deviation with the formula above. A scaled mark above %d is set to %d, and a scaled mark below 0 is set to 0. | |
| """ % (tol, tol, tol, top, top) | |
| return t | |
| def gen_moderation(seed, d): | |
| r = rng_for(ENV + "/moderation", seed, d) | |
| top = r.choice([50, 60, 80, 100]) | |
| tm, ts = int(round(top * r.choice([0.62, 0.65]))), int(round(top * r.choice([0.17, 0.19]))) | |
| tol = r.choice([1.5, 2.0, 2.5]) | |
| files, checks, lines = {}, [], [] | |
| def cluster(n, outlier): | |
| c = r.uniform(0.3, 0.5) * top; s = r.uniform(0.06, 0.1) * top | |
| xs = [int(min(top, max(0, round(r.gauss(c, s))))) for _ in range(n)] | |
| if outlier: xs[0] = int(min(top, round(c + 5.5 * s))) | |
| return xs | |
| def clamp_ok(v): return clear_of(v, [0, top], 0.3) | |
| if d == 1: | |
| n = 10; ids = sid_list(r, n) | |
| while True: | |
| xs = cluster(n, False) | |
| if psd(xs) > 0.05 * top and all(0 < rescale(x, pmean(xs), psd(xs), tm, ts) < top for x in xs): break | |
| rows = [{"student_id": s, "seat": r.randint(1, 30), "mark": x} for s, x in zip(ids, xs)] | |
| r.shuffle(rows) | |
| files["marks.csv"] = to_csv(rows, ["student_id", "seat", "mark"]) | |
| checks += [c_num("raw_mean", pmean(xs), 2), c_num("raw_sd", psd(xs), 2)] | |
| checks += [c_num("students.%s.scaled" % s, rescale(x, pmean(xs), psd(xs), tm, ts), 1) for s, x in zip(ids, xs)] | |
| lines = ["- `raw_mean`: the mean of the marks, 2 decimals.", "- `raw_sd`: the population standard deviation of the marks, 2 decimals.", | |
| "- `students`: an object keyed by student id, each with `scaled`: the rescaled mark, 1 decimal."] | |
| what = "`marks.csv` holds the marks of %d students on a class test." % n | |
| elif d == 2: | |
| groups = r.sample(["7A", "7B", "7C", "7D"], 2); ids = sid_list(r, 18); r.shuffle(ids) | |
| member = dict((g, sorted(ids[i * 8:(i + 1) * 8])) for i, g in enumerate(groups)); absent = sorted(ids[16:]) | |
| while True: | |
| marks, scaled, clamped, ok = {}, {}, [], True | |
| for gi, g in enumerate(groups): | |
| xs = cluster(8, gi == 0 or r.random() < 0.3) | |
| order = member[g][:]; r.shuffle(order) | |
| for s, x in zip(order, xs): | |
| raw = rescale(x, pmean(xs), psd(xs), tm, ts) | |
| marks[s] = x; scaled[s] = rescale(x, pmean(xs), psd(xs), tm, ts, top) | |
| if not clamp_ok(raw): ok = False | |
| if raw != scaled[s]: clamped.append(s) | |
| if psd(xs) < 0.04 * top: ok = False | |
| if ok and clamped: break | |
| rows = [{"student_id": s, "group": g, "mark": marks[s]} for g in groups for s in member[g]] | |
| rows += [{"student_id": s, "group": r.choice(groups), "mark": ""} for s in absent] | |
| r.shuffle(rows) | |
| files["marks.csv"] = to_csv(rows, ["student_id", "group", "mark"]) | |
| for g in sorted(groups): | |
| xs = [marks[s] for s in member[g]] | |
| checks += [c_num("groups.%s.raw_mean" % g, pmean(xs), 2), c_num("groups.%s.raw_sd" % g, psd(xs), 2)] | |
| checks += [c_num("students.%s.scaled" % s, scaled[s], 1) for s in sorted(marks)] | |
| checks += [c_set("clamped", clamped, weight=2), c_set("absent", absent, weight=2)] | |
| lines = ["- `groups`: an object keyed by teaching group, each with `raw_mean` and `raw_sd` (population standard deviation) of that group's marks, 2 decimals.", | |
| "- `students`: an object keyed by student id, for every student with a mark, each with `scaled`: the rescaled mark after any limiting, 1 decimal.", | |
| "- `clamped`: list of the student ids whose scaled mark had to be limited to the top or bottom of the range (any order; an empty list if none).", | |
| "- `absent`: list of the student ids with no mark (any order)."] | |
| what = "`marks.csv` holds the marks of two teaching groups on the same test." | |
| else: | |
| markers = ["M1", "M2", "M3"]; ids = sid_list(r, 21); r.shuffle(ids) | |
| scripts = dict((m, sorted(ids[i * 7:(i + 1) * 7])) for i, m in enumerate(markers)) | |
| while True: | |
| bias = dict((m, r.choice([-0.09, -0.06, 0.0, 0.0, 0.05, 0.08]) * top) for m in markers) | |
| marks, sample, diffs, add = {}, {}, {}, {} | |
| for mi, m in enumerate(markers): | |
| xs = cluster(7, mi == 0) | |
| order = scripts[m][:]; r.shuffle(order) | |
| for s, x in zip(order, xs): marks[s] = x | |
| chosen = r.sample(scripts[m], r.randint(3, 4)) | |
| for s in chosen: sample[s] = int(min(top, max(0, round(marks[s] + bias[m] + r.gauss(0, 0.02 * top))))) | |
| diffs[m], add[m] = marker_adjustment([(marks[s], sample[s]) for s in chosen], tol) | |
| if not all(clear_of(abs(diffs[m]), [tol], 0.3) for m in markers): continue | |
| if not 1 <= sum(1 for m in markers if add[m]) <= 2: continue | |
| adj = dict((s, marks[s] + add[m]) for m in markers for s in scripts[m]) | |
| vals = [adj[s] for s in sorted(adj)]; M, SD = pmean(vals), psd(vals) | |
| raw = dict((s, rescale(adj[s], M, SD, tm, ts)) for s in adj) | |
| if not all(clamp_ok(v) for v in raw.values()): continue | |
| final = dict((s, rescale(adj[s], M, SD, tm, ts, top)) for s in adj) | |
| clamped = [s for s in adj if final[s] != raw[s]] | |
| if clamped or r.random() < 0.3: break | |
| rows = [{"student_id": s, "marker": m, "mark": marks[s]} for m in markers for s in scripts[m]] | |
| r.shuffle(rows) | |
| srows = [{"student_id": s, "moderator_mark": v} for s, v in sample.items()] | |
| r.shuffle(srows) | |
| files["scripts.csv"] = to_csv(rows, ["student_id", "marker", "mark"]) | |
| files["moderation_sample.csv"] = to_csv(srows, ["student_id", "moderator_mark"]) | |
| checks += [c_num("markers.%s.mean_difference" % m, diffs[m], 2) for m in markers] | |
| checks += [c_set("adjusted_markers", [m for m in markers if add[m]], weight=2), c_num("cohort_mean", M, 2), c_num("cohort_sd", SD, 2)] | |
| checks += [c_num("students.%s.final" % s, final[s], 1) for s in sorted(final)] | |
| checks.append(c_set("clamped", clamped, weight=2)) | |
| lines = ["- `markers`: an object keyed by marker, each with `mean_difference`: the mean of moderator's mark minus marker's mark over that marker's sampled scripts, 2 decimals, with its sign.", | |
| "- `adjusted_markers`: list of the markers whose marks were adjusted in step 1 (any order; an empty list if none).", | |
| "- `cohort_mean` and `cohort_sd`: the mean and population standard deviation of all students' marks after step 1, 2 decimals.", | |
| "- `students`: an object keyed by student id, each with `final`: the mark after step 2, including any limiting, 1 decimal.", | |
| "- `clamped`: list of the student ids whose final mark had to be limited to the top or bottom of the range (any order; an empty list if none)."] | |
| what = "`scripts.csv` holds the marks three markers gave to their scripts, and `moderation_sample.csv` the marks a moderator gave to a sample of those scripts." | |
| inst = """# Class test: standardising marks | |
| %s `moderation_notes.md` gives the procedure, the targets and the formula: follow it exactly. | |
| Write `answer.json` in this folder, a JSON object with: | |
| %s | |
| Numbers are accepted within one unit of the last decimal place asked for. | |
| """ % (what, "\n".join(lines)) | |
| files["moderation_notes.md"] = moderation_notes(d, top, tm, ts, tol) | |
| return Task(ENV, "moderation", seed, d, "Standardise the marks of a class test", inst, files, checks, {"max_mark": top}) | |
| FAMILIES = {"marking": gen_marking, "item-analysis": gen_items, "distractors": gen_distractors, "moderation": gen_moderation} | |
| def generate(seed, difficulty, family=None): | |
| fam = family or sorted(FAMILIES)[seed % len(FAMILIES)] | |
| return FAMILIES[fam](seed, difficulty) | |