"""Fidelity of one rendering of a DDR against another, item by item. `compare(ref, hyp)` lines up two `Rendered` reports and returns one item per thing printed in `ref`: the two header lines, every header field, every section text, every column header and every table cell, plus one `*_label` item per field label, section title and table title (was the label itself read right?). An item holds both strings, whether they are equal, and the character and word edit distances, so every rate in a report is a group-by over items and every error can be shown. A label that `hyp` misreads is paired by its place in the printed order, so its value is still compared. Table rows are aligned by a monotone alignment of row similarity; columns by position or, when `hyp` has a different number of columns (one merged or split), by aligning the column headers. A `ref` row or column with no partner yields its cells with `hyp` = None; a `hyp` row or column with no partner yields one `row_extra` / `col_extra` item, and a header line, field, text or table of `hyp` that no `ref` label matched one `*_extra` item. Two uses: * OCR fidelity: ref = the publisher HTML, hyp = chandra's OCR of the PDF, `equal=exact`; * render fidelity: ref = `from_xml` (what the HTML should print, built from the WITSML source), hyp = the HTML, `equal=same_value` (numbers compared as numbers; a printed sentinel or "None" is missing). """ from __future__ import annotations import math import re import numpy as np import pandas as pd from rapidfuzz import fuzz, process from rapidfuzz.distance import Levenshtein from ..names import canonical from .rendered import Rendered, Table, clean, norm_key from .xml import SENTINELS #: Header field label (`norm_key`, unit suffix removed) -> drillReport column it prints. Found by matching every #: label against every column on all 1,759 reports (agreement 1.0 for each pair below). Labels with no column #: ("wellbore type", "dia last casing", "depth at kick off mtvd") are always printed empty. FIELD_COLUMNS = { "status": "versionKind", "report creation time": "createDate", "report number": "reportNo", "days ahead/behind": "daysAhead", "operator": "operator", "rig name": "rigAlias_NPD_Name", "drilling contractor": "drillContractor", "spud date": "dTimSpud", "wellbore type": None, "elevation rkb-msl": "elevKelly", "water depth msl": "waterDepth", "tight well": "tightWell", "hpht": "hpht", "temperature": "avgTempBH", "pressure": "avgPresBH", "date well complete": "dateDrillComplete", "dist drilled": "distDrill", "penetration rate": "ropCurrent", "hole dia": "diaHole", "pressure test type": "presTestType", "formation strength": "strengthForm", "dia last casing": None, "depth at kick off mmd": "mdKickoff", "depth at kick off mtvd": None, "depth mmd": "md", "depth mtvd": "tvd", "plug back depth mmd": "mdPlugTop", "depth at formation strength mmd": "mdStrengthForm", "depth at formation strength mtvd": "tvdStrengthForm", "depth at last casing mmd": "mdCsgLast", "depth at last casing mtvd": "tvdCsgLast", } #: 0/1 flags: the expected print is N/Y. FLAGS = {"tightWell", "hpht"} TEXT_COLUMNS = {"Summary of activities (24 Hours)": "sum24Hr", "Summary of planned activities (24 Hours)": "forecast24Hr"} OPERATIONS = ("Operations", ["Start time", "End time", "End Depth mMD", "Main - Sub Activity", "State", "Remark"]) _UNIT = re.compile(r"\s*\([^)]*\)$") _ISO = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}") def field_name(label_key: str) -> str: """'hole dia (in)' and 'hole dia ()' -> 'hole dia': the publisher prints the unit only when there is a value.""" return _UNIT.sub("", label_key) # --------------------------------------------------------------------------- equality def exact(ref: str, hyp: str | None) -> bool: return hyp is not None and clean(ref) == clean(hyp) def _same_label(ref: str, hyp: str | None) -> bool: return hyp is not None and norm_key(ref) == norm_key(hyp) def _missing(s: str) -> bool: s = clean(s) if s in ("", "None"): return True try: return float(s) in SENTINELS except ValueError: return False def same_value(ref: str, hyp: str | None) -> bool: """Equal as printed values: whitespace collapsed, numbers as numbers, '', 'None' and sentinels as missing.""" if hyp is None: return False if _missing(ref) or _missing(hyp): return _missing(ref) and _missing(hyp) a, b = clean(ref), clean(hyp) if a == b: return True try: return math.isclose(float(a), float(b), rel_tol=0, abs_tol=1e-9) except ValueError: return False # --------------------------------------------------------------------------- items def _item(part: str, table: str, key: str, row: int, ref: str, hyp: str | None, equal) -> dict: r, h = clean(ref), clean(hyp or "") return {"part": part, "table": table, "key": key, "row": row, "ref": r, "hyp": None if hyp is None else h, "exact": bool(equal(ref, hyp)), "edits": Levenshtein.distance(r, h), "chars": len(r), "w_edits": Levenshtein.distance(r.split(), h.split()), "words": len(r.split())} def align(a: list[list[str]], b: list[list[str]], min_sim: float = 0.5) -> list[tuple[int, int]]: """Monotone row alignment maximising the summed gain `similarity - min_sim` of the pairs. A pair must be worth more than leaving both rows unpaired, so two mediocre pairs never outweigh one good one (a dropped row next to an invented one), and rows no more similar than `min_sim` never pair.""" if not a or not b: return [] gain = process.cdist([" | ".join(r) for r in a], [" | ".join(r) for r in b], scorer=fuzz.ratio) / 100.0 - min_sim n, m = gain.shape best = np.zeros((n + 1, m + 1)) for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): v = max(best[i + 1, j], best[i, j + 1]) if gain[i, j] > 0: v = max(v, gain[i, j] + best[i + 1, j + 1]) best[i, j] = v pairs, i, j = [], 0, 0 while i < n and j < m: if gain[i, j] > 0 and math.isclose(best[i, j], gain[i, j] + best[i + 1, j + 1]): pairs.append((i, j)) i, j = i + 1, j + 1 elif best[i + 1, j] >= best[i, j + 1]: i += 1 else: j += 1 return pairs def _extra(part: str, table: str, key: str, row: int, content: str) -> dict: return {**_item(part, table, key, row, "", content, exact), "exact": False} def _table_items(title: str, ref: Table, hyp: Table | None, equal) -> list[dict]: items = [] hyp = hyp or Table(None, []) h_header, h_rows = hyp.header, hyp.rows if ref.header and not h_header and h_rows and fuzz.ratio(" | ".join(ref.header), " | ".join(h_rows[0])) >= 80: h_header, h_rows = h_rows[0], h_rows[1:] # header printed but not recognised as one cols = ref.header or [f"c{j}" for j in range(ref.n_cols)] if ref.header and h_header and len(h_header) != len(ref.header): col = dict(align([[c] for c in ref.header], [[c] for c in h_header])) else: col = {j: j for j in range(ref.n_cols)} if ref.header: for j, name in enumerate(ref.header): hj = col.get(j) items.append(_item("colhead", title, name, -1, name, h_header[hj] if h_header and hj is not None and hj < len(h_header) else None, equal)) pairs = dict(align(ref.rows, h_rows)) for i, row in enumerate(ref.rows): other = h_rows[pairs[i]] if i in pairs else None for j, cell in enumerate(row): name, hj = (cols[j] if j < len(cols) else f"c{j}"), col.get(j) h = None if other is None or hj is None else (other[hj] if hj < len(other) else "") items.append(_item("cell", title, name, i, cell, h, equal)) for j in sorted(set(range(len(h_rows))) - set(pairs.values())): items.append(_extra("row_extra", title, "", j, " | ".join(h_rows[j]))) paired = [h_rows[j] for j in sorted(pairs.values())] width = max([len(h_header or [])] + [len(r) for r in paired]) for hj in sorted(set(range(width)) - set(col.values())): head = h_header[hj] if h_header and hj < len(h_header) else "" content = " | ".join(c for c in [head] + [r[hj] for r in paired if hj < len(r)] if c) if content: items.append(_extra("col_extra", title, head, -1, content)) return items def _matcher(ref_keys, hyp_keys): """ref key -> hyp key: the hyp key with the same `norm_key`; else, labels being printed in a fixed order, the hyp key that `align` pairs with it among the keys left over on both sides (more than half similar: "hptt" for "hpht"). A misread label still finds its value, and the label error is an item of its own.""" norm = {norm_key(k): k for k in hyp_keys} pairs = {k: norm[norm_key(k)] for k in ref_keys if norm_key(k) in norm} taken = set(pairs.values()) ref_rest = [k for k in ref_keys if k not in pairs] hyp_rest = [k for k in hyp_keys if k not in taken] for i, j in align([[norm_key(k)] for k in ref_rest], [[norm_key(k)] for k in hyp_rest]): pairs[ref_rest[i]] = hyp_rest[j] return pairs.get def _flat(v: str | Table) -> str: if isinstance(v, str): return v return " | ".join(" | ".join(r) for r in ([v.header] if v.header else []) + v.rows) def compare(ref: Rendered, hyp: Rendered, equal=exact, extras: bool = True) -> list[dict]: """Items of `ref` against `hyp`. With `extras`, every header line, field, text or table of `hyp` that no `ref` key matched is one `*_extra` item (ref "", hyp = its label and content), so text that `hyp` invents counts as insertions.""" items = [_item("header", "", k, -1, v, hyp.header.get(k), equal) for k, v in ref.header.items()] if extras: items += [_extra("header_extra", "", k, -1, v) for k, v in hyp.header.items() if k not in ref.header] for part, ref_d, hyp_d in (("field", ref.fields, hyp.fields), ("text", ref.texts, hyp.texts), ("table", ref.tables, hyp.tables)): match = _matcher(ref_d, hyp_d) used = set() for k, v in ref_d.items(): hk = match(k) used.add(hk) items.append(_item(f"{part}_label", "", k, -1, k, hk, _same_label)) if part == "field": items.append(_item("field", "", k, -1, v, None if hk is None else hyp_d[hk], equal)) elif part == "text": items.append(_item("text", k, k, -1, v, None if hk is None else hyp_d[hk], equal)) else: items += _table_items(k, v, None if hk is None else hyp_d[hk], equal) if extras: for hk in hyp_d: if hk not in used: items.append(_extra(f"{part}_extra", "", hk, -1, f"{hk}: {_flat(hyp_d[hk])}".rstrip(": "))) return items # --------------------------------------------------------------------------- what the HTML should print def _printed(v) -> str: if v is None or pd.isna(v): return "" if isinstance(v, str) and _ISO.match(v): return v[:16].replace("T", " ") if isinstance(v, float) and v.is_integer(): return str(int(v)) return str(v) def from_xml(report: dict, activities: list[dict]) -> Rendered: """The parts of a report the publisher HTML should print, built from the drillReport: header, the header fields in `FIELD_COLUMNS`, the two summaries and the Operations table. Keys are field names (unit suffix removed), so compare with `html_for_xml` of the HTML side.""" out = Rendered() out.header = {"wellbore": report["wellbore"], "period": f"{_printed(report.get('dTimStart'))} - {_printed(report.get('dTimEnd'))}"} for name, col in FIELD_COLUMNS.items(): v = report.get(col) if col else None if col in FLAGS and v is not None and not pd.isna(v): v = "Y" if int(v) == 1 else "N" out.fields[name] = _printed(v) for title, col in TEXT_COLUMNS.items(): out.texts[title] = _printed(report.get(col)) if activities: title, header = OPERATIONS out.tables[title] = Table(header, [[_printed(a.get("dTimStart"))[11:16], _printed(a.get("dTimEnd"))[11:16], _printed(a.get("md")), _printed(a.get("proprietaryCode")), _printed(a.get("state")), _printed(a.get("comments"))] for a in sorted(activities, key=lambda a: a["seq"])]) return out def html_for_xml(r: Rendered) -> Rendered: """An HTML rendering keyed like `from_xml`: field keys without the unit suffix, wellbore canonical.""" out = Rendered(header=dict(r.header), texts=r.texts, tables=r.tables, notes=r.notes) if "wellbore" in out.header: try: out.header["wellbore"] = canonical(out.header["wellbore"]) except ValueError: pass for k, v in r.fields.items(): out.fields.setdefault(field_name(k), v) return out