File size: 17,047 Bytes
198cde1 | 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 | """
PhD Research OS v2.0 — Integration Tests
==========================================
Tests the complete pipeline: Layer 0 → Layer 2 → Layer 4 → Layer 5
"""
import os
import sys
import json
import tempfile
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from phd_research_os_v2.core.database import (
init_db, get_db, get_stats, get_state, set_state,
to_fixed, from_fixed, gen_id, now_iso
)
from phd_research_os_v2.layer0.parser import (
StructuralParser, detect_section, classify_region_type,
extract_cross_references, score_parse_quality
)
from phd_research_os_v2.layer2.extractor import (
QualifiedExtractor, SECTION_MODIFIERS, VALID_TAGS
)
from phd_research_os_v2.layer4.graph import KnowledgeGraph
from phd_research_os_v2.layer5.scorer import CalibratedScorer
TEST_DB = "test_v2_integration.db"
SAMPLE_PAPER = """Abstract
We investigated graphene field-effect transistor (GFET) biosensors for cardiac troponin detection.
Introduction
Cardiac troponin I (cTnI) is a gold-standard biomarker for myocardial infarction. Current detection methods require laboratory equipment. Point-of-care biosensors could enable faster diagnosis.
Methods
GFETs were fabricated using CVD graphene on SiO2/Si substrates. Aptamer probes were immobilized via pyrene linkers. Measurements were performed in 10 mM PBS at room temperature.
Results
The Dirac point shifted by 45 ± 3 mV upon binding of 1 pM cTnI (n=5, p<0.001). The limit of detection was 0.8 fM using the 3-sigma method. Sensitivity was not maintained at physiological ionic strength (150 mM), showing a 10-fold reduction. We observed no significant change in selectivity when tested against troponin T.
Discussion
These results suggest that aptamer-functionalized GFETs can achieve clinically relevant sensitivity in buffer conditions. However, the ionic strength dependence indicates that a desalting step may be necessary for clinical translation. We hypothesize that PEG spacers could mitigate Debye screening effects.
Conclusion
GFET biosensors show promise for cardiac biomarker detection but require further optimization for physiological conditions.
"""
@pytest.fixture(autouse=True)
def setup_teardown():
init_db(TEST_DB)
yield
for suffix in ["", "-wal", "-shm"]:
p = TEST_DB + suffix
if os.path.exists(p):
os.remove(p)
# ============================================================
# Database Tests
# ============================================================
def test_database_init():
stats = get_stats(TEST_DB)
assert isinstance(stats, dict)
for table in ["documents", "regions", "claims", "graph_nodes"]:
assert table in stats
def test_system_state():
assert get_state(TEST_DB, "schema_version") == "2.0"
set_state(TEST_DB, "test_key", "test_value")
assert get_state(TEST_DB, "test_key") == "test_value"
def test_fixed_point_math():
assert to_fixed(0.85) == 850
assert from_fixed(850) == 0.85
assert to_fixed(1.0) == 1000
assert to_fixed(0.0) == 0
# ============================================================
# Layer 0: Structural Parser Tests
# ============================================================
def test_section_detection():
assert detect_section("Abstract") == "abstract"
assert detect_section("2.1 Methods") == "methods"
assert detect_section("Results and Discussion") == "results_discussion"
assert detect_section("3. Results") == "results"
assert detect_section("References") == "references"
assert detect_section("Random paragraph text") is None
def test_region_classification():
assert classify_region_type("Table 1: Results summary") == "caption"
assert classify_region_type("Figure 3: Scatter plot of sensitivity vs ionic strength") == "caption"
assert classify_region_type("This is a normal paragraph about the experiment.") == "body_text"
assert classify_region_type("METHODS") == "header"
def test_cross_reference_extraction():
refs = extract_cross_references("As shown in Figure 3 and Table 2, the results (Eq. 4) confirm [32].")
types = [r["ref_type"] for r in refs]
assert "figure" in types
assert "table" in types
assert "citation" in types
def test_parse_quality_scoring():
good_text = "The limit of detection was determined to be 0.8 fM using the 3-sigma method."
bad_text = "â–¡â–¡ garbled text â– â– â– with bad â–¡ characters"
empty_text = ""
assert score_parse_quality(good_text, "fitz") > 700
assert score_parse_quality(bad_text, "fitz") < 700
assert score_parse_quality(empty_text, "fitz") == 0
def test_ingest_text_file():
# Create a temporary text file
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(SAMPLE_PAPER)
f.flush()
temp_path = f.name
try:
parser = StructuralParser(TEST_DB)
result = parser.ingest_document(temp_path, doc_type="main", title="Test Paper")
assert result.get("doc_id") is not None
assert result["total_regions"] > 0
assert result["parse_method"] == "text"
assert "results" in result.get("sections_found", [])
finally:
os.unlink(temp_path)
def test_section_aware_chunking():
# Ingest the sample paper
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(SAMPLE_PAPER)
temp_path = f.name
try:
parser = StructuralParser(TEST_DB)
result = parser.ingest_document(temp_path)
doc_id = result["doc_id"]
chunks = parser.get_section_chunks(doc_id)
assert len(chunks) > 0
# Verify chunks have section labels
sections = [c["section"] for c in chunks]
assert any(s is not None for s in sections)
finally:
os.unlink(temp_path)
# ============================================================
# Layer 2: Extraction Tests
# ============================================================
def test_extract_from_text_chunk():
extractor = QualifiedExtractor(TEST_DB)
chunk = {
"text": "The LOD was 0.8 fM (n=5, p<0.001). Sensitivity may decrease at higher ionic strength. We hypothesize that PEG spacers could help.",
"section": "results",
"page": 1,
"min_confidence": 900,
"doc_id": None,
"region_ids": [],
}
claims = extractor.extract_from_chunk(chunk)
assert len(claims) > 0
for claim in claims:
assert claim["epistemic_tag"] in VALID_TAGS
assert 0 <= claim["composite_confidence"] <= 1000
assert claim["status"] in ["Complete", "Incomplete"]
def test_section_modifier_applied():
extractor = QualifiedExtractor(TEST_DB)
# Results section should have modifier 1000
chunk_results = {
"text": "The measured value was 0.8 fM with p<0.001.",
"section": "results", "page": 1, "min_confidence": 900,
"doc_id": None, "region_ids": [],
}
claims_results = extractor.extract_from_chunk(chunk_results)
# Abstract section should have modifier 700
chunk_abstract = {
"text": "The measured value was 0.8 fM with p<0.001.",
"section": "abstract", "page": 1, "min_confidence": 900,
"doc_id": None, "region_ids": [],
}
claims_abstract = extractor.extract_from_chunk(chunk_abstract)
if claims_results and claims_abstract:
# Abstract claims should have lower confidence due to section modifier
assert claims_abstract[0]["composite_confidence"] <= claims_results[0]["composite_confidence"]
def test_abstract_fact_downgraded_to_interpretation():
"""Abstract claims tagged as Fact should be forced to Interpretation."""
extractor = QualifiedExtractor(TEST_DB)
chunk = {
"text": "We measured the LOD at 0.8 fM, achieving clinical sensitivity.",
"section": "abstract", "page": 1, "min_confidence": 900,
"doc_id": None, "region_ids": [],
}
claims = extractor.extract_from_chunk(chunk)
# Mock extractor will likely tag "measured" as Fact,
# but abstract section should force it to Interpretation
for claim in claims:
if claim["source_section"] == "abstract":
# The extractor should have downgraded Fact → Interpretation
# (this tests the Epistemic Separation Engine)
assert claim["epistemic_tag"] in VALID_TAGS
def test_null_result_detection():
extractor = QualifiedExtractor(TEST_DB)
chunk = {
"text": "There was no significant difference between treatment and control groups (p=0.43, N=200).",
"section": "results", "page": 1, "min_confidence": 900,
"doc_id": None, "region_ids": [],
}
claims = extractor.extract_from_chunk(chunk)
# Should detect null result
null_claims = [c for c in claims if c["is_null_result"]]
assert len(null_claims) > 0 or len(claims) > 0 # At minimum, something was extracted
def test_qualifier_extraction():
extractor = QualifiedExtractor(TEST_DB)
chunk = {
"text": "Results suggest that the effect may be temperature-dependent under these conditions.",
"section": "discussion", "page": 1, "min_confidence": 900,
"doc_id": None, "region_ids": [],
}
claims = extractor.extract_from_chunk(chunk)
# Should detect hedging qualifiers
for claim in claims:
if claim.get("qualifiers"):
assert any(q in ["may", "suggests", "under these conditions"] for q in claim["qualifiers"])
def test_full_document_extraction():
# Ingest then extract
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(SAMPLE_PAPER)
temp_path = f.name
try:
parser = StructuralParser(TEST_DB)
result = parser.ingest_document(temp_path, title="Integration Test Paper")
doc_id = result["doc_id"]
extractor = QualifiedExtractor(TEST_DB)
extract_result = extractor.extract_from_document(doc_id)
assert extract_result["total_claims"] > 0
assert "results" in extract_result.get("section_distribution", {}) or extract_result["total_claims"] > 0
finally:
os.unlink(temp_path)
# ============================================================
# Layer 4: Knowledge Graph Tests
# ============================================================
def test_graph_add_node():
graph = KnowledgeGraph(TEST_DB)
graph.add_claim_node("CLM_TEST001", "Test claim about graphene", {"tag": "Fact"})
stats = graph.get_stats()
assert stats["total_nodes"] >= 1
def test_graph_add_edge():
graph = KnowledgeGraph(TEST_DB)
graph.add_claim_node("CLM_A", "Claim A")
graph.add_claim_node("CLM_B", "Claim B")
edge_id = graph.add_edge("CLM_A", "CLM_B", "supports", 0.85, ["10.1234/test"])
assert edge_id.startswith("EDGE_")
stats = graph.get_stats()
assert stats["total_edges"] >= 1
def test_graph_neighbors():
graph = KnowledgeGraph(TEST_DB)
graph.add_claim_node("CLM_C", "Claim C")
graph.add_claim_node("CLM_D", "Claim D")
graph.add_claim_node("CLM_E", "Claim E")
graph.add_edge("CLM_C", "CLM_D", "supports", 0.9)
graph.add_edge("CLM_C", "CLM_E", "refutes", 0.7)
neighbors = graph.get_neighbors("CLM_C")
assert len(neighbors) >= 2
def test_graph_inferred_edges_hidden_by_default():
graph = KnowledgeGraph(TEST_DB)
graph.add_claim_node("CLM_F", "Claim F")
graph.add_claim_node("CLM_G", "Claim G")
graph.add_edge("CLM_F", "CLM_G", "investigative_hypothesis", 0.4, is_inferred=True)
# Default: inferred edges hidden
neighbors = graph.get_neighbors("CLM_F", include_inferred=False)
inferred = [n for n in neighbors if n.get("is_inferred")]
assert len(inferred) == 0
# Explicit: include inferred
all_neighbors = graph.get_neighbors("CLM_F", include_inferred=True)
assert len(all_neighbors) >= 1
# ============================================================
# Layer 5: Scoring Tests
# ============================================================
def test_scorer_basic():
scorer = CalibratedScorer(TEST_DB)
claim = {
"evidence_strength": 900, # 0.9
"source_section": "results",
"missing_fields": "[]",
"qualifiers": "[]",
"parse_confidence": 950,
"is_null_result": False,
"is_inherited_citation": False,
}
source = {"study_type": "direct_physical_measurement", "journal_tier": 1}
scores = scorer.score_claim(claim, source)
assert "evidence_quality" in scores
assert "truth_likelihood" in scores
assert "qualifier_strength_score" in scores
assert "composite_confidence" in scores
assert 0 <= scores["evidence_quality"] <= 1000
assert 0 <= scores["composite_confidence"] <= 1000
def test_scorer_section_modifier():
scorer = CalibratedScorer(TEST_DB)
claim_results = {
"evidence_strength": 800, "source_section": "results",
"missing_fields": "[]", "qualifiers": "[]",
"parse_confidence": 1000, "is_null_result": False, "is_inherited_citation": False,
}
claim_abstract = {
"evidence_strength": 800, "source_section": "abstract",
"missing_fields": "[]", "qualifiers": "[]",
"parse_confidence": 1000, "is_null_result": False, "is_inherited_citation": False,
}
source = {"study_type": "in_vivo", "journal_tier": 1}
scores_r = scorer.score_claim(claim_results, source)
scores_a = scorer.score_claim(claim_abstract, source)
# Results should score higher than Abstract (section modifier)
assert scores_r["evidence_quality"] > scores_a["evidence_quality"]
def test_scorer_null_result_penalty():
scorer = CalibratedScorer(TEST_DB)
normal = {"evidence_strength": 800, "source_section": "results",
"missing_fields": "[]", "qualifiers": "[]",
"parse_confidence": 1000, "is_null_result": False, "is_inherited_citation": False}
null = {"evidence_strength": 800, "source_section": "results",
"missing_fields": "[]", "qualifiers": "[]",
"parse_confidence": 1000, "is_null_result": True, "is_inherited_citation": False}
source = {"study_type": "in_vivo", "journal_tier": 1}
scores_normal = scorer.score_claim(normal, source)
scores_null = scorer.score_claim(null, source)
assert scores_null["truth_likelihood"] <= scores_normal["truth_likelihood"]
def test_scorer_parser_confidence_caps():
scorer = CalibratedScorer(TEST_DB)
claim = {"evidence_strength": 900, "source_section": "results",
"missing_fields": "[]", "qualifiers": "[]",
"parse_confidence": 400, # Low parser confidence
"is_null_result": False, "is_inherited_citation": False}
source = {"study_type": "in_vivo", "journal_tier": 1}
scores = scorer.score_claim(claim, source)
# Evidence quality should be capped at parser confidence (400)
assert scores["evidence_quality"] <= 400
# ============================================================
# End-to-End Integration Test
# ============================================================
def test_full_pipeline():
"""Test the complete pipeline: ingest → extract → graph → score."""
# Step 1: Ingest
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(SAMPLE_PAPER)
temp_path = f.name
try:
parser = StructuralParser(TEST_DB)
ingest_result = parser.ingest_document(temp_path, title="Full Pipeline Test")
doc_id = ingest_result["doc_id"]
assert ingest_result["total_regions"] > 0
# Step 2: Extract
extractor = QualifiedExtractor(TEST_DB)
extract_result = extractor.extract_from_document(doc_id)
assert extract_result["total_claims"] > 0
# Step 3: Build graph
graph = KnowledgeGraph(TEST_DB)
conn = get_db(TEST_DB)
claims = conn.execute("SELECT claim_id, text FROM claims WHERE source_doc_id = ?",
(doc_id,)).fetchall()
conn.close()
for c in claims:
d = dict(c)
graph.add_claim_node(d["claim_id"], d["text"])
stats = graph.get_stats()
assert stats["total_nodes"] > 0
# Step 4: Score
scorer = CalibratedScorer(TEST_DB)
count = scorer.rescore_all_claims()
assert count > 0
# Verify: claims have computed scores
conn = get_db(TEST_DB)
scored = conn.execute(
"SELECT COUNT(*) FROM claims WHERE evidence_quality IS NOT NULL"
).fetchone()[0]
conn.close()
assert scored > 0
finally:
os.unlink(temp_path)
if __name__ == "__main__":
pytest.main([__file__, "-v"])
|