"""WITSML 1.4.0.0 drillReport files (the XML version of the Volve DDRs) as flat tables. One file holds one report. The report-level elements (names, aliases, wellboreInfo, statusInfo) become one row of `reports`; every repeated section becomes a table of its own (`SECTIONS`). Column names are the WITSML element names, so every value can be traced back to the schema. Two normalisations, both counted rather than silent: * the sentinels -999.99, -999.25 and -9999 become missing (counted per column in the `sentinels` table); * a measure (an element with a `uom` attribute) becomes a float. Its unit goes to the `units` table, and `parse_dir` refuses a column that is published in more than one unit. Times stay ISO strings with their UTC offset, as published; `parse_dir` adds UTC timestamps for the report period and the activities. """ from __future__ import annotations import collections import re import xml.etree.ElementTree as ET from dataclasses import dataclass, field from pathlib import Path import pandas as pd from ..names import canonical, stem NS = "{http://www.witsml.org/schemas/1series}" SENTINELS = {-999.99, -999.25, -9999.0} #: drillReport child element -> table. Everything else in a drillReport is report-level. SECTIONS = { "activity": "activities", "fluid": "fluids", "surveyStation": "surveys", "porePressure": "pore_pressure", "equipFailureInfo": "equip_failures", "gasReadingInfo": "gas_readings", "lithShowInfo": "lith_shows", "stratInfo": "strat", "casing_liner_tubing": "casings", "bitRecord": "bits", "logInfo": "log_info", "perfInfo": "perforations", "coreInfo": "cores", "wellTestInfo": "well_tests", } #: Report-level elements that are flattened into `reports` (their leaves become columns). REPORT_GROUPS = ("wellboreInfo", "statusInfo") #: Numbers published without a unit. INTS = {"reportNo", "tightWell", "hpht"} FLOATS = {"daysAhead", "daysBehind"} _FILE = re.compile(r"(.+)_(\d{4})_(\d{2})_(\d{2})") @dataclass class ParsedReport: report: dict sections: dict[str, list[dict]] = field(default_factory=lambda: collections.defaultdict(list)) units: dict[tuple[str, str], tuple[str, str]] = field(default_factory=dict) # (table, column) -> (uom, datum) sentinels: collections.Counter = field(default_factory=collections.Counter) # (table, column) -> count def _tag(e: ET.Element) -> str: return e.tag.replace(NS, "") def _slug(s: str) -> str: return re.sub(r"\W+", "_", s.strip()).strip("_") class _Flattener: def __init__(self, parsed: ParsedReport, table: str): self.parsed, self.table = parsed, table def value(self, e: ET.Element, column: str): text = (e.text or "").strip() if "uom" in e.attrib: self.parsed.units[(self.table, column)] = (e.attrib["uom"], e.attrib.get("datum", "")) if not text: return None v = float(text) if v in SENTINELS: self.parsed.sentinels[(self.table, column)] += 1 return None return v if not text: return None if _tag(e) in INTS: return int(text) if _tag(e) in FLOATS: return float(text) return text def leaves(self, elem: ET.Element, row: dict, prefix: str = "") -> dict: """Leaves of `elem` into `row`. A nested alias (name + namingSystem) becomes `_`; other nested elements prefix their leaves with their tag, numbered from the second occurrence on.""" seen = collections.Counter() for child in elem: tag = _tag(child) if len(child) == 0: self._put(row, prefix + tag, self.value(child, prefix + tag)) continue names = {_tag(g): (g.text or "").strip() for g in child} if set(names) == {"name", "namingSystem"}: self._put(row, f"{prefix}{tag}_{_slug(names['namingSystem'])}", names["name"] or None) continue seen[tag] += 1 self.leaves(child, row, f"{prefix}{tag}{seen[tag] if seen[tag] > 1 else ''}_") return row @staticmethod def _put(row: dict, key: str, value) -> None: k, n = key, 1 while k in row: # repeated leaf: keep both, never overwrite n += 1 k = f"{key}_{n}" row[k] = value def parse_file(path: Path) -> ParsedReport: root = ET.parse(path).getroot() reports = root.findall(NS + "drillReport") if len(reports) != 1: raise ValueError(f"{path.name}: {len(reports)} drillReport elements, expected 1") (dr,) = reports m = _FILE.fullmatch(path.stem) if not m: raise ValueError(f"unexpected DDR file name: {path.name}") report_id = path.stem parsed = ParsedReport(report={}) head = _Flattener(parsed, "reports") rep = {"report_id": report_id, "file_wellbore": canonical(m.group(1)), "file_date": f"{m.group(2)}-{m.group(3)}-{m.group(4)}"} for child in dr: tag = _tag(child) if tag in SECTIONS: continue if len(child) == 0: head._put(rep, tag, head.value(child, tag)) elif tag in REPORT_GROUPS: head.leaves(child, rep) else: # wellAlias / wellboreAlias: name + namingSystem names = {_tag(g): (g.text or "").strip() for g in child} head._put(rep, f"{tag}_{_slug(names.get('namingSystem', 'name'))}", names.get("name") or None) rep["wellbore"] = canonical(rep["nameWellbore"]) parsed.report = rep for child in dr: tag = _tag(child) if tag not in SECTIONS: continue table = SECTIONS[tag] rows = parsed.sections[table] row = {"report_id": report_id, "wellbore": rep["wellbore"], "seq": len(rows)} _Flattener(parsed, table).leaves(child, row) if table == "activities": row["act_id"] = f"{report_id}:{row['seq']:03d}" code = row.get("proprietaryCode") or "" main, _, sub = code.partition(" -- ") row["code_main"], row["code_sub"] = main or None, sub or None rows.append(row) return parsed def _utc(s: pd.Series) -> pd.Series: return pd.to_datetime(s, utc=True, format="ISO8601") def parse_dir(directory: Path) -> dict[str, pd.DataFrame]: """All drillReport files of `directory` as DataFrames: `reports`, one table per section, `units`, `sentinels`.""" files = sorted(directory.glob("*.xml")) if not files: raise FileNotFoundError(f"no XML files in {directory}") reports: list[dict] = [] sections: dict[str, list[dict]] = collections.defaultdict(list) units: dict[tuple[str, str], set] = collections.defaultdict(set) unit_files: collections.Counter = collections.Counter() sentinels: collections.Counter = collections.Counter() for f in files: p = parse_file(f) reports.append(p.report) for table, rows in p.sections.items(): sections[table].extend(rows) for key, u in p.units.items(): units[key].add(u) unit_files[key] += 1 sentinels.update(p.sentinels) mixed = {k: v for k, v in units.items() if len(v) > 1} if mixed: raise ValueError(f"columns published in more than one unit: {mixed}") out = {"reports": pd.DataFrame(reports)} for table in SECTIONS.values(): out[table] = pd.DataFrame(sections.get(table, [])) r = out["reports"] r["start_utc"], r["end_utc"] = _utc(r["dTimStart"]), _utc(r["dTimEnd"]) r["stem_ok"] = [stem(w) == stem(fw) for w, fw in zip(r["wellbore"], r["file_wellbore"])] a = out["activities"] a["start_utc"], a["end_utc"] = _utc(a["dTimStart"]), _utc(a["dTimEnd"]) a["duration_h"] = (a["end_utc"] - a["start_utc"]).dt.total_seconds() / 3600 out["units"] = pd.DataFrame([{"table": t, "column": c, "uom": u, "datum": d, "n_files": unit_files[(t, c)]} for (t, c), ((u, d),) in sorted(units.items())]) out["sentinels"] = pd.DataFrame([{"table": t, "column": c, "n": n} for (t, c), n in sorted(sentinels.items())]) return out