File size: 8,017 Bytes
a496c92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evidence-controlled DEV cohort binding stress test, not an IR benchmark."""
import json
import re
import tiktoken
from prepare_confirmation_source_cohort import OUT, read, digest
from prepare_openqa_dev161_equal_budget import freeze, sha
from study_population_witness_gate import counts, decision

DEST=OUT/'study_bound_numeric_binding_development_v2/population_binding_challenge_development_v1'
CHECK=''' Before giving a quantity, check that the evidence ties the question's exact population, including any stated sample or patient count, to the requested analysis or statistic. A number appearing in another subgroup, demographic table, or unrelated sentence does not establish this link. Do not replace the question's population with the paper's full cohort. If the evidence reports the statistic for a different population or does not report it for the requested one, return unanswerable. Do not compute an unreported subgroup estimate. Keep the same two-field answer/citations output contract.'''


def main():
    DEST.mkdir(exist_ok=True)
    root=OUT/'study_bound_numeric_binding_development_v2'
    items={r['id']:r for r in read(root/'structured_numeric_reader_development_v1/items17_local_only.jsonl')}
    corpus_path=OUT/'numeric_rag_development_smoke_v2/corpus_source_only_local.jsonl'
    corpus={r['source_id']:r for r in read(corpus_path)}
    blocks={r['pmid']:json.loads(r['messages'][1]['content'])['source_blocks'] for r in read(OUT/'development_qa_pilot/development_requests8_local_only.jsonl')}
    plans=[('CONFDEV:32670372:1:identified-v2','PMC7341374:table2',32),
           ('CONFDEV:36212448:1:identified-v2','PMC9532974:p3',123),
           ('CONFDEV:37397644:1:identified-v2','PMC10314723:p33',14),
           ('CONFDEV:37425507:2:identified-v2','PMC10324624:p16',729)]
    explanations=['32samples is the age-table denominator, whereas aCGH analysis explicitly uses33samples.',
                  '123patients have focal neurological deficits; the reported GTR percentage concerns the300patient surgical series, not an explicitly reported123patient subgroup.',
                  '14patients have elevated biochemical measurements; mean patient age is reported for23patients, not the14patient biochemical subgroup.',
                  '729patients are the supratentorial subgroup;47.53years is the overall916patient mean, not a reported729patient subgroup mean.']
    prompt=read(root/'common42_hybrid_plain_reader_development_v2/requests68_local_only.jsonl')[0]['messages'][0]['content']
    encoder=tiktoken.encoding_for_model('gpt-4o');questions=[];requests=[];decisions=[]
    for (ident,distractor_id,distractor_n),why in zip(plans,explanations):
        item=items[ident];pmid=item['pmid'];requested=counts(item['question'],True);assert len(requested)==1
        n=requested[0]['value'];family=requested[0]['family']
        block=next(r['text'] for r in blocks[pmid] if r['block_id']==item['support_block_id'])
        quote=block[item['support_quote_start']:item['support_quote_end']];assert sha(quote.encode())==item['support_quote_sha256']
        source=sorted(k for k,u in corpus.items() if u['paper_id']==pmid and quote in u['text']);assert source
        population=sorted((k for k,u in corpus.items() if u['paper_id']==pmid and any(c['value']==n and c['family']==family for c in counts(u['text']))),key=lambda k:(len(corpus[k]['text']),k));assert population
        assert corpus[distractor_id]['paper_id']==pmid and any(c['value']==distractor_n and c['family']==family for c in counts(corpus[distractor_id]['text']))
        ids=list(dict.fromkeys([population[0],source[0],distractor_id]))
        evidence='\n\n'.join(f"[E{j}] SourceID:{k} {corpus[k]['title']}\n{corpus[k]['text']}" for j,k in enumerate(ids,1))
        assert len(encoder.encode(evidence))<=6000 and quote in evidence
        available={c['value'] for c in counts(evidence) if c['family']==family};assert n in available and distractor_n in available
        absent=n+1
        while absent in available:absent+=1
        number=re.compile(r'\b'+str(n)+r'\b');assert len(number.findall(item['question']))==1
        for kind,value in [('positive',n),('absent_count',absent),('present_other_role_count',distractor_n)]:
            question=number.sub(str(value),item['question']);qid='POPDEV:'+pmid+':'+kind
            payload={'study':item['study'],'question':question,'evidence':evidence}
            questions.append({'id':qid,'pmid':pmid,'original_development_id':ident,'question':question,'study':item['study'],
                'condition':kind,'source_ids':ids,'support_quote_sha256':sha(quote.encode()),
                'target':item['target'] if kind=='positive' else None,'expected_evidence_bound_abstention':kind!='positive',
                'source_count':n,'requested_count':value,'same_paper_distractor_explanation':why,
                'label_status':'assistant source-read synthetic development control; not clinician-certified or a statement of clinical impossibility',
                'accepted_main_benchmark_question':False,'expert_reviewed':False})
            decisions.append({'id':qid,'decision':decision(payload,corpus)})
            for method,system in [('plain_reader',prompt),('explicit_population_check',prompt+CHECK)]:
                requests.append({'id':qid,'method':method,'track':'evidence_controlled_population_development',
                    'option_letters':[],'context_sha256':sha(evidence.encode()),'context_tokens_unified':len(encoder.encode(evidence)),
                    'response_protocol':'identified_numeric_prompt_only_plain_v2','messages':[{'role':'system','content':system},
                        {'role':'user','content':json.dumps(payload,ensure_ascii=False)}]})
    freeze(DEST/'items12_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in questions))
    freeze(DEST/'requests24_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in requests))
    freeze(DEST/'literal_gate_decisions_before_readers.jsonl',''.join(json.dumps(r)+'\n' for r in decisions))
    freeze(DEST/'protocol.json',json.dumps({'scope':'Evidence-controlled DEVELOPMENT stress test:4previously used development articles, each with1positive+1plausible absent count+1same-paper present distractor count. NOT an independent test, IR evaluation, new clinical gold, or dataset-size addition.',
        'requests_sha256':digest(DEST/'requests24_local_only.jsonl'),'items_sha256':digest(DEST/'items12_local_only.jsonl'),
        'same_evidence_within_each_three_question_family_and_both_reader_arms':True,'max_evidence_tokens':6000,'max_source_units':3,
        'evidence_selection':'Label-informed known-positive source unit + shortest literal population-count unit + fixed actual same-paper other-role unit, deduplicated. This is intentionally oracle-like controlled evidence, NOT a deployable retrieval policy.',
        'intervention':'Extra generic internal population-to-analysis check, same two-field output contract; literal count gate separately replayed without changing raw answers.',
        'methods':['plain_reader','explicit_population_check'],'questions':12,'source_articles':4,
        'luna_reasoning_effort':'low','luna_temperature':'provider_default','local_temperature':0,'max_completion_tokens_or_local_max_tokens':1000,
        'metrics':'Positive requested numeric contract, negative evidence-bound abstention; absent and present-distractor strata separate, method paired gains/losses, false positive abstentions, source-family balanced summaries. Pointer validity is not entailment.',
        'confirmation7_inputs_used':False,'new_expert_reviews':0,'new_accepted_benchmark_questions':0,
        'limits':'Count mutation is a synthetic source-bounded stressor and can create an unsupported premise. This does not certify clinical falsehood. Four articles support mechanism diagnosis only; no novelty or general safety claim.'},indent=2)+'\n')
    print('Frozen12development cases/24requests,4sourcefamilies;0reader calls')


if __name__=='__main__':main()