{
  "id": "adam-spec-row-to-r-code",
  "title": "Turn ADaM spec rows into draft code with a test plan, then run and compare with the real ADAE",
  "study": {
    "name": "CDISCPILOT01 (CDISC SDTM/ADaM Pilot Project, xanomeline TTS in Alzheimer's disease)",
    "source_url": "https://github.com/cdisc-org/sdtm-adam-pilot-project",
    "licence_note": "Datasets, define.xml and programs are CDISC Pilot Project materials, used unmodified and attributed to CDISC under the Terms of Use in the repository README (no modification, no sale of the data, attribution required). The study is a CDISC mock submission with fictional dates. Not legal advice."
  },
  "task": "Draft code for 15 ADAE variables from their adam_define.xml derivation rows and SDTM AE source variables, write a test plan, run the code on the real SDTM AE and ADSL, and compare every variable with adam_adae.xpt cell by cell.",
  "time_to_try_minutes": "About 45 minutes (estimate, not measured), including pasting the rows and running the comparison on your own data",
  "good": {
    "input_excerpt": "Source: adam_define.xml (CDISC SDTM/ADaM Pilot Project, unmodified), ADaM metadata for dataset ADAE, ItemDef entries. Format: variable | label | type | derivation text from the file's Comment attribute, with XML entities and curly quote characters normalised to plain text (define.xml lines 3544-3925; line numbers cited on this page are the first line of each ItemDef, and the Comment text sits a few lines below it, for example TRTEMFL text at line 3843, CQ01NAM text and the 'SUBC UTANEOUS' string at line 3913, AOCC01FL text at line 3921). Source SDTM: AE (sdtm_ae.xpt). Treatment start date comes from ADSL (adam_adsl.xpt, variable TRTSDT, a SAS date: whole days since 1960-01-01), matched on USUBJID.\n\nAESEQ | Sequence Number | integer | AE.AESEQ\nASTDT | Analysis Start Date | integer (date, DATE9.) | AE.AESTDTC, converted to a numeric SAS date. Some events with partial dates are imputed in a conservative manner. If the day component is missing, a value of '01' is used. If both the month and day are missing no imputation is performed as these dates clearly indicate a start prior to the beginning of treatment. There are no events with completely missing start dates.\nASTDTF | Analysis Start Date Imputation Flag | text | ASTDTF='D' if the day value within the character date is imputed. Note that only day values needed to be imputed for this study.\nAENDT | Analysis End Date | integer (date) | AE.AEENDTC, converted to a numeric SAS date\nASTDY | Analysis Start Relative Day | integer | IF ASTDT>=TRTSDT>MISSING then ASTDY=ASTDT-TRTSDT+1 Else if TRTSDT>ASTDT>MISSING then ASTDY=ASTDT-TRTSDT\nAENDY | Analysis End Relative Day | integer | IF AENDT>=TRTSDT>MISSING then AENDY=AENDT-TRTSDT+1 Else if TRTSDT>AENDT>MISSING then AENDY=AENDT-TRTSDT\nADURN | AE Duration (N) | integer | ADURN=AENDT-ASTDT+1\nADURU | AE Duration Units | text | If ADURN is not missing then ADURU='DAY'\nTRTEMFL | Treatment Emergent Analysis Flag | text (Y/N) | If ASTDT >= TRTSDT > . then TRTEMFL='Y'. Otherwise TRTEMFL='N'\nAOCCFL | 1st Occurrence of Any AE Flag | text | Subset to TRTEMFL='Y' and sort by Subject (USUBJID), Start Date (ASTDT), and Sequence Number (AESEQ) and flag the first record (set AOCCFL='Y') within each Subject\nAOCCSFL | 1st Occurrence of SOC Flag | text | Subset to TRTEMFL='Y' and sort by Subject (USUBJID), System Organ Class (AEBODSYS), Start Date (ASTDT), and Sequence Number (AESEQ) and flag the first record (set AOCCSFL='Y') within each Subject and SOC\nAOCCPFL | 1st Occurrence of Preferred Term Flag | text | Subset to TRTEMFL='Y' and sort by Subject (USUBJID), System Organ Class (AEBODSYS), Preferred Term (AEDECOD), Start Date (ASTDT), and Sequence Number (AESEQ) and flag the first record (set AOCCPFL='Y') within each Subject, SOC, and PT\nAOCC02FL | 1st Occurrence 02 Flag for Serious | text | Subset to TRTEMFL='Y' and AESER='Y' and sort by Subject (USUBJID), Start Date (ASTDT), and Sequence Number (AESEQ) and flag the first record (set AOCC02FL='Y') within each Subject\nCQ01NAM | Customized Query 01 Name | text | If AEDECOD contains any of the character strings of ('APPLICATION', 'DERMATITIS', 'ERYTHEMA', 'BLISTER') OR if AEBODSYS='SKIN AND SUBC UTANEOUS TISSUE DISORDERS' but AEDECOD is not in ('COLD SWEAT', 'HYPERHIDROSIS', 'ALOPECIA') then CQ01NAM='DERMATOLOGIC EVENTS' Otherwise CQ01NAM=NULL\nAOCC01FL | 1st Occurrence 01 Flag for CQ01 | text | Subset to CQ01NAM='' and TRTEMFL='Y' and sort by Subject (USUBJID), Start Date (ASTDT), and Sequence Number (AESEQ) and flag the first record (set AOCC01FL='Y') within each Subject (Flag First Treatment Emergent Dermatological Event for Time to Event Analysis)\n\nSDTM AE variables available: USUBJID, AESEQ, AESTDTC and AEENDTC (ISO 8601 text, may be YYYY-MM-DD, YYYY-MM or YYYY, or blank), AEDECOD, AEBODSYS, AESER (Y/N).",
    "prompt": "Draft code for the ADAE variables in the rows below. Language: R if you can; if R is not available, use Python (pandas). Allowed: base functions and dplyr only (no admiral).\n\nFor each variable give one code block with a comment restating the derivation text. Use only the rows and source variables I pasted; do not add logic the text does not state. Where the text looks ambiguous or self-contradictory, say so once in OPEN QUESTIONS and say which reading you coded.\n\nThen give a test plan: 8 to 10 small synthetic cases with the expected value derived by hand from the text, and a plan for comparing every variable with an existing ADAE (keys USUBJID + AESEQ, variable by variable, counts of matches and a listing of mismatches).\n\nLabel the code UNRUN. Do not claim it is correct.\n\n[define.xml rows and source variables pasted here]",
    "output": "LANGUAGE: Python (pandas). R is not installed on the machine that ran this, so the instruction \"R if you can\" was answered with Python. An R/dplyr version was not written or run. The code was UNRUN when written; run results follow it.\n\nCODE\n\nimport numpy as np, pandas as pd\nSAS0 = pd.Timestamp(\"1960-01-01\")\ndt_to_sas = lambda s: (s - SAS0).dt.days.astype(\"float\")          # SAS date number; NaT -> NaN\n\ndef first_flag(d, by, mask, name):\n    # sort by USUBJID, <by>, ASTDT, AESEQ among rows in mask; flag first row within USUBJID + <by>\n    s = d[mask].sort_values([\"USUBJID\"] + by + [\"ASTDT\", \"AESEQ\"])\n    idx = s.groupby([\"USUBJID\"] + by, sort=False).head(1).index\n    d[name] = \"\"; d.loc[idx, name] = \"Y\"\n\ndef derive(ae, adsl):\n    d = ae.merge(adsl[[\"USUBJID\", \"TRTSDT\"]], on=\"USUBJID\", how=\"left\")   # TRTSDT = SAS date number\n    # ASTDT: AESTDTC to a date; YYYY-MM -> day '01'; YYYY only -> no imputation (missing)\n    s = d.AESTDTC.fillna(\"\").str.strip()\n    full = pd.to_datetime(s.where(s.str.len() >= 10).str[:10], format=\"%Y-%m-%d\", errors=\"coerce\")\n    ym   = pd.to_datetime(s.where(s.str.len() == 7) + \"-01\", format=\"%Y-%m-%d\", errors=\"coerce\")\n    d[\"ASTDT\"]  = dt_to_sas(full.fillna(ym))\n    d[\"ASTDTF\"] = np.where(full.isna() & ym.notna(), \"D\", \"\")             # day imputed\n    # AENDT: AEENDTC converted to a date, no imputation stated\n    e = d.AEENDTC.fillna(\"\").str.strip()\n    d[\"AENDT\"] = dt_to_sas(pd.to_datetime(e.where(e.str.len() >= 10).str[:10], format=\"%Y-%m-%d\", errors=\"coerce\"))\n    # relative day: on/after TRTSDT = diff + 1; before = diff (no day 0)\n    rel = lambda x: np.where(x >= d.TRTSDT, x - d.TRTSDT + 1, np.where(d.TRTSDT > x, x - d.TRTSDT, np.nan))\n    d[\"ASTDY\"], d[\"AENDY\"] = rel(d.ASTDT), rel(d.AENDT)\n    d[\"ADURN\"] = d.AENDT - d.ASTDT + 1\n    d[\"ADURU\"] = np.where(d.ADURN.notna(), \"DAY\", \"\")\n    d[\"TRTEMFL\"] = np.where(d.ASTDT >= d.TRTSDT, \"Y\", \"N\")                # NaN compares False -> \"N\"\n    te = d.TRTEMFL == \"Y\"\n    pt, soc = d.AEDECOD.fillna(\"\"), d.AEBODSYS.fillna(\"\")\n    derm = pt.str.contains(\"APPLICATION|DERMATITIS|ERYTHEMA|BLISTER\") | \\\n           ((soc == \"SKIN AND SUBC UTANEOUS TISSUE DISORDERS\") & ~pt.isin([\"COLD SWEAT\", \"HYPERHIDROSIS\", \"ALOPECIA\"]))\n    d[\"CQ01NAM\"] = np.where(derm, \"DERMATOLOGIC EVENTS\", \"\")\n    first_flag(d, [],                        te,                       \"AOCCFL\")\n    first_flag(d, [\"AEBODSYS\"],              te,                       \"AOCCSFL\")\n    first_flag(d, [\"AEBODSYS\", \"AEDECOD\"],   te,                       \"AOCCPFL\")\n    first_flag(d, [],                        te & (d.AESER == \"Y\"),    \"AOCC02FL\")\n    first_flag(d, [],                        te & (d.CQ01NAM == \"DERMATOLOGIC EVENTS\"), \"AOCC01FL\")\n    return d\n\nOPEN QUESTIONS (each once, as the cold answer listed them)\n1. AOCC01FL text says \"Subset to CQ01NAM=''\" but the parenthetical says \"Flag First Treatment Emergent Dermatological Event\". Coded the parenthetical (subset to CQ01NAM = 'DERMATOLOGIC EVENTS'). The literal text would flag the first non-dermatologic event.\n2. The CQ01NAM text has \"SUBC UTANEOUS\" with a space. Coded exactly as written; this looks like a typo for SUBCUTANEOUS. Check the distinct AEBODSYS values before trusting it.\n3. AENDT: \"converted to a numeric SAS date\" gives no rule for partial or blank end dates. Coded: full dates only; anything else missing.\n4. ADURN: no rule for what to do when ASTDT was imputed. Coded the formula as written.\n5. AESTDTC with a time part: not stated. Coded: use the first 10 characters when 10 or more are present.\n\nTEST PLAN\nA. Synthetic cases (hand-derived from the text, 1 subject, TRTSDT = 2013-03-10):\n 1. AESTDTC 2013-03-10 -> ASTDY 1, TRTEMFL Y.\n 2. AESTDTC 2013-03-09 -> ASTDY -1 (no day 0), TRTEMFL N.\n 3. AESTDTC 2013-03 -> ASTDT 2013-03-01, ASTDTF D, ASTDY -9.\n 4. AESTDTC 2013 -> ASTDT missing, ASTDTF blank, TRTEMFL N.\n 5. Two events on the same ASTDT -> AOCCFL on the lower AESEQ.\n 6. Same PT twice, same SOC -> AOCCPFL and AOCCSFL on the earliest only.\n 7. A serious event that is not treatment emergent -> AOCC02FL stays blank.\n 8. A dermatologic event that is not treatment emergent -> CQ01NAM set, AOCC01FL blank.\n 9. AENDT blank -> AENDY, ADURN missing, ADURU blank.\n 10. ADURN for 2013-03-10 to 2013-03-12 -> 3, ADURU DAY.\nB. Comparison with the existing ADAE: merge on USUBJID + AESEQ, check the key sets are equal, then for each of the 15 variables count equal cells (treat NaN = NaN as equal, trim text) and print the first five mismatches. Report matches/total per variable.\nC. Where a variable mismatches, test one cause at a time: input date format, missing handling, sort order, the text of the rule itself.\n\nRESULTS (run 2026-10-19: python -I adam-spec-row-to-r-code_recompute.py <source_dir> first)\n\nSynthetic tests: 10/10 pass.\n\nAgainst adam_adae.xpt (1191 rows; keys USUBJID + AESEQ match exactly, 0 key mismatches):\nAESEQ 1191/1191 | TRTEMFL 1191/1191 | ASTDT 1191/1191 | ASTDTF 1191/1191 | AENDT 1191/1191 | ASTDY 1191/1191 | AENDY 1191/1191\nADURN 1187/1191 (99.7%) | ADURU 1187/1191 (99.7%)\nAOCCFL 1191/1191 | AOCCSFL 1191/1191 | AOCCPFL 1191/1191 | AOCC02FL 1191/1191\nCQ01NAM 1010/1191 (84.8%) | AOCC01FL 1107/1191 (92.9%)\nTOTAL 17592/17865 cells = 98.47%\n\nMISMATCHES AND DIAGNOSIS (written after the run)\n1. CQ01NAM, 181 cells: reference DERMATOLOGIC EVENTS, draft blank. Every one is an event in SKIN AND SUBCUTANEOUS TISSUE DISORDERS. Cause: the draft copied the define.xml string \"SKIN AND SUBC UTANEOUS ...\" (flagged as open question 2); the data value has no space. The synthetic tests passed because they used the correct string. Fix: one string. After the fix CQ01NAM is 1191/1191.\n2. AOCC01FL, 84 cells: knock-on of 1. It is built on CQ01NAM, so missing dermatologic rows moved the first flag to a later event or removed it. After the CQ01NAM fix: 1191/1191. The parenthetical reading chosen for open question 1 was right.\n3. ADURN and ADURU, 4 cells each (subject 01-716-1418, AESEQ 5 to 8): reference missing, draft 88, 96, 88, 96 days. All four are among the 15 events with an imputed start date (ASTDTF = D). The define.xml text gives ADURN=AENDT-ASTDT+1 with no exception, so the draft followed it. The existing dataset leaves duration missing when the start day was imputed. This rule is not in the define.xml text for ADAE. Fix, reverse-engineered from the data and NOT from the spec: set ADURN missing when ASTDTF = D. After it: 1191/1191 on every variable, total 17865/17865 (100.00%) (variant \"final\" of the script).",
    "trim_note": "Define.xml Comment text is quoted from the Comment attribute with XML entities and quote characters normalised, including the 'SUBC UTANEOUS' string and the AOCC01FL wording. Label, type and ordering are condensed into one line per variable. Variables not shown (identifier, treatment and demographic copies from ADSL, MedDRA term copies) were not part of this run."
  },
  "bad": {
    "input": "Write R code to derive the ADAE variables from the spec, TRTEMFL and the dates and the first-occurrence flags. I'll run it.",
    "output": "I do not have your spec in front of me, so this is a typical ADAE derivation using common ADaM conventions. Adjust names to your spec.\n\nlibrary(dplyr)\nlibrary(lubridate)\n\nadae <- ae %>%\n  left_join(adsl %>% select(USUBJID, TRTSDT, TRTEDT), by = \"USUBJID\") %>%\n  mutate(\n    ASTDT   = ymd(AESTDTC),\n    AENDT   = ymd(AEENDTC),\n    TRTEMFL = if_else(ASTDT >= TRTSDT & ASTDT <= TRTEDT + 30, \"Y\", \"N\"),\n    ASTDY   = as.numeric(ASTDT - TRTSDT) + 1,\n    AENDY   = as.numeric(AENDT - TRTSDT) + 1,\n    ADURN   = as.numeric(AENDT - ASTDT) + 1,\n    ADURU   = if_else(!is.na(ADURN), \"DAYS\", NA_character_)\n  ) %>%\n  arrange(USUBJID, ASTDT) %>%\n  group_by(USUBJID) %>%\n  mutate(AOCCFL = if_else(row_number() == 1 & TRTEMFL == \"Y\", \"Y\", NA_character_)) %>%\n  ungroup()\n\nNotes: TRTEMFL uses the usual 30-day follow-up window. Partial dates are left missing. Add the SOC and PT flags the same way with group_by(USUBJID, AEBODSYS) and group_by(USUBJID, AEBODSYS, AEDECOD). Test it on a few subjects and compare with your expected output.\n\n---\nFIRST CHECK, 2026-10-19 (a pandas stand-in for the R; the real R run is under R RUN below). R was not installed on the machine used, so the R above was translated line by line into pandas (function derive_bad in adam-spec-row-to-r-code_recompute.py; lubridate::ymd returns NA on a partial date, which the translation reproduces) and run on the real SDTM AE and ADSL, then compared with adam_adae.xpt, 1191 rows, 15 variables. The translation is mine, not an R run.\nCommand: python -I adam-spec-row-to-r-code_recompute.py <source_dir> bad\n\nTRTEMFL   1185/1191  99.5%\nASTDT     1176/1191  98.7%\nASTDTF    not produced\nASTDY     1131/1191  95.0%\nAENDY     1187/1191  99.7%\nADURU      477/1191  40.1%   (\"DAYS\" instead of \"DAY\" on all 714 non-missing rows)\nAOCCFL    1130/1191  94.9%\nAOCCSFL, AOCCPFL, AOCC02FL, CQ01NAM, AOCC01FL: not produced\n(AESEQ, AENDT, ADURN agree: 1191/1191 each.)\nTOTAL cells 9859/17865 = 55.19%\n\nExamples: 01-701-1111 AESEQ 1 ASTDY reference -5, draft -4 (the +1 was applied to dates before first dose, where the spec says no +1). 01-701-1239 AESEQ 9 and 10 TRTEMFL reference Y, draft N (partial start dates left missing by ymd, so they never reach TRTEMFL=Y).\n\nR RUN (2026-10-20). R 4.6.1 on Windows; dplyr 1.2.1, lubridate 1.9.5, haven 2.5.5. The R block above was extracted character for character (adam-spec-row-to-r-code_Rrun/run_bad.R). It assumes data frames ae and adsl already exist, so a short harness (harness_bad.R, not AI code) reads sdtm_ae.xpt and adam_adsl.xpt with haven::read_xpt and then runs run_bad.R. The code ran to the end with no error. One warning: In argument: `ASTDT = ymd(AESTDTC)`. ! 19 failed to parse.\nComparison with adam_adae.xpt on USUBJID + AESEQ (1191 of 1191 keys found), in R, text trimmed:\nTRTEMFL   1172/1191\nASTDT     1176/1191\nASTDTF    not produced\nAENDT     1191/1191\nASTDY     1131/1191\nAENDY     1187/1191\nADURN     1191/1191\nADURU      477/1191   (\"DAYS\" instead of \"DAY\" on all 714 non-missing rows)\nAOCCFL    1130/1191\nAOCCSFL, AOCCPFL, AOCC02FL, CQ01NAM, AOCC01FL: not produced\nTOTAL 9846/17865 cells = 55.11% (AESEQ counted as matching, variables not produced counted as not matching).\nThe pandas stand-in above gave 9859/17865 = 55.19%. What the real R run changed:\n- TRTEMFL: 19 rows differ, all NA in R (6 where adam_adae.xpt has Y, 13 where it has N), because a comparison with a missing date gives NA. The stand-in had 6 wrong rows and treated the missing dates as N. No mismatch comes from the 30-day window.\n- lubridate::ymd on the whole column did not give NA for every partial date, as the stand-in assumed. 8 month-only values became NA and 7 became wrong dates, for example AESTDTC 2012-02 became 2020-12-02 and 2010-06 became 2020-10-06 (xpt: 2012-02-01 and 2010-06-01). Run on a single value, ymd(\"2013-03\") gives NA, so the result depends on the other values in the column. The only sign is the warning \"19 failed to parse\", which counts 8 month-only and 11 year-only values and not the 7 wrong dates.\n- ASTDY: 60 rows differ (45 off by one, 8 NA, 7 wrong dates); AENDY: 4 off by one; AOCCFL: 201 rows flagged Y against 218 in the xpt (61 cells differ, as in the stand-in).",
    "what_went_wrong": [
      "No spec was pasted, so the code is a generic recipe built from habit. The assistant did not ask which rows; it filled the gap with common conventions.",
      "TRTEMFL used a 30-day follow-up window that appears nowhere in the study's spec (define.xml item ADAE.TRTEMFL, line 3838: ASTDT >= TRTSDT > . only). In the real R run TRTEMFL differs from adam_adae.xpt in 19 rows, all NA from partial start dates (the earlier pandas stand-in showed 6); no mismatch comes from the window.",
      "Partial start dates were silently left missing (the 15 events with only the day missing should be imputed to day 01 and flagged ASTDTF='D'; the draft never creates ASTDTF at all). In the real R run, ymd() turned 8 of the 15 month-only dates into NA and 7 into wrong dates (2012-02 became 2020-12-02), with only the warning '19 failed to parse'.",
      "Study day used +1 on both sides of the reference date; the spec has no day 0, so dates before first dose get date minus TRTSDT. 45 ASTDY values are off by one and 15 are wrong in the draft (the month-only start dates it left unimputed: 8 missing and 7 wrong dates in the real R run); 4 AENDY values are off by one.",
      "ADURU was 'DAYS'; the spec says 'DAY'. Wrong on all 714 non-missing rows.",
      "AOCCFL took the first row after sorting by ASTDT only (no AESEQ tie-break) and only if that row was treatment emergent, so the flag was wrong in 61 cells across 39 subjects (61 cells in the real R run too; the subject count and the two causes come from the pandas stand-in), from two causes found by re-running the script: in 17 subjects the draft's first row was not treatment emergent, so the real first treatment-emergent row got no flag (17 cells); in 22 subjects two or more events share the earliest treatment-emergent date and the draft flagged a different one of them than the real ADAE does (the real one has the lower AESEQ), giving 22 missing and 22 spurious flags (44 cells). The SOC and PT flags were deferred, and the serious and dermatologic flags and CQ01NAM were not written.",
      "It said 'test it on a few subjects' but gave no test plan. Nothing in the answer would tell the programmer which of the 15 variables was wrong."
    ]
  },
  "what_changed": [
    "The bad run guessed the derivations from habit (30-day window, +1 on every study day, 'DAYS'); the good run coded only the pasted define.xml text, and 11 of 15 variables matched the real ADAE on every one of 1191 rows on the first run.",
    "The bad run produced 9 of the 15 variables and 55.11% of cells matched when its R code was run in R 4.6.1 (55.19% in an earlier pandas stand-in). The good run produced all 15: 98.47% on the first run, 100% after two fixes.",
    "The good run listed the ambiguous AOCC01FL text and the odd 'SUBC UTANEOUS' string as open questions before running anything. The first was resolved correctly; the second is exactly where cells failed. Caveat: the builder had read adam_adae.sas before writing the cold answer, so these two catches (and open question 4 about ADURN for imputed start dates) may reflect that exposure and are not unaided catches by the model.",
    "The good run came with a comparison plan (merge on USUBJID + AESEQ, per-variable match counts), so 273 mismatched cells were traced to three causes quickly instead of by eye.",
    "Hand-written synthetic tests (10/10 pass) did not catch either spec problem. Only the comparison with the real dataset did."
  ],
  "check_before_trust": [
    "Run the code yourself on your own data. This page shows one run of Python (good answer) and one run of R 4.6.1 (bad answer) on the CDISC pilot data, not a validation of anything. No R version of the good answer was written or run.",
    "Compare against an existing dataset variable by variable on the full key (USUBJID + AESEQ). Check the key sets match first, and treat missing = missing as equal.",
    "Read each mismatch as a possible spec problem, not only a code problem. Here two of the three causes were in the define.xml text (a typo in a string, and a missing exception for duration).",
    "Search the spec text for literal strings you will compare against (SOC names, preferred terms, controlled terminology) and check them against the distinct values in the data before you trust them.",
    "Tests derived from the same spec share its blind spots. Add at least one test that uses real values from the data, not only synthetic ones.",
    "Do not accept a fix reverse-engineered from the target dataset (here, ADURN missing when the start day was imputed). Take it back to the spec owner and get the rule written down."
  ],
  "verification": {
    "answer_key": "The real ADAE dataset (adam_adae.xpt, 1191 rows) compared cell by cell; adam_define.xml lines 3544 to 3925 (ADAE ItemDefs); adam_adae.sas as the reference derivation (read by the builder before the cold answer was written; used again after the run for the ADURN diagnosis).",
    "rows": [
      {
        "claim": "AESEQ copied from AE.AESEQ and keys are unique (1191 of 1191 match)",
        "verdict": "Correct",
        "cite": "define.xml line 3830; ADAE vs SDTM AE, both 1191 rows"
      },
      {
        "claim": "ASTDT: full dates converted; YYYY-MM imputed to day 01; year-only left missing (1191/1191)",
        "verdict": "Correct",
        "cite": "define.xml line 3544; 15 events imputed, 11 missing (year only) in ADAE"
      },
      {
        "claim": "ASTDTF = D exactly on the 15 imputed events (1191/1191)",
        "verdict": "Correct",
        "cite": "define.xml line 3553"
      },
      {
        "claim": "AENDT full-dates-only conversion (1191/1191)",
        "verdict": "Correct",
        "cite": "define.xml line 3571; the 473 blank end dates stay missing in ADAE"
      },
      {
        "claim": "ASTDY and AENDY with no day 0 (1191/1191 each)",
        "verdict": "Correct",
        "cite": "define.xml lines 3563, 3580"
      },
      {
        "claim": "TRTEMFL (1191/1191; Y 1126, N 65)",
        "verdict": "Correct",
        "cite": "define.xml line 3838"
      },
      {
        "claim": "AOCCFL, AOCCSFL, AOCCPFL, AOCC02FL (1191/1191 each; Y counts 218, 550, 781, 3)",
        "verdict": "Correct",
        "cite": "define.xml lines 3848 to 3878"
      },
      {
        "claim": "ADURN = AENDT-ASTDT+1 and ADURU = DAY (1187/1191 each)",
        "verdict": "Partly",
        "cite": "define.xml lines 3588, 3596: formula right, but the ADAE data leave both missing for the 4 events with an imputed start date; the exception is not in the define text"
      },
      {
        "claim": "CQ01NAM using the string exactly as written in define (1010/1191)",
        "verdict": "Wrong",
        "cite": "define.xml line 3913 has 'SUBC UTANEOUS'; the data value is 'SKIN AND SUBCUTANEOUS TISSUE DISORDERS'"
      },
      {
        "claim": "AOCC01FL coded from the parenthetical (first TE dermatologic event), not the literal CQ01NAM='' text (1107/1191; 1191/1191 once CQ01NAM is fixed)",
        "verdict": "Correct",
        "cite": "define.xml line 3916; the Comment text is inconsistent with its own parenthetical"
      },
      {
        "claim": "Open question 2 flagged the 'SUBC UTANEOUS' string as a probable typo",
        "verdict": "Correct",
        "cite": "define.xml line 3913; confirmed by the 181 CQ01NAM mismatches"
      },
      {
        "claim": "Synthetic tests (10/10) show the code is right",
        "verdict": "Wrong",
        "cite": "They passed while 273 real cells failed; the tests used the correct SOC string and had no imputed-start duration case"
      },
      {
        "claim": "TRTSDT from ADSL is a SAS date (days since 1960-01-01)",
        "verdict": "Correct",
        "cite": "define.xml line 6440 (ADSL.TRTSDT); adam_adsl.xpt has 0 missing TRTSDT"
      },
      {
        "claim": "ADAE variables outside these 15, and ADSL and ADTTE rows",
        "verdict": "Not in source",
        "cite": "Not attempted in this run"
      }
    ],
    "errors_found": [
      "CQ01NAM: 181 cells wrong because the define.xml string 'SKIN AND SUBC UTANEOUS TISSUE DISORDERS' contains a stray space. The draft copied it literally even though it had flagged it as a probable typo. Spec defect, not an invention by the AI.",
      "AOCC01FL: 84 cells wrong, knock-on of the CQ01NAM error. The AI's reading of the self-contradictory text (parenthetical over the literal CQ01NAM='') was correct.",
      "ADURN and ADURU: 4 cells each wrong. The existing ADAE leaves duration missing for events with an imputed start date; the define text does not say so. The AI followed the define text. The fix used here (missing when ASTDTF = D) was reverse-engineered from the data.",
      "Diagnosis aid, consulted after the run: adam_adae.sas computes the duration before start-date imputation, which explains the four missing ADURN values. The program also names the variable ADUR, while define.xml and the xpt use ADURN, so the define and the program are not fully consistent.",
      "The 10 synthetic tests all passed even though 273 real cells failed. Tests built from the spec cannot find spec defects.",
      "The pandas stand-in for the bad R code assumed lubridate::ymd returns NA on every partial date and treated a missing TRTEMFL as N. The real R run (2026-10-20) differs: 7 of 15 month-only dates became wrong dates (for example 2012-02 became 2020-12-02) and TRTEMFL was NA in 19 rows. The overall match was 55.11% in R against 55.19% in the stand-in, so the findings on the bad draft hold, but two details on this page came from the stand-in and were corrected."
    ],
    "summary": "The cold draft produced all 15 requested ADAE variables and matched the real ADAE on 17592 of 17865 cells (98.47%) on the first run; 11 variables matched on every row. The 273 mismatches had three causes: a typo in the define.xml CQ01NAM string (181 cells, plus 84 knock-on cells in AOCC01FL, 265 in all) and an undocumented exception in the existing data (ADURN and ADURU, 4 cells each). All three are spec or data-versus-spec problems, not coding slips; after two fixes the match is 17865 of 17865. The lazy-prompt version matched 55.11% when its R code was run in R 4.6.1 on 2026-10-20 (55.19% in the earlier pandas stand-in) and skipped six variables. Caveats: the good run is Python, not R (R was not available then; no R version of the good answer was written or run), while the bad answer's R code was run in R 4.6.1; it is a single cold draft; the builder had read the reference SAS program before writing the cold answer, although the answer used only the pasted excerpt and prompt; ADSL and ADTTE rows were not attempted. Not a validation of any code."
  },
  "run": {
    "generated_by": "Claude (Anthropic), run as a subagent on 2026-10-19; the bad answer's R code was run in R 4.6.1 on 2026-10-20 (dplyr 1.2.1, lubridate 1.9.5, haven 2.5.5)",
    "not_tested_in": "Microsoft 365 Copilot"
  },
  "run_summary": [
    {
      "kind": "warn",
      "label": "Good prompt, first run",
      "text": "17,592 of 17,865 cells match the real ADAE (98.47%); 11 of 15 variables match on every row."
    },
    {
      "kind": "fail",
      "label": "Why not 100%",
      "text": "A typo in the define.xml and an undocumented data exception, not coding slips."
    },
    {
      "kind": "ok",
      "label": "After two fixes",
      "text": "17,865 of 17,865 cells match."
    },
    {
      "kind": "fail",
      "label": "Lazy prompt, run in R 4.6.1",
      "text": "55.11% of cells match; ymd() turned 7 month-only dates into wrong dates."
    }
  ]
}