19 - Generate LLM Context from Well Logs¶
Part B - Petrophys Curriculum
This lesson turns LAS data into compact, auditable JSON context packages organized by
analysis category, well, formation, and lithology group. It uses only public petrophys
APIs and bundled sample data, so it runs without machine-specific paths.
The generated JSON is model-neutral: use it with any LLM client, retrieval system, or review workflow. Nothing in this lesson calls a model or the network.
Learning goals¶
Build context for one interpreted well with
pp.export_context(result)and save it withpp.export_context(result, path).Generate a computed package organized by category, formation and lithology group from a folder of LAS files plus optional formation and lithology tables.
Select one level of a ranked formation table (
rank="formation") so groups and their formations are not counted twice.Enforce byte budgets and inspect provenance, warnings and limitations.
Build a model-neutral request without making a network call.
Prerequisites¶
Lesson 10 (
pp.interpret, the step trace, skip reasons and warnings) and lesson 11 (formation tops andrank="formation").The base install. Context generation runs locally and writes JSON; no LLM account, API key or network access is needed.
The Rw convention used throughout the course: for 30/6-5, Rw = 0.070 ohm.m measured at 230 degF (
rw=0.070, rw_meas_temp="230 degF"). Without the temperature the library takes Rw at the median formation temperature, which changes saturation strongly.
Why this matters¶
A language model knows only the text you give it. Raw depth-by-depth curves waste its
context window and leave it to invent the interpretation; a free-text summary hides
the assumptions. A context package sits in between: every number comes from the same
traced workflow as pp.interpret, grouped by the question being asked (hydrocarbon,
saturation, permeability, …), bounded in size, and accompanied by the inputs,
warnings and data gaps a reviewer needs to judge it. The same files serve a retrieval
index, a review checklist or a human reader.
What the exporter produces¶
For each formation and lithology group, the package exporter writes separate views for hydrocarbon, saturation, permeability, porosity, numerical statistics, and lithology analysis. Each JSON file records the source well, formation interval, input logs, computed logs, statistics, analysis results, data completeness, and bad-hole QC.
Raw depth-by-depth traces are intentionally excluded by default. This keeps context smaller while retaining the statistics and provenance needed for interpretation and review.
1. Context for one interpreted well¶
pp.export_context(result) turns an interpretation result into a JSON-safe dictionary
(schema 1.0) and never reruns a calculation; pp.export_context(result, path) writes
the same content to a file and enforces a byte budget (1,000,000 UTF-8 bytes by
default). Pass the result, not the raw well: only the result carries the calculated
curves and the workflow provenance. The dictionary’s top-level keys are shown below the
cell: the well, its interpretation and its geology.
Interpreting 30/6-5 prints UserWarnings: the core saturation curves SWC and SOC
are stored in percent although the file labels them frac, so Petrophys divides them
by 100 and says so. They reappear whenever this file is interpreted, including inside
the package export below.
import json
import shutil
from pathlib import Path
from tempfile import mkdtemp
import petrophys as pp
result = pp.interpret(pp.read(pp.sample("30_6-5")), rw=0.070, rw_meas_temp="230.0 degF") # Rw (ohm.m) at 230 degF
context = pp.export_context(result)
list(context)
[repository]\src\petrophys\preprocessing\standardization\curve_standardizer.py:851: UserWarning: SWC: inferred percent core saturation despite unit 'frac'; divided by 100 to v/v. Verify source units.
standardize_core_saturation(new_curve, inplace=True)
[repository]\src\petrophys\preprocessing\standardization\curve_standardizer.py:851: UserWarning: SOC: inferred percent core saturation despite unit 'frac'; divided by 100 to v/v. Verify source units.
standardize_core_saturation(new_curve, inplace=True)
['schema_version',
'petrophys_version',
'context_kind',
'well',
'interpretation',
'geology',
'include_raw_traces_in_context']
Given a path, the same summary is written to a file, and the path is returned:
pp.export_context(result, "30_6-5_context.json").name
'30_6-5_context.json'
2. A folder of LAS files¶
A package export reads a folder of LAS files. Only the LAS is mandatory; this
example also supplies optional formation and lithology tables. We copy the bundled
30/6-5 LAS into a logs folder inside a fresh run folder and write everything below
it. Supported well parameters
and core curves are read from the LAS when present.
run = Path(mkdtemp()) # a fresh folder for this run
(run / "logs").mkdir()
shutil.copy(pp.sample("30_6-5"), run / "logs");
For your own data, replace the LAS path and optionally fill the packaged formation or
lithology templates. CSV, TSV and Excel geology tables are accepted, including NPD/SODIR
Well identifier / Surface / MD headers. The
Context Export guide lists the sheet and depth metadata to supply.
3. Inspect the ranked formation table¶
The bundled 30/6-5 table declares metre depths, explicit bottoms, a rank (group or
formation) and a parent for each row. Groups overlap the formations they contain -
for example BRENT GP. (the Brent Group, 2841-2958 m) contains the Ness and Etive
formations - so a package built from every row would describe the same rock twice.
Select one level with tops_options={"rank": "formation"} (12 of the 20 rows below);
do not try to infer the hierarchy by deleting nested rows.
pp.read_formations(pp.sample("formations_30_6-5"))[["formation_name", "top_depth", "bottom_depth", "rank", "parent"]]
| formation_name | top_depth | bottom_depth | rank | parent | |
|---|---|---|---|---|---|
| 0 | NORDLAND GP. | 181.0 | 726.0 | group | |
| 1 | Utsira Fm. | 726.0 | 879.0 | formation | |
| 2 | HORDALAND GP. | 879.0 | 1908.0 | group | |
| 3 | ROGALAND GP. | 1908.0 | 2203.0 | group | |
| 4 | Balder Fm. | 1908.0 | 2023.0 | formation | ROGALAND GP. |
| 5 | Sele Fm. | 2023.0 | 2123.0 | formation | ROGALAND GP. |
| 6 | Lista Fm. | 2123.0 | 2203.0 | formation | ROGALAND GP. |
| 7 | SHETLAND GP. | 2203.0 | 2408.0 | group | |
| 8 | CROMER KNOLL GP. | 2408.0 | 2452.0 | group | |
| 9 | VIKING GP. | 2452.0 | 2841.0 | group | |
| 10 | Draupne Fm. | 2452.0 | 2593.0 | formation | VIKING GP. |
| 11 | Heather Fm. | 2593.0 | 2841.0 | formation | VIKING GP. |
| 12 | BRENT GP. | 2841.0 | 2958.0 | group | |
| 13 | Ness Fm. | 2841.0 | 2865.0 | formation | BRENT GP. |
| 14 | Etive Fm. | 2865.0 | 2958.0 | formation | BRENT GP. |
| 15 | DUNLIN GP. | 2958.0 | 3223.0 | group | |
| 16 | Drake Fm. | 2958.0 | 3071.0 | formation | DUNLIN GP. |
| 17 | Cook Fm. | 3071.0 | 3123.0 | formation | DUNLIN GP. |
| 18 | Amundsen Fm. | 3123.0 | 3223.0 | formation | DUNLIN GP. |
| 19 | Statfjord Fm. | 3223.0 | 3556.0 | formation |
4. Generate bounded, category-first context¶
pp.export_context with layout="package" reads every LAS in the folder, applies
optional geology inputs, runs the workflow, groups the results by formation and
lithology, and validates every file before publishing the new directory. Groups thinner
than minimum_group_thickness (2.0 by default, in the LAS depth unit) are left out,
and each JSON document must fit in max_bytes (1,000,000 by default). Category
documents contain the computed context directly, without replay or a wrapper object. A
failed or oversized export raises an exception without leaving a partial destination.
The call returns one record per document written; there are 72 of them here.
records = pp.export_context(run / "logs", run / "context", layout="package",
formations=pp.sample("formations_30_6-5"),
lithology=pp.sample("lithology_30_6-5"),
tops_options={"rank": "formation"})
len(records)
[repository]\src\petrophys\preprocessing\standardization\curve_standardizer.py:851: UserWarning: SWC: inferred percent core saturation despite unit 'frac'; divided by 100 to v/v. Verify source units.
standardize_core_saturation(new_curve, inplace=True)
[repository]\src\petrophys\preprocessing\standardization\curve_standardizer.py:851: UserWarning: SOC: inferred percent core saturation despite unit 'frac'; divided by 100 to v/v. Verify source units.
standardize_core_saturation(new_curve, inplace=True)
72
5. Summarize and review warnings¶
The API has already checked for failures. Still read the warnings before interpreting
the exported statistics; successful serialization is not scientific validation. For
example, the package export passes no Rw: it takes the bundled 30/6-5 header values,
RW = 0.070 ohm.m with its measurement temperature RWT = 230 degF (the course
convention), and corrects Rw along the temperature profile. The workflow records that
source in the trace so it can be reviewed; a header Rw without a temperature, or with
a wrong value, would flow into every exported saturation in the same way. The run’s
distinct warnings follow: the bad-hole flag removing net pay, the lithology intervals’
uncovered samples, the routing convention for marl, and the PEF set aside in the
mineral solution.
sorted({warning for record in records for warning in record.warnings})
["Bad hole removed 53.93 m of net pay (BAD_HOLE at 12631 of 22176 samples). Check the flag against the caliper and DRHO; bad_hole={'drho': ..., 'cali': ...} sets its thresholds and skip_steps=['bad_hole'] keeps the pay.",
'External lithology: unmapped labels [], 30 uncovered samples. Labels/gaps are preserved; unclassified samples use configured calculation fallbacks, not inferred rock labels.',
'Held readings, one value repeated exactly over ten samples or more: RHOB 1.8 over 180.42-242.752 m (411 samples), RSHA 7.012 over 3537.94-3555.32 m (116 samples), RHOB 1.9602 over 1461.19-1468.66 m (51 samples), GR 187.5 over 3548.77-3556.08 m (50 samples), RHOB 1.899 over 529.416-536.274 m (47 samples) and 28 more. A tool that stopped reading, or a log padded to a depth, holds its last value while the other logs change; check these against the other logs before using them.',
'Marl uses the limestone matrix and carbonate cutoff family. This is a routing convention, not a calibrated marl model; check clay correction and supply project-specific cutoffs.',
'Net pay where the gamma ray reads shale and neutron-density clean, VCL_GR above VCL_ND by more than 0.5: 2805.05-2805.66 m (VCL_GR 0.78, VCL_ND 0.15), 3272.77-3273.07 m (VCL_GR 0.72, VCL_ND 0.05). VCL takes the lower value, so these beds count as clean rock; check the density and neutron there (a density read too light in bad hole or near a casing shoe, gas, heavy minerals).',
'lithology: PEF set aside: in 96% of 259 clean porous samples the apparent matrix density is quartz-like (< 2.67 g/cm3) but the apparent matrix U calcite-like (> 10 b/cm3), the signature of barite-weighted mud; minerals solved without PEF']
The package holds one folder per analysis category, next to the curve-name mapping it used:
sorted(path.name for path in (run / "context").iterdir())
['curve_name_mapping.json',
'hydrocarbon',
'lithology',
'numerical',
'permeability',
'porosity',
'saturation']
Inside each category, the layout is <category>/<well>/<formation>/<formation>_<lithology group>_<category>.json:
one folder per formation of the selected rank, here the 12 formations from the Utsira
down to the Statfjord.
sorted(path.name for path in (run / "context" / "hydrocarbon" / "30_6-5").iterdir())
['AMUNDSEN FM',
'BALDER FM',
'COOK FM',
'DRAKE FM',
'DRAUPNE FM',
'ETIVE FM',
'HEATHER FM',
'LISTA FM',
'NESS FM',
'SELE FM',
'STATFJORD FM',
'UTSIRA FM']
6. Inspect one context document¶
Choose the category that matches the question being asked. Here we open the hydrocarbon
context of the Etive Formation (Brent Group): its sandstone group. Every document has
the same top-level parts - the formation interval (formation_info), the analysis
(analysis_results: well, formation, lithology group, input logs, computed logs,
statistics, data completeness, bad-hole QC) and the raw-trace flag; raw traces are left
out by default.
path = next((run / "context" / "hydrocarbon" / "30_6-5" / "ETIVE FM").glob("*SANDSTONE*.json"))
document = json.loads(path.read_text(encoding="utf-8"))
path.name, list(document), document["formation_info"]
('ETIVE FM._SANDSTONE_GROUP_1_hydrocarbon.json',
['formation_info',
'analysis_results',
'raw_log_traces_in_segment',
'include_raw_traces_in_context'],
{'name': 'ETIVE FM.',
'min_depth': 2865.0986,
'max_depth': 2957.9102,
'thickness': 92.8115,
'depth_unit': 'm'})
Scientific review, beyond schema¶
Before an LLM sees a document, check that it has the parts above and inspect a known interval and the assumptions used to calculate it. The saturation context of the same Etive sandstone group gives the mean SW and the mean Rw that reached it (about 0.07 ohm.m expected from the header value, corrected for temperature). These numbers do not establish hydrocarbons, validate the chosen calibration, or justify shale/overburden pay flags. Review clay-volume methods, bad-hole QC, saturation-model assumptions, and supplied geology before treating cutoff screening as pay.
path = next((run / "context" / "saturation" / "30_6-5" / "ETIVE FM").glob("*SANDSTONE*.json"))
statistics = json.loads(path.read_text(encoding="utf-8"))["analysis_results"]["statistics"]
statistics["SW_overall"]["arithmetic_mean"], statistics["RW_overall"]["arithmetic_mean"]
(0.7999, 0.0718)
The Etive sandstone group’s mean SW is 0.798, and the mean Rw that reached it is 0.072 ohm.m: the header value of 0.070 ohm.m at 230 degF, corrected along the temperature profile.
7. Build a model-neutral LLM request¶
Keep measured inputs, computed outputs, warnings, and missing-data statements intact. Ask the model to distinguish observation from inference and to avoid inventing values. The object below can be serialized for any LLM SDK or stored in a retrieval index.
llm_request = {
"task": "Summarize the interval's measured evidence, calculations and limitations.",
"instructions": [
"Use only the supplied context.",
"Separate measurements from calculated interpretations.",
"Do not infer missing values or equate cutoff screening with confirmed pay.",
"Report well, formation, lithology group and depth interval.",
"Retain QC warnings and state which assumptions need calibration.",
],
"petrophysical_context": document,
}
len(json.dumps(llm_request).encode("utf-8")) # UTF-8 bytes; no LLM or network call was made
27179
CLI equivalent¶
petrophys-context well.las context.json --formations formation_intervals.csv --lithology lithology_intervals.csv
petrophys-context logs outputs/context_run_01 --layout package --formations formation_intervals.csv --lithology lithology_intervals.csv --tops-rank formation
Remove flags for optional inputs that are unavailable. Supported Rw, temperature and
Archie parameters come from LAS metadata; use --lithology-domain carbonate when the
broad mineral-solving domain is not stored in the LAS. The command always computes
context from the LAS and supplied geology tables.
Pitfalls¶
Pass the result, not the raw well.
pp.export_context(well)only summarizes what the well already holds; without an interpretation there are no calculated curves and no trace.State Rw with its temperature. Store
RWandRWTtogether in LAS metadata, or in Python passrwwithrw_meas_temp. Otherwise the library documents its reference-temperature assumption.Choose one formation level. Mixing groups and formations describes the same rock twice; use
tops_options={"rank": "formation"}(CLI:--tops-rank formation).Package directories are never overwritten. Export into a new directory; an existing one raises
FileExistsError.minimum_group_thicknessis in the LAS depth unit - 2.0 means 2 m for a metric LAS and 2 ft for a foot-based one.Serialization is not validation. Schema checks prove the files are well formed, not that the calibration, clay model or pay flags are right.
Default context uses the maintained calculations. Package exports (
pp.export_contextwith alayout, andpetrophys-context) interpret every well with the default calculation profile,"current". To regenerate the calculations of the GeoLink eval context package instead, passcontext_profile="geolink"with its raw LAS folder, tops workbook and lithology codebook (likewise"costa"and"danish"for the other two packages).
Recap¶
pp.export_context(result)andpp.export_context(result, path)work without geology.The CLI always interprets LAS input before exporting context.
Package exports use LAS metadata and accept optional geology tables.
Exports are byte-bounded and package directories are never overwritten.
Rw always travels with its measurement temperature.
Warnings and physical calibration matter beyond JSON/schema checks.
Context generation is model-neutral and makes no LLM request.
Try it yourself¶
Exercise 1. Export the same inputs into a new directory with
zones=, a table of your own intervals (zone,top,bottom). How do the folder names and the keys of a group’s JSON differ from the formation and lithology groups?Exercise 2. Re-run the package export into a new directory with
max_bytes=5_000. What exception do you get, and what is left on disk?Exercise 3. Copy the LAS into a new logs folder, delete the
RWTparameter from its header (for example withlasio), and export again into a new directory. What does the Rw decision in the trace say, and how does the Etive saturation mean change?
What’s next¶
Continue with 20_mcp_server.ipynb. Instead of preparing context for a model, it lets an LLM client call Petrophys directly through the Model Context Protocol: load wells, interpret, explain steps, summarize zones and plot - with every number coming from the same traced workflow.