Download tasks/P162/evaluation/score_engine.py from xiaojie06/DrugResearchBench: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/xiaojie06/DrugResearchBench/resolve/main/tasks/P162/evaluation/score_engine.py
- Command line
-
hf download hf://xiaojie06/DrugResearchBench/tasks/P162/evaluation/score_engine.py
-
curl -L -o score_engine.py https://huggingface.co/xiaojie06/DrugResearchBench/resolve/main/tasks/P162/evaluation/score_engine.py
16.8 kB
| """Scientific judge functions extracted verbatim from the archived per-paper controller.""" | |
| import json, math, hashlib, re | |
| from pathlib import Path | |
| from drb import load as read_json, sha as file_hash, require, within | |
| def safe_path(root,name,must_exist=False): | |
| p=within(Path(root),name) | |
| require(not must_exist or p.exists(),"Missing evidence") | |
| return p | |
| MODES = ('sealed', 'original', 'hidden') | |
| ORIGINAL_MODES = ('sealed', 'original') | |
| def compare_values(actual, expected, atol=0., rtol=0., path='$'): | |
| """Compare required scientific fields, retaining list order and finite numbers. | |
| Additional dict annotations are permitted. Booleans are not numeric 0/1. | |
| Diagnostics deliberately omit expected hidden fixture values. | |
| """ | |
| require(isinstance(atol, (int, float)) and not isinstance(atol, bool) and | |
| math.isfinite(atol) and atol >= 0, 'Invalid absolute tolerance') | |
| require(isinstance(rtol, (int, float)) and not isinstance(rtol, bool) and | |
| math.isfinite(rtol) and rtol >= 0, 'Invalid relative tolerance') | |
| if isinstance(expected, dict): | |
| if not isinstance(actual, dict): | |
| return [path + ': scientific object required'] | |
| errors = [] | |
| for key, value in expected.items(): | |
| child = path + '.' + str(key) | |
| errors.extend(compare_values(actual[key], value, atol, rtol, child) | |
| if key in actual else [child + ': missing scientific field']) | |
| return errors | |
| if isinstance(expected, list): | |
| if not isinstance(actual, list) or len(actual) != len(expected): | |
| return [path + ': scientific array type/length mismatch'] | |
| return [error for i, value in enumerate(expected) | |
| for error in compare_values(actual[i], value, atol, rtol, path + '[' + str(i) + ']')] | |
| if isinstance(expected, bool): | |
| return [] if type(actual) is bool and actual == expected else [path + ': boolean mismatch'] | |
| if isinstance(expected, (int, float)): | |
| if not math.isfinite(expected): | |
| return [path + ': non-finite reference; independent review required'] | |
| if (not isinstance(actual, (int, float)) or isinstance(actual, bool) or not math.isfinite(actual)): | |
| return [path + ': finite scientific number required'] | |
| return [] if abs(actual - expected) <= atol + rtol * abs(expected) else [path + ': numeric tolerance exceeded'] | |
| if expected is None: | |
| return [] if actual is None else [path + ': expected an undefined scientific value'] | |
| return [] if type(actual) is type(expected) and actual == expected else [path + ': scientific value mismatch'] | |
| def rubric_claims(rubric): | |
| claims = rubric['claims'] | |
| require(len({c['id'] for c in claims}) == len(claims), 'Repeated frozen criterion') | |
| require(all(isinstance(c.get('unit_id'), str) and c['unit_id'].strip() for c in claims), | |
| 'Every frozen criterion needs a scientific unit_id before inference') | |
| require(all(c['category'] in {'original_results', 'method_rules'} for c in claims), 'Unknown score category') | |
| require(all(isinstance(c['weight'], (int, float)) and not isinstance(c['weight'], bool) | |
| and math.isfinite(c['weight']) and c['weight'] > 0 for c in claims), 'Invalid frozen weight') | |
| for category, maximum in [('original_results', 90), ('method_rules', 10)]: | |
| require(math.isclose(sum(c['weight'] for c in claims if c['category'] == category), maximum, | |
| rel_tol=0., abs_tol=1e-7), 'Frozen 90+10 denominator changed') | |
| return claims | |
| def _evidence_exists(folder, names): | |
| if not isinstance(names, list) or not names: | |
| return False | |
| try: | |
| receipt=read_json(folder/'receipt.json') if (folder/'receipt.json').is_file() else None | |
| record=read_json(folder/'server_evidence.json') if (folder/'server_evidence.json').is_file() else None | |
| if receipt is None or record is None: | |
| return all(safe_path(folder/'artifacts', name, True).is_file() for name in names) | |
| require(record['verification']['all_output_bytes_verified'] is True and record['complete_server_outputs']==receipt['outputs'],'Unverified server evidence') | |
| return all(safe_path(folder/'artifacts',name,False) and name in receipt['outputs'] | |
| and (name in record['local_copies'] or name in record['server_only_outputs']) for name in names) | |
| except (ValueError, TypeError, OSError): | |
| return False | |
| def _classification(ref, reason): | |
| if ref.get('status') != 'qualified': | |
| return 'material_or_original_condition_gap' | |
| text = reason.lower() | |
| if any(x in text for x in ['source conflict', 'mismatch; unavailable', 'canonicalcohortbinding unresolved']): | |
| return 'original_source_or_cohort_difference' | |
| return 'scientific_result_not_demonstrated' | |
| def scientific_caps(rubric, originals, methods, references): | |
| """All frozen claims receive a numeric ceiling; no global execution gate.""" | |
| claims = rubric_claims(rubric) | |
| results = [] | |
| for claim in claims: | |
| cid = claim['id'] | |
| if claim['category'] == 'method_rules': | |
| checks = methods[cid] | |
| passed = all(checks[mode]['passed'] for mode in MODES) | |
| bounds=[claim.get('max_verified_fraction',1.)]+[checks[m].get('fraction_cap',1.) for m in MODES] | |
| require(all(isinstance(v,(int,float)) and not isinstance(v,bool) and math.isfinite(v) and 0<=v<=1 for v in bounds),'Invalid private method credit bound') | |
| fraction = min(bounds) if passed else 0. | |
| reasons = ['Same-schema original and private new-value scientific computations independently verified'] if passed else [mode + ': ' + checks[mode]['reason'] for mode in MODES if not checks[mode]['passed']] | |
| classification = 'scientific_method_verified' if passed else 'scientific_method_error_or_missing' | |
| evidence = [mode+'/artifacts/'+p for mode in MODES for p in checks[mode].get('evidence',[])] | |
| else: | |
| ref = references[cid] | |
| checks = originals[cid] | |
| qualified = ref.get('status') == 'qualified' and all(checks[m]['passed'] for m in ORIGINAL_MODES) | |
| bound = float(claim.get('max_verified_fraction', 1.)) | |
| for v in [ref.get('fraction_cap', 1.)] + [checks[m].get('fraction_cap', 1.) for m in ORIGINAL_MODES]: | |
| require(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and 0 <= v <= 1, | |
| 'Invalid scientific partial-credit limit') | |
| bound = min(bound, v) | |
| require(0 <= bound <= 1, 'Invalid public partial-credit limit') | |
| fraction = bound if qualified else 0. | |
| reasons = [ref.get('reason', '')] + [mode + ': ' + checks[mode]['reason'] for mode in ORIGINAL_MODES if not checks[mode]['passed']] | |
| unresolved_reference = any(checks[m].get('reference_evaluation_error') for m in ORIGINAL_MODES) | |
| classification = ('verified_own_method_result' if fraction == 1. else 'verified_predeclared_partial_own_method_result') if qualified else ( | |
| 'reference_evaluation_unresolved' if unresolved_reference and ref.get('status') == 'qualified' else _classification(ref, ' '.join(reasons))) | |
| evidence = [mode + '/artifacts/' + p for mode in ORIGINAL_MODES for p in checks[mode].get('evidence', [])] | |
| results.append(dict(id=cid, category=claim['category'], unit_id=claim.get('unit_id'), max_points=claim['weight'], | |
| verified_fraction_cap=fraction, verified_points_cap=claim['weight'] * fraction, | |
| classification=classification, reason='; '.join(x for x in reasons if x), | |
| evidence_files=evidence or ['verification/checks.json'])) | |
| available_points=sum(c['weight']*min(c.get('max_verified_fraction',1.),references[c['id']].get('fraction_cap',1.)) | |
| for c in claims if c['category']=='original_results' and references[c['id']].get('status')=='qualified') | |
| available_points+=sum(c['weight']*c.get('max_verified_fraction',1.) for c in claims if c['category']=='method_rules') | |
| return dict(claims=results, maximum_demonstrated_points=sum(c['verified_points_cap'] for c in results), | |
| available_points=available_points,condition_missing_points=100.-available_points, | |
| condition_missing_is_not_observed_candidate_mismatch=True, | |
| own_method_results_maximum=90, method_rules_maximum=10, denominator=100, | |
| failed_execution_is_not_global_zero=True) | |
| def evaluate_checks(rubric, references, bundles, directories): | |
| from .b67_current_measurement_mapping_20261109_v1 import bound_directory_evidence | |
| bundles = bound_directory_evidence(bundles, directories) | |
| """Convert private oracle results and actual artifacts into row-local checks.""" | |
| originals, methods, source_differences = {}, {}, [] | |
| for claim in rubric_claims(rubric): | |
| cid = claim['id']; atol = claim.get('atol', 0.); rtol = claim.get('rtol', 0.) | |
| if claim['category'] == 'method_rules': | |
| methods[cid] = {} | |
| for mode in MODES: | |
| observed=bundles[mode]['method_checks'].get(cid) | |
| require(isinstance(observed,dict),'Independent method check missing: '+cid) | |
| errors=[] | |
| if observed.get('passed',observed.get('qualified')) is not True:errors.append(observed.get('reason','Method result not independently demonstrated')) | |
| if not _evidence_exists(directories[mode],observed.get('evidence')):errors.append('No input-bound scientific output evidence') | |
| if observed.get('reference_error') or bundles[mode].get('reference_evaluation_error'):errors.append('Reference evaluation unresolved; not proven algorithm error') | |
| methods[cid][mode] = dict(passed=not errors, reason='; '.join(errors) or 'Scientific fields match independently computed inputs', | |
| evidence=observed.get('evidence',[]),fraction_cap=observed.get('fraction_cap',1.), | |
| reference_evaluation_error=bool(observed.get('reference_error') or observed.get('evaluation_error') or bundles[mode].get('reference_evaluation_error'))) | |
| continue | |
| require(cid in references, 'Original frozen scientific reference missing') | |
| ref = references[cid] | |
| originals[cid] = {} | |
| for mode in ORIGINAL_MODES: | |
| observed = bundles[mode]['original_checks'].get(cid) | |
| require(isinstance(observed, dict), 'Independent original criterion missing') | |
| evaluator_error = bool(observed.get('evaluation_error') or observed.get('reference_error') or bundles[mode].get('evaluation_error') or bundles[mode].get('reference_evaluation_error')) | |
| reasons = [] | |
| if evaluator_error: | |
| reasons.append('Trusted reference evaluation error; scientific qualification unresolved, not an observed solver algorithm error') | |
| if ref.get('status') != 'qualified': | |
| reasons.append(ref.get('reason', 'Original raw materials/conditions unavailable')) | |
| if observed.get('qualified') is not True: | |
| reasons.append(observed.get('reason', 'Independent per-record scientific evidence not verified')) | |
| if not _evidence_exists(directories[mode], observed.get('evidence')): | |
| reasons.append('No valid independently byte-bound scientific evidence files') | |
| if observed.get('qualified') is True and ref.get('status') == 'qualified' and ref.get('comparison') != 'reference_evaluated_predicate': | |
| reasons += compare_values(observed.get('value'), ref.get('expected'), ref.get('atol', atol), ref.get('rtol', rtol)) | |
| originals[cid][mode] = dict(passed=not reasons, qualified=observed.get('qualified') is True, | |
| reason='; '.join(reasons) or observed.get('reason', 'Independent original result matched'), | |
| evidence=observed.get('evidence', []), fraction_cap=observed.get('fraction_cap', 1.), | |
| reference_evaluation_error=evaluator_error, | |
| data_derived_value=observed.get('value')) | |
| if claim.get('max_verified_fraction', 1.) < 1 or ref.get('fraction_cap', 1.) < 1 or ref.get('status') != 'qualified': | |
| source_differences.append(dict(id=cid, reason=ref.get('reason', ''), classification=_classification(ref, ref.get('reason', '')), | |
| frozen_fraction_cap=min(claim.get('max_verified_fraction', 1.), ref.get('fraction_cap', 1.)))) | |
| elif any(v['qualified'] and not v['passed'] for v in originals[cid].values()): | |
| source_differences.append(dict(id=cid, classification='observed_original_numeric_or_evidence_difference', | |
| reason='Independent observations differ from the frozen published target or evidence conditions; this record alone does not decide whether the cause is method or original-source ambiguity.', | |
| affected_modes=[m for m in ORIGINAL_MODES if originals[cid][m]['qualified'] and not originals[cid][m]['passed']])) | |
| return dict(original_criterion_checks=originals, method_criterion_checks=methods, | |
| original_material_and_source_differences=source_differences, | |
| reference_evaluation_errors=[dict(mode=m, classification='reference_evaluation_unresolved', | |
| affected_ids=[cid for cid, rows in originals.items() if rows[m].get('reference_evaluation_error')], | |
| algorithm_error_claim_supported=False) | |
| for m in ORIGINAL_MODES if any(rows[m].get('reference_evaluation_error') for rows in originals.values())], | |
| scientific_progress_metrics={m:bundles[m].get('progress_metrics',{}) for m in MODES}, | |
| rubric_hidden_from_solver=True,private_test_cases_hidden=True, | |
| original_reproduction_modes=list(ORIGINAL_MODES),method_validation_modes=list(MODES)) | |
| def validate_assessment(assessment, rubric, caps, evidence_allowed=None): | |
| claims = rubric_claims(rubric) | |
| rows = assessment.get('assessments') | |
| require(isinstance(rows, list) and len(rows) == len(claims) and | |
| {r.get('id') for r in rows} == {c['id'] for c in claims}, 'Final judge criterion coverage incomplete or duplicated') | |
| bounds = {c['id']: c for c in caps['claims']} | |
| for row in rows: | |
| bound = bounds[row['id']] | |
| fraction, points = row.get('verified_fraction'), row.get('points') | |
| require(isinstance(fraction, (int, float)) and not isinstance(fraction, bool) and math.isfinite(fraction) | |
| and 0 <= fraction <= bound['verified_fraction_cap'] + 1e-9, 'Judge exceeds independently verified scientific credit') | |
| require(isinstance(points, (int, float)) and not isinstance(points, bool) and math.isfinite(points) | |
| and math.isclose(points, bound['max_points'] * fraction, rel_tol=0., abs_tol=1e-7), 'Judge weighted score mismatch') | |
| require(isinstance(row.get('reason'), str) and row['reason'].strip() and | |
| isinstance(row.get('classification'), str) and row['classification'].strip(), 'Judge lacks scientific explanation') | |
| require(isinstance(row.get('evidence_files'), list) and row['evidence_files'] | |
| and all(isinstance(p, str) for p in row['evidence_files']), 'Judge lacks own-evidence citations') | |
| if evidence_allowed is not None: | |
| require(set(row['evidence_files']) <= evidence_allowed, 'Judge cited unavailable or other-paper evidence') | |
| require(type(assessment.get('full_paper_reproduced')) is bool, 'Full-paper conclusion required') | |
| require(assessment['full_paper_reproduced'] is False, 'Supplied-condition progress is not historical whole-paper reproduction') | |
| require(isinstance(assessment.get('summary'), str) and assessment['summary'].strip(), 'Final scientific summary required') | |
| return rows | |
| def require_healthy_reference(checks): | |
| """Curator measurement errors stay pending; they are not candidate zeros.""" | |
| require(not checks.get('reference_evaluation_errors'), | |
| 'Trusted result evaluator failed; retain independent artifacts and repair measurement before final judgment') | |
| for cid, modes in checks.get('method_criterion_checks', {}).items(): | |
| require(not any(r.get('reference_evaluation_error') for r in modes.values()), | |
| 'Trusted method evaluator failed for '+cid+'; no final zero from an evaluator exception') | |