"ameliorat", "counteract", "normoglycemi", "reduc", "decreas", "inhibit", "attenuat", "block", "abolish", "abrogat", "suppress", "diminish", "lower", "higher", "greater", "elevat", "upregulat", "extended", "delay", "spar", ) ): direction = "Protective_or_Improved" else: direction = "Neutral_or_NonInferior" return direction, penalty_observed def _pvalue_tokens(sentence: str) -> list[tuple[str, Decimal]]: """Typed source operands. A P< bound is never an observed equality.""" sentence = re.sub(r"(\d)\u00b7(\d)", r"\1.\2", sentence or "") out = [] token = r"(?:\d+(?:\.\d*)?|\.\d+)(?:\s*[×xX*]\s*10\s*\^?\s*[-−]?\d+|[eE][-+−]?\d+)?" for m in re.finditer(rf"(?=|[=<>≤≥])\s*({token})(?![\d.])", sentence): raw = re.sub(r"\s+", "", m.group(2)).replace("−", "-") try: if re.search(r"[×xX*]", raw): base, exponent = re.split(r"[×xX*]10\^?", raw) val = Decimal(base) * (Decimal(10) ** int(exponent)) else: val = Decimal(raw) # A positive source probability must not become exact p=0 merely # because its value falls below the binary64 JSON numeric range. if val.is_finite() and Decimal(0) <= val <= Decimal(1) and (val == 0 or float(val) > 0): out.append(({"≤": "<=", "≥": ">="}.get(m.group(1), m.group(1)), val)) except (DecimalException, ValueError, OverflowError): continue return out def parse_pvalue_and_n(sentence: str) -> tuple[float | None, int | None]: ps = _pvalue_tokens(sentence) pval = float(ps[0][1]) if len(ps) == 1 and ps[0][0] == "=" else None n_val = None m_n = re.search(r"\bn\s*=\s*(\d+(?:,\d{3})*)\b", sentence, flags=re.IGNORECASE) if m_n: try: cand_n = int(m_n.group(1).replace(",", "")) if 0 < cand_n <= 100000 and _num_in_quote(cand_n, sentence, "treatment_n"): n_val = cand_n except Exception: n_val = None return pval, n_val LEX_H = ( "specific lysis", "cytotoxicity", "apoptosis", "cell death", "apoptotic", "necrotic core", "blood glucose", "hyperglycemia", "amyloid area", "thioflavin", ) LEX_P = ( "survival", "viability", "gsis", "stimulation index", "c-peptide", "insulin secretion", "normoglycemia", "vascular density", ) EXTRA_H = ( "lysis", "killing", "cytolysis", "cytolytic", "degranulation", "cd107", "rejection", "insulitis", "infiltrat", "inflammat", "ifn-γ secretion", "ifn-gamma secretion", "t cell proliferation", "t-cell proliferation", "proliferation of t", "phagocyt", "fibrosis", "necrosis", "er stress", "perforin", "granzyme", "granulysin", "tnf+", ) class _NumericEvidenceDomainError(ValueError): pass class _NumericEvidenceNotationError(ValueError): pass class _NumericEvidenceBoundedError(ValueError): pass # Qualifiers are attached to an operand, never searched sentence-wide: a # separate p-value inequality must not invalidate an exact measured contrast. _NUMERIC_QUALIFIER = ( r"(?:[<>≤≥~≈]=?\s*|\b(?:at\s+least|at\s+most|more\s+than|less\s+than|" r"greater\s+than|fewer\s+than|up\s+to|nearly|almost|over|under|" r"approximately|approx\.?|about|around|roughly)\s+)" ) def _finite_numeric_evidence(value: Any, label: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)): raise _NumericEvidenceDomainError(f"{label} must be a finite real number") try: number = float(value) except (OverflowError, ValueError) as exc: raise _NumericEvidenceDomainError(f"{label} is outside the finite numeric domain") from exc if not math.isfinite(number): raise _NumericEvidenceDomainError(f"{label} must be a finite real number") return number def _log_response_ratio(treatment: Any, control: Any) -> float: treatment = _finite_numeric_evidence(treatment, "Treatment mean") control = _finite_numeric_evidence(control, "Control mean") if treatment <= 0 or control <= 0: raise _NumericEvidenceDomainError("Log response ratios require positive operands") # Subtraction of nearly equal logarithms loses a small, nonzero contrast. # Nearby positive binary64 operands have a safe finite difference, while # far ratios use separate logs so neither division nor subtraction overflows. if min(treatment, control) >= max(treatment, control) / 2.0: return math.log1p((treatment - control) / control) return math.log(treatment) - math.log(control) def _source_numeric_operand(token: str) -> float: token = token.replace(",", "") number = _finite_numeric_evidence(float(token), "Source numeric operand") if number == 0 and Decimal(token) != 0: raise _NumericEvidenceDomainError("Source numeric operand underflows the finite numeric domain") return number def _source_numeric_match(match: re.Match[str], group: int, *, exact: bool = False) -> float: """Reject regex captures that are only a suffix of a source operand. Source eligibility, arm assignment and endpoint orientation are unchanged. The unsigned-decimal grammar must not turn .5 into 5, -20 into 20, or the exponent in 1e-2 into a twofold change. +/- and +- remain dispersion markers. Exact paired fields cannot represent a qualified bound or approximation; descriptive duration parsing keeps its existing censoring metadata path. """ prefix = match.string[:match.start(group)] previous = prefix.rstrip() bad_immediate = bool(prefix and prefix[-1] in "0123456789.,eE") bad_sign = bool(previous and previous[-1] in "+-−–—" and not previous.endswith(("+/-", "+-"))) bad_grouping = bool(re.search(r"\d_+$", prefix)) or bool( re.search(r"\d[^\S\r\n]+$", prefix) and re.fullmatch(r"\d{3}(?:,\d{3})*(?:\.\d+)?", match.group(group)) ) suffix = match.string[match.end(group):] if bad_immediate or bad_sign or bad_grouping or re.match(r"[eE][+\-−]?\d", suffix): raise _NumericEvidenceNotationError("Source operand uses unsupported numeric notation") if exact and re.search(_NUMERIC_QUALIFIER + r"$", prefix, flags=re.IGNORECASE): raise _NumericEvidenceBoundedError("A qualified operand is not an exact paired measurement") return _source_numeric_operand(match.group(group)) def _v063_parse_quantitative_numbers( sentence: str, direction: str ) -> tuple[float | None, float | None, float | None, float | None, str | None, float | None]: """Preserves exact v0.6.3 candidate sentence sort priority tuple so all 2,794 effect_ids and V-17/V-18 remain invariant.""" sl = sentence.lower() has_h = any(k in sl for k in LEX_H) has_p = any(k in sl for k in LEX_P) orient_sign = -1.0 if (has_h and not has_p) else (1.0 if (has_p and not has_h) else 0.0) is_protocol = any( k in sl for k in ( "stimulated with", "incubated with", "cultured with", "treated with", "supplemented with", "concentration", "physiological", "monitored", "quantified", "ranging from", "between ", "heatmap", "depicting", "log2 fold", "not functional", "triglyceride", ) ) m_pair_sd = re.search( r"(from\s+)?(\d+\.?\d*)\s*(?:±|\+/-|\+-)\s*(\d+\.?\d*)\s*(%|fold|mg/dL|ng/mL|pmol|days|weeks|mmHg|µm|um)?\s*" r"(vs\.?|versus|compared\s+to|compared\s+with|to)\s*" r"(\d+\.?\d*)\s*(?:±|\+/-|\+-)\s*(\d+\.?\d*)\s*(%|fold|mg/dL|ng/mL|pmol|days|weeks|mmHg|µm|um)?", sentence, flags=re.IGNORECASE, ) if m_pair_sd: has_from = bool(m_pair_sd.group(1)) v1, sd1, u1 = _source_numeric_operand(m_pair_sd.group(2)), _source_numeric_operand(m_pair_sd.group(3)), m_pair_sd.group(4) sep = m_pair_sd.group(5).lower() v2, sd2, u2 = _source_numeric_operand(m_pair_sd.group(6)), _source_numeric_operand(m_pair_sd.group(7)), m_pair_sd.group(8) unit = u1 or u2 or "reported_units" if sep == "to" and not has_from: return None, None, None, None, unit, None t_mean, t_sd, c_mean, c_sd = (v2, sd2, v1, sd1) if has_from else (v1, sd1, v2, sd2) if has_h and has_p: return None, None, None, None, "quarantined_mixed_polarity_endpoints", None if t_mean > 0 and c_mean > 0 and orient_sign != 0.0 and not is_protocol: lrr = round(_log_response_ratio(t_mean, c_mean), 4) if (direction == "Protective_or_Improved" and lrr * orient_sign <= 0) or ( direction == "Deleterious_or_Impaired" and lrr * orient_sign >= 0 ): return None, None, None, None, "quarantined_ambiguous_numeric", None return t_mean, t_sd, c_mean, c_sd, unit, lrr return None, None, None, None, unit, None