Add M1: OCR hub import, WITSML, labels T1-T3, T4 questions, trial raters, draft protocol
- OCR: match the colleague's full-set Dataset Hub export to the DDRs by content (3,059/3,066 pages) and QC it against the HTML (CER 2.40%, exact 0.9181). - WITSML parser and formation tops: 21 DDR wellbores with time logs, 1,384 reports; WITSML 15/9-F-15 S is DDR 15/9-F-15. - Deterministic labels T1-T3 (configs/labels.yaml), 1,662 T4 questions with SQL, pandas and raw-XML answers in full agreement. - Trial label validation by three blind LLM raters (not an author or expert audit) and rater agreement script; draft protocol_v1 (not locked): split by well. - Literature notes and BibTeX; docs, report and run_m1.sh synchronised. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
826
volve_dia/witsml.py
Normal file
826
volve_dia/witsml.py
Normal file
@@ -0,0 +1,826 @@
|
||||
"""WITSML 1.4.1.1 real-time objects of Volve (`WITSML Realtime drilling data/`) as flat tables.
|
||||
|
||||
Layout of the source. A top folder is a *well* on one of two servers (Schlumberger-era folders such as
|
||||
`Norway-StatoilHydro-15_$47$_9-F-15A`, Baker-Hughes-era folders such as `Norway-Statoil-NO 15_$47$_9-F-11`); its
|
||||
numbered subfolders are the *wellbores* of that well (`NO 15/9-F-11` holds F-11, F-11 A, F-11 B and F-11 T2). The
|
||||
wellbore of an object is therefore read from the object (`nameWellbore`, `uidWellbore`), never from the folder.
|
||||
|
||||
<well>/<n>/log/<i>/<j>/<k>/NNNNN.xml one log (`<k>`) cut into consecutive chunk files
|
||||
<well>/<n>/{trajectory,message,bhaRun,mudLog}/N.xml
|
||||
|
||||
Parsed here: `log` (header, logCurveInfo, logData; time- and depth-indexed), `trajectory`, `message`, `bhaRun`,
|
||||
`mudLog`. Not parsed: `tubular`, `rig`, `wbGeometry`, `_wellInfo`, `_wellboreInfo`.
|
||||
|
||||
Column names are the WITSML element names (a nested element prefixes its leaves with its tag), so every value can
|
||||
be traced back to the schema. Values are stored as published, in the published unit. Log data are stored long:
|
||||
one row per published value `(wellbore, log_id, mnemonic, index, value | text, chunk)`, because the logs publish
|
||||
1,744 different mnemonics, of which the two service companies share 3 (HKLD, MWIN, DXC). `log_id` + `chunk` name the
|
||||
source file of every value. Normalisations, all counted, none silent:
|
||||
|
||||
* an empty log cell is "no value" and makes no row;
|
||||
* a log value equal to the `nullValue` of its curve (or of its log) becomes missing (`n_null_value`);
|
||||
* the sentinels -999.25 and -9999 become missing (TADI, arXiv:2605.00060, section 3.3 "Sentinel values");
|
||||
two more sentinels found in the object files are listed in `EXTRA_SENTINELS` with the reason;
|
||||
* a cell of a numeric curve that is not a number (array curves publish 16 space-separated values) is kept as
|
||||
text (`n_not_number`); curves of type string or date time are text;
|
||||
* trajectory angles and magnetic fields are published in two units (Schlumberger: dega, nT; Baker Hughes: rad, T):
|
||||
they are stored in the units of `STORED_UNITS` and the conversion is counted in the `units` table;
|
||||
* duplicates, see `dedup_curve` (inside one log: rows with the same index, one is kept) and `merge_curve`
|
||||
(between logs of one wellbore: rows with the same mnemonic and index are all kept and ranked, `dup_rank`);
|
||||
* three Schlumberger-server wellbores are renamed to their DDR name (`WELLBORE_BY_UID`).
|
||||
|
||||
Deviations from TADI (sections 3.2-3.3): TADI converts ROP to m/h, WOB to kN and RPM to 1/min and drops values it
|
||||
calls implausible (ROP > 200 m/h, RPM > 300, WOB > 500 kN). Here units stay as published (recorded per column and
|
||||
per curve) and no value is dropped for being large: `tadi_implausible` only flags mudLog intervals, and the values
|
||||
listed in `SUSPECT_VALUES` are only counted per curve, because a benchmark value must be the published one. TADI
|
||||
did not parse the `log` objects.
|
||||
|
||||
Times: log indexes are UTC timestamps (every published index ends in "Z", checked); other times stay ISO strings
|
||||
as published.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.compute as pc
|
||||
import pyarrow.csv as pacsv
|
||||
import pyarrow.parquet as pq
|
||||
|
||||
from .names import canonical, stem
|
||||
|
||||
NS = "{http://www.witsml.org/schemas/1series}"
|
||||
|
||||
#: TADI section 3.3: "WITSML uses -999.25 and -9999".
|
||||
SENTINELS = (-999.25, -9999.0)
|
||||
#: Sentinels of the object files that TADI does not list: (table, column prefix) -> value.
|
||||
#: * mudLog gas concentrations (ppm) are published as -999 where there is no reading; a concentration is never
|
||||
#: negative. (+999 also occurs, 5 times, but 999 ppm is a possible reading, so it is kept.)
|
||||
#: * `stnGridCorUsed` is 999.25 in 2,123 Baker Hughes stations: a grid convergence of 999.25 rad is not an angle.
|
||||
EXTRA_SENTINELS = {
|
||||
("mudlog_intervals", "chromatograph_"): -999.0,
|
||||
("mudlog_intervals", "mudGas_"): -999.0,
|
||||
("trajectory", "corUsed_stnGridCorUsed"): 999.25,
|
||||
}
|
||||
#: Log values that look like more sentinels. They are *kept* and counted per curve (`log_suspects`): none of them
|
||||
#: is a declared null value, and e.g. 9999 s is a possible off-bottom time.
|
||||
SUSPECT_VALUES = (-999.0, 999.25, -999.99, 9999.0, -99999.0, 99999.0, 1e30, -1e30)
|
||||
SUSPECT_HUGE = 1e15 # |value| above this is counted as "huge"
|
||||
#: Unit a column is stored in when the source publishes it in more than one unit: published unit -> (stored, factor).
|
||||
STORED_UNITS = {
|
||||
"rad": ("dega", 180.0 / math.pi),
|
||||
"T": ("nT", 1e9),
|
||||
"rad/m": ("dega/30m", 30.0 * 180.0 / math.pi),
|
||||
"dega/m": ("dega/30m", 30.0),
|
||||
}
|
||||
#: TADI section 3.3 quality filters in the published SI units; used only to flag (`tadi_implausible`).
|
||||
TADI_FILTERS = {"ropAv": 200.0 / 3600.0, "rpmAv": 300.0 / 60.0, "wobAv": 500.0e3} # m/s, c/s, N
|
||||
|
||||
#: commonData leaves that identify people and machines of the operator; not needed, not copied.
|
||||
DROPPED = {"priv_userOwner", "priv_userLastChange", "priv_ipOwner", "priv_ipLastChange"}
|
||||
#: WITSML `typeLogData` values stored as numbers; every other type is stored as text.
|
||||
NUMERIC_TYPES = {"double", "float", "long", "int", "short", "byte"}
|
||||
INDEX_KINDS = {"date time": "time", "measured depth": "depth"}
|
||||
#: Logs that hold display settings of the WITSML store (2 rows of text written on 22.09.2015 into every wellbore),
|
||||
#: not measurements. They are parsed like every log but excluded from time ranges and coverage.
|
||||
SETTINGS_LOGS = {"GlcSettingsLog"}
|
||||
#: Hole depth and bit depth of the time logs: Schlumberger `DMEA`/`DBTM`; Baker Hughes `Depth`/`BITDEP` of the
|
||||
#: `GenTime` log. (Every Baker Hughes log has a `Depth` curve: the reference depth of *that* log, which for an MWD
|
||||
#: log is the sensor depth. Only in `GenTime` is it the hole depth.)
|
||||
HOLE_DEPTH = {"DMEA": None, "Depth": "GenTime"} # mnemonic -> required log name (None: any)
|
||||
BIT_DEPTH = {"DBTM": None, "BITDEP": "GenTime"}
|
||||
|
||||
#: The Schlumberger server names three wellbores of slot F-15 differently from the DDR and from NPD: uidWellbore
|
||||
#: -> DDR wellbore. No DDR and no NPD wellbore is called F-15 S. Evidence, per uid (the first item is recomputed on
|
||||
#: every run by `scripts/06_parse_witsml.py`, which fails if a uid agrees better with another DDR wellbore):
|
||||
#: 1. hole depth `DMEA` at the end of the DDR report periods against `md` of the DDR (table
|
||||
#: `check_wellbore_identity`), for every DDR wellbore of the slot;
|
||||
#: 2. DDR survey stations found in the WITSML trajectories (MD within 0.5 m, inclination 0.1, azimuth 0.5 deg);
|
||||
#: 3. total depth in `_wellboreInfo` against the deepest `md` of the DDR and the TD of NPD FactPages;
|
||||
#: 4. dates of the time logs against the DDR reports and the NPD entry and completion dates.
|
||||
#:
|
||||
#: B-744206 "15/9-F-15S" = DDR 15/9-F-15: (1) 47 reports, median |diff| 0.12 m, 42 within 5 m; (2) 27 of its
|
||||
#: 27 distinct DDR stations; (3) 4090.0 m, DDR 4090 m; (4) logs 08.09-08.12.2008, NPD completed 05.12.2008.
|
||||
#: B-826806 "15/9-F-15" = DDR 15/9-F-15 A: (1) 15 reports, median 0.50 m, 13 within 5 m, while against DDR
|
||||
#: 15/9-F-15 all 3 reports are 2890 m off; (2) 53 stations of F-15 A, 0 of F-15; (3) 4096.5 m, DDR and
|
||||
#: NPD 4095 m; (4) logs 08.12.2008-12.01.2009, NPD 11.12.2008-10.01.2009.
|
||||
#: B-861401 "15/9-F-15A" = DDR 15/9-F-15 C: (1) 7 reports, median 0.12 m, 7 within 5 m, while against DDR
|
||||
#: 15/9-F-15 B both reports are about 960 m off; (2) 6 of the 6 stations of F-15 C, 1 of F-15 A;
|
||||
#: (3) 3232.1 m, DDR and NPD 3232 m; (4) logs 14.01-02.03.2009, NPD 18.01-15.02.2009.
|
||||
#: B-854763 "15/9-F-15B" keeps its name: (1) 2 reports within 0.6 m; (2) 8 of 9 stations; (3) 3497.6 m, NPD 3497 m.
|
||||
#: The Baker Hughes server (2013 onwards) uses the NPD names: its "NO 15/9-F-15 C" is DDR 15/9-F-15 C.
|
||||
WELLBORE_BY_UID = {
|
||||
"B-744206": "15/9-F-15",
|
||||
"B-826806": "15/9-F-15 A",
|
||||
"B-861401": "15/9-F-15 C",
|
||||
}
|
||||
|
||||
_MAIN = re.compile(r"\s*-\s*Main Wellbore$")
|
||||
|
||||
|
||||
def published_wellbore(name_well: str, name_wellbore: str) -> tuple[str, str]:
|
||||
"""(canonical wellbore as published, source). The name comes from `nameWellbore` ("15/9-F-15A - Main
|
||||
Wellbore", "NO 15/9-F-11 T2"); when that is not a wellbore name ("EcoScope_Customer_Run5", "test") it falls
|
||||
back to `nameWell` and says so."""
|
||||
try:
|
||||
return canonical(_MAIN.sub("", name_wellbore or "")), "nameWellbore"
|
||||
except ValueError:
|
||||
return canonical(name_well), "nameWell"
|
||||
|
||||
|
||||
def wellbore_name(name_well: str, name_wellbore: str, uid_wellbore: str | None = None) -> tuple[str, str]:
|
||||
"""(DDR wellbore, source): `WELLBORE_BY_UID` first, else the published name."""
|
||||
if uid_wellbore in WELLBORE_BY_UID:
|
||||
return WELLBORE_BY_UID[uid_wellbore], "uidWellbore"
|
||||
return published_wellbore(name_well, name_wellbore)
|
||||
|
||||
|
||||
def wellbore_dir(wellbore: str) -> str:
|
||||
"""File name of a wellbore in the parquet tree: '15/9-F-11 T2' -> '15_9_F_11_T2'."""
|
||||
return stem(wellbore)
|
||||
|
||||
|
||||
def _tag(e: ET.Element) -> str:
|
||||
return e.tag.replace(NS, "")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# log: reading
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class LogFile:
|
||||
"""One chunk file of a log: header leaves, logCurveInfo rows, and the raw comma-separated data rows."""
|
||||
header: dict
|
||||
curves: list[dict]
|
||||
mnemonics: list[str]
|
||||
units: list[str]
|
||||
rows: list[str]
|
||||
|
||||
|
||||
def read_log_file(source, header_only: bool = False) -> LogFile:
|
||||
"""Stream one `<logs><log>` file (path or binary file object). `logData/data` rows are kept as text.
|
||||
With `header_only` the parse stops at the first logCurveInfo (enough to name the wellbore)."""
|
||||
header: dict = {}
|
||||
curves: list[dict] = []
|
||||
mnemonics: list[str] = []
|
||||
units: list[str] = []
|
||||
rows: list[str] = []
|
||||
stack: list[str] = []
|
||||
n_logs = 0
|
||||
for event, e in ET.iterparse(source, events=("start", "end")):
|
||||
tag = _tag(e)
|
||||
if event == "start":
|
||||
stack.append(tag)
|
||||
if tag == "log":
|
||||
n_logs += 1
|
||||
header.update(e.attrib)
|
||||
elif header_only and tag in ("logCurveInfo", "logData"):
|
||||
return LogFile(header, curves, mnemonics, units, rows)
|
||||
continue
|
||||
stack.pop()
|
||||
parent = stack[-1] if stack else ""
|
||||
if tag == "data":
|
||||
rows.append(e.text or "")
|
||||
e.clear()
|
||||
elif tag == "logCurveInfo":
|
||||
c = {"uid": e.attrib.get("uid")}
|
||||
for child in e:
|
||||
c[_tag(child)] = (child.text or "").strip()
|
||||
if "uom" in child.attrib:
|
||||
c[_tag(child) + "_uom"] = child.attrib["uom"]
|
||||
curves.append(c)
|
||||
e.clear()
|
||||
elif tag == "mnemonicList":
|
||||
mnemonics = [m.strip() for m in (e.text or "").split(",")]
|
||||
elif tag == "unitList":
|
||||
units = [u.strip() for u in (e.text or "").split(",")]
|
||||
elif parent == "log" and len(e) == 0:
|
||||
header[tag] = (e.text or "").strip()
|
||||
if "uom" in e.attrib:
|
||||
header[tag + "_uom"] = e.attrib["uom"]
|
||||
elif parent == "commonData" and tag not in DROPPED:
|
||||
header["commonData_" + tag] = (e.text or "").strip()
|
||||
if n_logs != 1:
|
||||
raise ValueError(f"{source}: {n_logs} log elements, expected 1")
|
||||
return LogFile(header, curves, mnemonics, units, rows)
|
||||
|
||||
|
||||
def _split(rows: list[str], n_cols: int) -> tuple[pa.Table, int]:
|
||||
"""Comma-separated rows -> a table of string columns c0..cN. Rows with another field count are dropped and
|
||||
counted (WITSML 1.4.1 has no quoting, so a text value with a comma would break its row)."""
|
||||
bad = [0]
|
||||
|
||||
def on_invalid(row) -> str:
|
||||
bad[0] += 1
|
||||
return "skip"
|
||||
|
||||
data = "\n".join(r.replace("\n", " ").replace("\r", " ") for r in rows).encode("utf-8")
|
||||
names = [f"c{i}" for i in range(n_cols)]
|
||||
table = pacsv.read_csv(
|
||||
io.BytesIO(data),
|
||||
read_options=pacsv.ReadOptions(column_names=names, block_size=max(len(data) + 16, 1 << 20),
|
||||
use_threads=False),
|
||||
parse_options=pacsv.ParseOptions(delimiter=",", quote_char=False, escape_char=False,
|
||||
newlines_in_values=False, ignore_empty_lines=False,
|
||||
invalid_row_handler=on_invalid),
|
||||
convert_options=pacsv.ConvertOptions(column_types={n: pa.string() for n in names},
|
||||
strings_can_be_null=True, null_values=[""]),
|
||||
)
|
||||
return table, bad[0]
|
||||
|
||||
|
||||
def _objects(col: pa.ChunkedArray) -> np.ndarray:
|
||||
out = np.empty(len(col), dtype=object)
|
||||
out[:] = col.to_pylist()
|
||||
return out
|
||||
|
||||
|
||||
def _numbers(col: pa.ChunkedArray) -> tuple[np.ndarray, np.ndarray | None, int]:
|
||||
"""A string column -> (float64 values, NaN where missing; texts of the cells that are not numbers, or None;
|
||||
number of such cells)."""
|
||||
try:
|
||||
return pc.cast(col, pa.float64()).to_numpy(zero_copy_only=False), None, 0
|
||||
except pa.ArrowInvalid:
|
||||
raw = _objects(col)
|
||||
out = np.full(len(raw), np.nan)
|
||||
text = np.full(len(raw), None, dtype=object)
|
||||
bad = 0
|
||||
for i, s in enumerate(raw):
|
||||
if s is None:
|
||||
continue
|
||||
try:
|
||||
out[i] = float(s)
|
||||
except ValueError:
|
||||
text[i], bad = s, bad + 1
|
||||
return out, text, bad
|
||||
|
||||
|
||||
def parse_time_index(col: pa.ChunkedArray) -> np.ndarray:
|
||||
"""ISO 8601 strings ending in "Z" -> int64 milliseconds since the epoch (UTC). Raises on anything else."""
|
||||
if not pc.all(pc.ends_with(col, "Z")).as_py():
|
||||
raise ValueError("a time index value does not end in 'Z'")
|
||||
t = pd.to_datetime(col.to_pandas(), utc=True, format="ISO8601")
|
||||
return t.dt.as_unit("ms").astype("int64").to_numpy()
|
||||
|
||||
|
||||
def _float_or_none(s) -> float | None:
|
||||
try:
|
||||
return float(s) if s not in (None, "") else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class CurveData:
|
||||
"""Values of one curve of one log, one list entry per chunk file, in file order."""
|
||||
index: list = field(default_factory=list) # int64 ms since the epoch, or float64 metres
|
||||
value: list = field(default_factory=list) # float64, NaN where the value is text
|
||||
text: list = field(default_factory=list) # object array or None
|
||||
chunk: list = field(default_factory=list) # int16 source file number
|
||||
has_text: bool = False
|
||||
stats: collections.Counter = field(default_factory=collections.Counter)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Curve:
|
||||
"""One curve of one log after `dedup_curve`: sorted by index, one row per index value."""
|
||||
log_id: int
|
||||
mnemonic: str
|
||||
index: np.ndarray
|
||||
value: np.ndarray
|
||||
text: np.ndarray | None
|
||||
chunk: np.ndarray
|
||||
stats: dict
|
||||
|
||||
|
||||
class ParsedLog:
|
||||
"""All chunk files of one log merged: header, curve table, and the values of every curve in file order."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.header: dict = {}
|
||||
self.kind: str | None = None # "time" | "depth"
|
||||
self.index_unit: str | None = None
|
||||
self.curve_info: dict[str, dict] = {} # mnemonic -> logCurveInfo of the first chunk that has it
|
||||
self.data: dict[str, CurveData] = {}
|
||||
self.counts: collections.Counter = collections.Counter()
|
||||
self.index_values: list[np.ndarray] = [] # the index column of every chunk, in file order
|
||||
|
||||
def add(self, lf: LogFile, chunk: int) -> None:
|
||||
h = lf.header
|
||||
if not self.header:
|
||||
self.header = dict(h)
|
||||
self.kind = INDEX_KINDS.get(h.get("indexType", ""))
|
||||
if self.kind is None:
|
||||
raise ValueError(f"unsupported indexType {h.get('indexType')!r}")
|
||||
else:
|
||||
for key in ("uid", "uidWellbore", "indexType", "indexCurve"):
|
||||
if h.get(key) != self.header.get(key):
|
||||
raise ValueError(f"chunk {chunk}: {key} changes inside one log: "
|
||||
f"{self.header.get(key)!r} -> {h.get(key)!r}")
|
||||
for c in lf.curves:
|
||||
known = self.curve_info.setdefault(c["mnemonic"], c)
|
||||
if known is not c and known.get("unit") != c.get("unit"):
|
||||
raise ValueError(f"chunk {chunk}: unit of {c['mnemonic']} changes inside one log")
|
||||
self.counts["files"] += 1
|
||||
self.counts["rows"] += len(lf.rows)
|
||||
if not lf.rows:
|
||||
return
|
||||
names = lf.mnemonics
|
||||
index_curve = h.get("indexCurve", "")
|
||||
if names.count(index_curve) != 1:
|
||||
raise ValueError(f"chunk {chunk}: index curve {index_curve!r} is not exactly once in mnemonicList")
|
||||
if len(set(names)) != len(names):
|
||||
raise ValueError(f"chunk {chunk}: repeated mnemonic in mnemonicList")
|
||||
table, bad = _split(lf.rows, len(names))
|
||||
self.counts["bad_rows"] += bad
|
||||
i_index = names.index(index_curve)
|
||||
icol = table.column(i_index)
|
||||
if icol.null_count:
|
||||
raise ValueError(f"chunk {chunk}: {icol.null_count} rows without an index value")
|
||||
if self.kind == "time":
|
||||
index = parse_time_index(icol)
|
||||
else:
|
||||
unit = lf.units[i_index] if i_index < len(lf.units) else ""
|
||||
if unit not in ("m", ""):
|
||||
raise ValueError(f"chunk {chunk}: depth index in {unit!r}, expected metres")
|
||||
self.index_unit = unit or self.index_unit
|
||||
index = pc.cast(icol, pa.float64()).to_numpy(zero_copy_only=False)
|
||||
self.index_values.append(index)
|
||||
log_null = _float_or_none(h.get("nullValue"))
|
||||
for j, name in enumerate(names):
|
||||
if j == i_index:
|
||||
continue
|
||||
col = table.column(j)
|
||||
n_valid = len(col) - col.null_count
|
||||
if n_valid == 0:
|
||||
continue
|
||||
info = self.curve_info.get(name)
|
||||
if info is None: # data for a curve without logCurveInfo
|
||||
info = self.curve_info.setdefault(name, {"mnemonic": name, "undeclared": True,
|
||||
"unit": lf.units[j] if j < len(lf.units) else None})
|
||||
cd = self.data.setdefault(name, CurveData())
|
||||
ltype = (info.get("typeLogData") or "").lower()
|
||||
if ltype in NUMERIC_TYPES or not ltype:
|
||||
values, text, n_bad = _numbers(col)
|
||||
cd.stats["n_not_number"] += n_bad
|
||||
keep = ~np.isnan(values)
|
||||
cd.stats["n_nan"] += int(n_valid - n_bad - keep.sum()) # the literal "NaN"
|
||||
null = _float_or_none(info.get("nullValue"))
|
||||
null = log_null if null is None else null
|
||||
if null is not None:
|
||||
hit = keep & (values == null)
|
||||
cd.stats["n_null_value"] += int(hit.sum())
|
||||
keep &= ~hit
|
||||
for s in SENTINELS:
|
||||
hit = keep & (values == s)
|
||||
if hit.any():
|
||||
cd.stats[f"sentinel:{s:g}"] += int(hit.sum())
|
||||
keep &= ~hit
|
||||
for s in SUSPECT_VALUES:
|
||||
n_hit = int((keep & (values == s)).sum())
|
||||
if n_hit:
|
||||
cd.stats[f"suspect:{s:g}"] += n_hit
|
||||
n_hit = int((keep & (np.abs(values) > SUSPECT_HUGE)).sum())
|
||||
if n_hit:
|
||||
cd.stats["suspect:huge"] += n_hit
|
||||
if text is not None:
|
||||
keep |= np.array([t is not None for t in text])
|
||||
cd.has_text = True
|
||||
cd.text.append(text[keep])
|
||||
else:
|
||||
cd.text.append(None)
|
||||
cd.value.append(values[keep])
|
||||
else:
|
||||
raw = _objects(col)
|
||||
keep = np.array([s is not None for s in raw])
|
||||
cd.has_text = True
|
||||
cd.text.append(raw[keep])
|
||||
cd.value.append(np.full(int(keep.sum()), np.nan))
|
||||
cd.index.append(index[keep])
|
||||
cd.chunk.append(np.full(int(keep.sum()), chunk, dtype=np.int16))
|
||||
|
||||
def index_stats(self) -> dict:
|
||||
"""Row-level statistics of the index column over all chunks, in file order. Steps are in seconds for a
|
||||
time log and metres for a depth log, between consecutive distinct index values."""
|
||||
if not self.index_values:
|
||||
return {"n_index_values": 0}
|
||||
idx = np.concatenate(self.index_values)
|
||||
uniq = np.unique(idx)
|
||||
ustep = np.diff(uniq) / (1000.0 if self.kind == "time" else 1.0)
|
||||
return {
|
||||
"n_index_values": int(len(idx)),
|
||||
"n_index_distinct": int(len(uniq)),
|
||||
"n_index_backwards": int((np.diff(idx) < 0).sum()),
|
||||
"index_min": idx.min(), "index_max": idx.max(),
|
||||
"step_median": float(np.median(ustep)) if len(ustep) else None,
|
||||
"step_p10": float(np.quantile(ustep, 0.1)) if len(ustep) else None,
|
||||
"step_p90": float(np.quantile(ustep, 0.9)) if len(ustep) else None,
|
||||
}
|
||||
|
||||
def curves(self, log_id: int = 0) -> list[Curve]:
|
||||
"""Every curve with data, de-duplicated on the index (`dedup_curve`) and sorted by it."""
|
||||
out = []
|
||||
for name in sorted(self.data):
|
||||
cd = self.data[name]
|
||||
index, value, chunk = np.concatenate(cd.index), np.concatenate(cd.value), np.concatenate(cd.chunk)
|
||||
text = None
|
||||
if cd.has_text:
|
||||
text = np.concatenate([t if t is not None else np.full(len(v), None, dtype=object)
|
||||
for t, v in zip(cd.text, cd.value)])
|
||||
index, value, text, chunk, dd = dedup_curve(index, value, text, chunk)
|
||||
stats = dict(cd.stats)
|
||||
stats.update(dd)
|
||||
stats["n_values"] = int(len(index))
|
||||
stats["n_text"] = int(sum(t is not None for t in text)) if text is not None else 0
|
||||
out.append(Curve(log_id, name, index, value, text, chunk, stats))
|
||||
return out
|
||||
|
||||
|
||||
def parse_log(files: list[Path]) -> ParsedLog:
|
||||
"""All chunk files of one log, in file-name order (00001.xml, 00002.xml, ...)."""
|
||||
log = ParsedLog()
|
||||
for f in sorted(files):
|
||||
log.add(read_log_file(f), int(f.stem))
|
||||
return log
|
||||
|
||||
|
||||
def find_logs(root: Path) -> list[tuple[str, str, Path, list[Path]]]:
|
||||
"""(well folder, wellbore subfolder, log directory, chunk files) of every log under `root`, sorted."""
|
||||
out = []
|
||||
for d in sorted(p for p in root.glob("*/*/log/*/*/*") if p.is_dir()):
|
||||
files = sorted(d.glob("*.xml"))
|
||||
if files:
|
||||
rel = d.relative_to(root).parts
|
||||
out.append((rel[0], rel[1], d, files))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# log: duplicates
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _same(value_a: np.ndarray, value_b: np.ndarray, text_a, text_b) -> np.ndarray:
|
||||
same = (value_a == value_b) | (np.isnan(value_a) & np.isnan(value_b))
|
||||
if text_a is not None:
|
||||
same &= text_a == text_b
|
||||
return same
|
||||
|
||||
|
||||
def dedup_curve(index: np.ndarray, value: np.ndarray, text: np.ndarray | None, chunk: np.ndarray):
|
||||
"""De-duplicate one curve of one log on its index. Rows are sorted by index (stable, so file order breaks
|
||||
ties). Among rows with the same index the *last* row in file order is kept and the others are dropped. A
|
||||
dropped row is counted in `n_dup_same` if the row after it has the same value, else in `n_dup_conflict` (a
|
||||
WITSML store appends corrections, so the later row is the one the server would return).
|
||||
|
||||
In the Volve logs every such row is a plain repeat (`n_dup_conflict` is 0 in all 2,047 logs): the last row of
|
||||
a chunk file is repeated as the first row of the next file, and one log was stored twice.
|
||||
|
||||
Returns (index, value, text, chunk, counts); `n_out_of_order` counts the rows that had to move."""
|
||||
n = len(index)
|
||||
order = np.argsort(index, kind="stable")
|
||||
moved = order != np.arange(n)
|
||||
if moved.any():
|
||||
index, value, chunk = index[order], value[order], chunk[order]
|
||||
text = text[order] if text is not None else None
|
||||
counts = {"n_dup_same": 0, "n_dup_conflict": 0, "n_out_of_order": int(moved.sum())}
|
||||
if n < 2:
|
||||
return index, value, text, chunk, counts
|
||||
same_index = index[1:] == index[:-1]
|
||||
if not same_index.any():
|
||||
return index, value, text, chunk, counts
|
||||
same_value = _same(value[1:], value[:-1], None if text is None else text[1:], None if text is None else text[:-1])
|
||||
keep = np.ones(n, dtype=bool)
|
||||
keep[:-1] = ~same_index # the last row of every run of equal index
|
||||
counts["n_dup_same"] = int((same_index & same_value).sum())
|
||||
counts["n_dup_conflict"] = int((same_index & ~same_value).sum())
|
||||
return index[keep], value[keep], text[keep] if text is not None else None, chunk[keep], counts
|
||||
|
||||
|
||||
#: Two colliding values that differ by at most this (relative to max(1, |value|)) are "rounding": memory logs
|
||||
#: publish 4-5 decimals where the real-time log publishes float32 values with all their digits.
|
||||
ROUNDING = 1e-4
|
||||
|
||||
|
||||
def merge_curve(curves: list[Curve]):
|
||||
"""All logs of one wellbore that publish the same mnemonic -> one series sorted by index, every row kept.
|
||||
|
||||
A mnemonic is only unique inside a log (the Baker Hughes `Depth` curve is the reference depth of its own
|
||||
log), so rows of different logs with the same index are *not* dropped. They are ranked: `dup_rank` is 0 for
|
||||
the row of the preferred log and 1, 2, ... for the others. The preferred log is the one with the most values
|
||||
of this curve in the wellbore (the main record; ties: lower log_id). Keeping `dup_rank = 0` gives at most one
|
||||
value per (wellbore, mnemonic, index).
|
||||
|
||||
Returns (log_id, index, value, text, chunk, dup_rank, overlaps); `overlaps` has one row per pair (preferred
|
||||
log, other log): colliding index values, how many values are identical, differ by rounding, or conflict, and
|
||||
the largest absolute difference."""
|
||||
curves = sorted(curves, key=lambda c: (-len(c.index), c.log_id))
|
||||
index = np.concatenate([c.index for c in curves])
|
||||
value = np.concatenate([c.value for c in curves])
|
||||
chunk = np.concatenate([c.chunk for c in curves])
|
||||
log_id = np.concatenate([np.full(len(c.index), c.log_id, dtype=np.int32) for c in curves])
|
||||
text = None
|
||||
if any(c.text is not None for c in curves):
|
||||
text = np.concatenate([c.text if c.text is not None else np.full(len(c.index), None, dtype=object)
|
||||
for c in curves])
|
||||
n = len(index)
|
||||
rank = np.zeros(n, dtype=np.int8)
|
||||
if len(curves) == 1:
|
||||
return log_id, index, value, text, chunk, rank, []
|
||||
order = np.argsort(index, kind="stable") # stable: the preferred log comes first in a tie
|
||||
index, value, chunk, log_id = index[order], value[order], chunk[order], log_id[order]
|
||||
text = text[order] if text is not None else None
|
||||
new_run = np.ones(n, dtype=bool)
|
||||
new_run[1:] = index[1:] != index[:-1]
|
||||
if new_run.all():
|
||||
return log_id, index, value, text, chunk, rank, []
|
||||
first = np.flatnonzero(new_run)[np.cumsum(new_run) - 1] # position of the preferred row
|
||||
position = np.arange(n) - first
|
||||
rank = np.minimum(position, 127).astype(np.int8)
|
||||
dup = position > 0
|
||||
va, vb = value[first[dup]], value[dup]
|
||||
same = _same(va, vb, None if text is None else text[first[dup]], None if text is None else text[dup])
|
||||
with np.errstate(invalid="ignore"):
|
||||
diff = np.abs(va - vb)
|
||||
rounding = ~same & (diff <= ROUNDING * np.maximum(1.0, np.abs(va)))
|
||||
pairs = pd.DataFrame({"log_id": log_id[first[dup]], "other_log_id": log_id[dup], "same": same,
|
||||
"rounding": rounding, "conflict": ~same & ~rounding, "diff": np.where(same, 0.0, diff)})
|
||||
g = pairs.groupby(["log_id", "other_log_id"], sort=True)
|
||||
overlaps = g.agg(n=("same", "size"), n_same=("same", "sum"), n_rounding=("rounding", "sum"),
|
||||
n_conflict=("conflict", "sum"), max_abs_diff=("diff", "max")).reset_index()
|
||||
return log_id, index, value, text, chunk, rank, overlaps.to_dict("records")
|
||||
|
||||
|
||||
def log_schema(kind: str) -> pa.Schema:
|
||||
index = ("time", pa.timestamp("ms", tz="UTC")) if kind == "time" else ("md", pa.float64())
|
||||
return pa.schema([("wellbore", pa.dictionary(pa.int32(), pa.string())), ("log_id", pa.int32()),
|
||||
("mnemonic", pa.dictionary(pa.int32(), pa.string())), index, ("value", pa.float64()),
|
||||
("text", pa.string()), ("chunk", pa.int16()), ("dup_rank", pa.int8())])
|
||||
|
||||
|
||||
class LongWriter:
|
||||
"""Writes the long log table of one wellbore, curve after curve (so the file is sorted by mnemonic, index).
|
||||
The time index is delta-encoded, so a regular sampling costs almost nothing; the file takes about one byte
|
||||
per value. Small curves are buffered into row groups of about a million rows."""
|
||||
|
||||
ROW_GROUP = 1 << 20
|
||||
|
||||
def __init__(self, path: Path, kind: str, wellbore: str, mnemonics: list[str]) -> None:
|
||||
self.path, self.kind, self.schema = path, kind, log_schema(kind)
|
||||
self.wellbores, self.mnemonics = pa.array([wellbore]), pa.array(sorted(mnemonics))
|
||||
self.codes = {m: i for i, m in enumerate(sorted(mnemonics))}
|
||||
self.buffer: list[pa.Table] = []
|
||||
self.buffered = self.rows = 0
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.tmp = path.with_suffix(".parquet.tmp")
|
||||
self.writer = pq.ParquetWriter(
|
||||
self.tmp, self.schema, compression="zstd", compression_level=9,
|
||||
use_dictionary=["wellbore", "mnemonic", "log_id", "chunk", "text", "dup_rank"],
|
||||
column_encoding={"time": "DELTA_BINARY_PACKED"} if kind == "time" else None)
|
||||
|
||||
def write(self, mnemonic: str, log_id, index, value, text, chunk, dup_rank) -> None:
|
||||
n = len(index)
|
||||
if n == 0:
|
||||
return
|
||||
zeros = pa.array(np.zeros(n, dtype=np.int32))
|
||||
idx = pa.array(index, type=pa.int64()).cast(pa.timestamp("ms", tz="UTC")) if self.kind == "time" \
|
||||
else pa.array(index, type=pa.float64())
|
||||
table = pa.Table.from_arrays([
|
||||
pa.DictionaryArray.from_arrays(zeros, self.wellbores), pa.array(log_id, type=pa.int32()),
|
||||
pa.DictionaryArray.from_arrays(pa.array(np.full(n, self.codes[mnemonic], dtype=np.int32)), self.mnemonics),
|
||||
idx, pa.array(value, mask=np.isnan(value)),
|
||||
pa.array(text, type=pa.string()) if text is not None else pa.nulls(n, pa.string()),
|
||||
pa.array(chunk, type=pa.int16()), pa.array(dup_rank, type=pa.int8())], schema=self.schema)
|
||||
self.buffer.append(table)
|
||||
self.buffered += n
|
||||
self.rows += n
|
||||
if self.buffered >= self.ROW_GROUP:
|
||||
self._flush()
|
||||
|
||||
def _flush(self) -> None:
|
||||
if self.buffer:
|
||||
self.writer.write_table(pa.concat_tables(self.buffer), row_group_size=self.ROW_GROUP)
|
||||
self.buffer, self.buffered = [], 0
|
||||
|
||||
def close(self) -> None:
|
||||
self._flush()
|
||||
self.writer.close()
|
||||
self.tmp.replace(self.path)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# trajectory, message, bhaRun, mudLog
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
class Flat:
|
||||
"""Flattens WITSML elements into rows and counts sentinels and units per (table, column)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sentinels: collections.Counter = collections.Counter() # (table, column, value) -> n
|
||||
self.units: collections.Counter = collections.Counter() # (table, column, uom published) -> n
|
||||
|
||||
def value(self, e: ET.Element, table: str, column: str):
|
||||
text = (e.text or "").strip()
|
||||
if "uom" not in e.attrib:
|
||||
return text or None
|
||||
uom = e.attrib["uom"]
|
||||
if not text:
|
||||
return None
|
||||
v = float(text)
|
||||
extra = [s for (t, prefix), s in EXTRA_SENTINELS.items() if t == table and column.startswith(prefix)]
|
||||
if v in SENTINELS or v in extra:
|
||||
self.sentinels[(table, column, v)] += 1
|
||||
return None
|
||||
self.units[(table, column, uom)] += 1
|
||||
return v * STORED_UNITS[uom][1] if uom in STORED_UNITS else v
|
||||
|
||||
def leaves(self, elem: ET.Element, row: dict, table: str, prefix: str = "", skip: tuple[str, ...] = ()) -> dict:
|
||||
"""Leaves of `elem` into `row`; a nested element prefixes its leaves with its tag (numbered from the second
|
||||
occurrence on). `uid` and `uidRef` attributes become `<tag>_uid` and `<tag>_uidRef` columns."""
|
||||
seen: collections.Counter = collections.Counter()
|
||||
for child in elem:
|
||||
tag = _tag(child)
|
||||
if tag in skip or tag in DROPPED:
|
||||
continue
|
||||
if len(child) == 0:
|
||||
column = prefix + tag
|
||||
if column in row:
|
||||
raise ValueError(f"{table}: repeated leaf {column}")
|
||||
row[column] = self.value(child, table, column)
|
||||
if "uidRef" in child.attrib:
|
||||
row[column + "_uidRef"] = child.attrib["uidRef"]
|
||||
else:
|
||||
seen[tag] += 1
|
||||
nested = f"{prefix}{tag}{seen[tag] if seen[tag] > 1 else ''}_"
|
||||
if "uid" in child.attrib:
|
||||
row[nested + "uid"] = child.attrib["uid"]
|
||||
self.leaves(child, row, table, nested, skip)
|
||||
return row
|
||||
|
||||
|
||||
def _object(path: Path, plural: str, singular: str) -> ET.Element:
|
||||
root = ET.parse(path).getroot()
|
||||
if _tag(root) != plural or len(root) != 1 or _tag(root[0]) != singular:
|
||||
raise ValueError(f"{path}: expected one {singular} in {plural}")
|
||||
return root[0]
|
||||
|
||||
|
||||
def _ids(obj: ET.Element, path: Path, root: Path) -> dict:
|
||||
rel = path.relative_to(root)
|
||||
name_well, name_wellbore = obj.findtext(NS + "nameWell") or "", obj.findtext(NS + "nameWellbore") or ""
|
||||
wb, source = wellbore_name(name_well, name_wellbore, obj.attrib.get("uidWellbore"))
|
||||
return {"wellbore": wb, "wellbore_source": source,
|
||||
"wellbore_witsml": published_wellbore(name_well, name_wellbore)[0], "folder": rel.parts[0],
|
||||
"path": rel.as_posix(), "uidWell": obj.attrib.get("uidWell"),
|
||||
"uidWellbore": obj.attrib.get("uidWellbore"), "uid": obj.attrib.get("uid")}
|
||||
|
||||
|
||||
def _utc(s: pd.Series) -> pd.Series:
|
||||
return pd.to_datetime(s, utc=True, format="ISO8601")
|
||||
|
||||
|
||||
def parse_objects(root: Path) -> tuple[dict[str, pd.DataFrame], Flat]:
|
||||
"""trajectory, message, bhaRun and mudLog files under `root` -> tables `trajectory_catalog` (one row per
|
||||
trajectory), `trajectory` (stations), `messages`, `bha_runs`, `mudlog_catalog`, `mudlog_intervals`,
|
||||
`mudlog_lithology`, `mudlog_qualifiers`. UTC timestamps are added next to the published time strings."""
|
||||
flat = Flat()
|
||||
rows: dict[str, list[dict]] = {k: [] for k in (
|
||||
"trajectory_catalog", "trajectory", "messages", "bha_runs", "mudlog_catalog", "mudlog_intervals",
|
||||
"mudlog_lithology", "mudlog_qualifiers")}
|
||||
for path in sorted(root.glob("*/*/trajectory/*.xml")):
|
||||
obj = _object(path, "trajectorys", "trajectory")
|
||||
ids = _ids(obj, path, root)
|
||||
head = flat.leaves(obj, dict(ids), "trajectory_catalog", skip=("trajectoryStation",))
|
||||
stations = obj.findall(NS + "trajectoryStation")
|
||||
head["n_stations"] = len(stations)
|
||||
rows["trajectory_catalog"].append(head)
|
||||
for seq, st in enumerate(stations):
|
||||
row = {"wellbore": ids["wellbore"], "path": ids["path"], "traj_uid": ids["uid"],
|
||||
"traj_name": head.get("name"), "seq": seq, "uid": st.attrib.get("uid")}
|
||||
rows["trajectory"].append(flat.leaves(st, row, "trajectory"))
|
||||
for path in sorted(root.glob("*/*/message/*.xml")):
|
||||
obj = _object(path, "messages", "message")
|
||||
rows["messages"].append(flat.leaves(obj, _ids(obj, path, root), "messages"))
|
||||
for path in sorted(root.glob("*/*/bhaRun/*.xml")):
|
||||
obj = _object(path, "bhaRuns", "bhaRun")
|
||||
rows["bha_runs"].append(flat.leaves(obj, _ids(obj, path, root), "bha_runs"))
|
||||
for path in sorted(root.glob("*/*/mudLog/*.xml")):
|
||||
obj = _object(path, "mudLogs", "mudLog")
|
||||
ids = _ids(obj, path, root)
|
||||
head = flat.leaves(obj, dict(ids), "mudlog_catalog", skip=("geologyInterval",))
|
||||
intervals = obj.findall(NS + "geologyInterval")
|
||||
head["n_intervals"] = len(intervals)
|
||||
rows["mudlog_catalog"].append(head)
|
||||
for seq, gi in enumerate(intervals):
|
||||
base = {"wellbore": ids["wellbore"], "path": ids["path"], "mudlog_uid": ids["uid"], "seq": seq,
|
||||
"uid": gi.attrib.get("uid")}
|
||||
row = flat.leaves(gi, dict(base), "mudlog_intervals", skip=("lithology",))
|
||||
liths = gi.findall(NS + "lithology")
|
||||
row["n_lithology"] = len(liths)
|
||||
rows["mudlog_intervals"].append(row)
|
||||
for lseq, lith in enumerate(liths):
|
||||
lrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
|
||||
"interval_seq": seq, "seq": lseq, "uid": lith.attrib.get("uid")}
|
||||
rows["mudlog_lithology"].append(flat.leaves(lith, lrow, "mudlog_lithology", skip=("qualifier",)))
|
||||
for qseq, q in enumerate(lith.findall(NS + "qualifier")):
|
||||
qrow = {"wellbore": ids["wellbore"], "mudlog_uid": ids["uid"], "interval_uid": base["uid"],
|
||||
"lithology_uid": lrow["uid"], "seq": qseq, "uid": q.attrib.get("uid")}
|
||||
rows["mudlog_qualifiers"].append(flat.leaves(q, qrow, "mudlog_qualifiers"))
|
||||
tables = {name: pd.DataFrame(r) for name, r in rows.items()}
|
||||
for table, column in (("trajectory", "dTimStn"), ("messages", "dTim"), ("bha_runs", "dTimStart"),
|
||||
("bha_runs", "dTimStop"), ("mudlog_intervals", "dTim")):
|
||||
if column in tables[table]:
|
||||
tables[table][column + "_utc"] = _utc(tables[table][column])
|
||||
if len(tables["mudlog_intervals"]):
|
||||
tables["mudlog_intervals"]["tadi_implausible"] = tadi_implausible(tables["mudlog_intervals"])
|
||||
return tables, flat
|
||||
|
||||
|
||||
def tadi_implausible(intervals: pd.DataFrame) -> pd.Series:
|
||||
"""True where TADI (section 3.3) would drop a mudLog interval: ROP > 200 m/h, RPM > 300 or WOB > 500 kN.
|
||||
A flag only; the values stay as published."""
|
||||
out = pd.Series(False, index=intervals.index)
|
||||
for column, limit in TADI_FILTERS.items():
|
||||
if column in intervals:
|
||||
out |= intervals[column] > limit
|
||||
return out
|
||||
|
||||
|
||||
def units_table(flat: Flat) -> pd.DataFrame:
|
||||
"""(table, column, uom published, n values, uom stored, factor) for every measure of the object tables.
|
||||
Refuses a column that would be stored in more than one unit."""
|
||||
rows = []
|
||||
for (table, column, uom), n in sorted(flat.units.items()):
|
||||
stored, factor = STORED_UNITS.get(uom, (uom, 1.0))
|
||||
rows.append({"table": table, "column": column, "uom": uom, "n": n, "uom_stored": stored, "factor": factor})
|
||||
out = pd.DataFrame(rows, columns=["table", "column", "uom", "n", "uom_stored", "factor"])
|
||||
mixed = out.groupby(["table", "column"])["uom_stored"].nunique()
|
||||
if (mixed > 1).any():
|
||||
raise ValueError(f"columns stored in more than one unit: {mixed[mixed > 1].index.tolist()}")
|
||||
return out
|
||||
|
||||
|
||||
def sentinels_table(flat: Flat) -> pd.DataFrame:
|
||||
return pd.DataFrame([{"table": t, "column": c, "value": v, "n": n, "kind": "sentinel"}
|
||||
for (t, c, v), n in sorted(flat.sentinels.items())],
|
||||
columns=["table", "column", "value", "n", "kind"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
# DuckDB views over the long log tables
|
||||
# --------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def depth_filter(channels: dict) -> str:
|
||||
return " OR ".join(f"(d.mnemonic = '{m}'" + (f" AND c.name = '{name}')" if name else ")")
|
||||
for m, name in channels.items())
|
||||
|
||||
|
||||
def view_sql(out: Path) -> dict[str, str]:
|
||||
"""SELECT statements of the views over `<out>/time_log/*.parquet` and `<out>/depth_log/*.parquet`:
|
||||
|
||||
`time_log`, `depth_log` every published value;
|
||||
`time_log_dedup`, `depth_log_dedup` one value per (wellbore, mnemonic, index): the rows with dup_rank = 0.
|
||||
Not for the Baker Hughes `Depth` curve, which is the reference
|
||||
depth of its own log (9.0 of its 15.0 million collisions between logs
|
||||
disagree): select it by log, or use `drill_depth`;
|
||||
`drill_depth` hole depth and bit depth against time (`HOLE_DEPTH`, `BIT_DEPTH`), one
|
||||
value per (wellbore, time, depth): the log with the most values wins.
|
||||
"""
|
||||
hole, bit = depth_filter(HOLE_DEPTH), depth_filter(BIT_DEPTH)
|
||||
mnemonics = ", ".join(repr(m) for m in (*HOLE_DEPTH, *BIT_DEPTH))
|
||||
views = {}
|
||||
for kind in ("time", "depth"):
|
||||
views[f"{kind}_log"] = f"SELECT * FROM read_parquet('{(Path(out) / f'{kind}_log').as_posix()}/*.parquet')"
|
||||
views[f"{kind}_log_dedup"] = f"SELECT * EXCLUDE (dup_rank) FROM {kind}_log WHERE dup_rank = 0"
|
||||
views["drill_depth"] = f"""
|
||||
SELECT wellbore, time, depth, first(value ORDER BY n_values DESC, log_id) AS md,
|
||||
first(log_id ORDER BY n_values DESC, log_id) AS log_id
|
||||
FROM (SELECT d.wellbore, d.time, d.value, d.log_id, c.n_values,
|
||||
CASE WHEN {hole} THEN 'hole' ELSE 'bit' END AS depth
|
||||
FROM time_log d JOIN log_catalog c USING (log_id)
|
||||
WHERE d.mnemonic IN ({mnemonics}) AND d.value IS NOT NULL AND ({hole} OR {bit}))
|
||||
GROUP BY wellbore, time, depth"""
|
||||
return views
|
||||
|
||||
|
||||
def connect(out: Path | None = None):
|
||||
"""Read-only connection to `volve_witsml.duckdb`. The log views stored in the file name the parquet files by
|
||||
the absolute path they had when the file was built; here they are redefined (as temporary views) over the
|
||||
files next to the database, so the tables also work after the outputs folder was moved or copied."""
|
||||
import duckdb
|
||||
|
||||
from . import paths
|
||||
out = Path(out) if out else paths.outputs_dir() / "witsml"
|
||||
con = duckdb.connect(str(out / "volve_witsml.duckdb"), read_only=True)
|
||||
for name, sql in view_sql(out.resolve()).items():
|
||||
con.execute(f"CREATE OR REPLACE TEMP VIEW {name} AS {sql}")
|
||||
return con
|
||||
Reference in New Issue
Block a user