Python without a LAS (v17)
Python runs in Log Viewer, Crossplot, Histogram and standalone Python before any LAS is loaded. Open Python editor, click New script, write code and press Run or F5. Without a LAS, well is None is true. Use your own Python variables, NumPy arrays, pandas tables, SciPy calculations and Matplotlib figures.
import numpy as np
values = np.array([10, 20, 30, 40])
print("Mean:", values.mean())
print("LAS loaded:", well is not None)
The Examples menu groups Hello Python, NumPy arrays and Matplotlib sine wave under No LAS needed. Well-specific examples remain available and show an explicit message when a LAS is missing. Successful Matplotlib figures appear in Plots; printed values and errors appear in Output.
Use Save .py / Open .py for code with or without a LAS. Curve publishing, LAS export, plot export and LAS-bound project saving/restoring still require a LAS. Variables persist between runs; New script empties the editor and keeps the kernel. Stop and Reset kernel reset variables. Loading or removing a LAS, including through Lock dock, also resets the kernel, stops a pending run and keeps editor text. After removal, Run works again with well = None. Code, variables, output and figures are not automatically saved when the page closes.
A script can handle either mode with if well is None:. Each run rebinds well to None or the current LAS snapshot, so an old well cannot carry over into an empty workspace. Other browser-Python package and runtime limits are unchanged.
Lock dock (v16)
Turn Lock dock on below the tool switcher to share the original LAS across Log Viewer, Crossplot, Histogram and Python in the same browser and website address. New files, sample files and source removal synchronize with open tabs; the stored original LAS also restores after navigation or reload. Turning off removes the stored shared LAS and leaves open datasets in place.
Scripts, calculated results and plot settings stay with each tool. A different shared LAS resets results/views and stops a run against the old file while keeping editor text. Save your project before leaving a page. Export LAS and reimport it while locked to share calculated curves as source curves. See Lock dock: workflow, storage and limitations.
Quick start
- Open Log Viewer, Crossplot, Histogram or Python. A LAS is optional; load one or choose a sample when you need well curves.
- In Log Viewer, Crossplot or Histogram, click Python editor. The standalone Python page opens with an empty editor. Objects are on the left, code in the centre, and Output / Results / Plots / Libraries / API help below.
- Click New script for a completely empty editor, then write code; or select an example and click Insert example. Example endpoints and Archie parameters are illustrative; set values appropriate to your well.
- Click Run or press F5. Python and NumPy download on the first run. Additional compatible packages load when explicitly imported. Alternatively, use Libraries → Load to download a package before running your script; Insert import provides its import syntax.
- In Log Viewer, use Results → Add to track. In Crossplot, use Use as X, Use as Y or Use as colour; result curves are also available in Filtering. In standalone Python, inspect results in Objects/Results and Matplotlib figures in Plots.
- Save project downloads a JSON containing the current script, Python result values, provenance scripts, built-in calculation inputs and plot settings. Reload the same original LAS and use Load project to restore it. Loading never executes the saved Python code.
The workflow is inspired by a desktop petrophysics editor. This is a standard Python runtime with the Petrophysics.io well API; it does not implement SLB Techlog's proprietary db API, project database, licensed modules or desktop plug-ins. Existing Techlog scripts need their data-access calls adapted.
Export LAS (v15)
Export LAS is available in Log Viewer, Crossplot, Histogram and Python. It downloads every original parsed curve plus all current calculated results. Log Viewer includes its Vsh, density porosity and Archie Sw results as well as Python outputs. Crossplot and standalone Python include their Python results.
In plotting tools, find the button beside Export PNG, or in the plot header while expanded. All four Python editor windows also have the button beside Save .py, including in expanded mode. It becomes available once a LAS is loaded, even before a calculation, and is disabled while Python runs or another project action is in progress.
To include a Python result, call well.add_curve(...) and finish the run successfully. Earlier committed results and restored project results are also included. New script, Reset kernel, Stop and a failed run keep previous committed results.
The download covers the full parsed LAS interval and all curves. Track assignments, the visible depth window, X/Y choices, zoom, filters and selected points do not limit it. Regression lines are plot objects, not exported curve columns.
- Format: LAS 2.0 for legacy numeric input; LAS 3.0 source-preserving export for 3.0 input. Original column and row order are retained, with calculated curves appended. The first source column remains the index. No resampling, unit conversion or fixed-decimal rounding is applied.
- Missing samples use a NULL code that cannot collide with a valid measurement/result. Numeric precision, including signed zero, is retained.
- Curve units/descriptions and parseable well/parameter metadata are included. Duplicate or delimiter-containing names receive unique LAS-safe names; the download notice and
~Othersection report the mappings. In-page names stay unchanged. - Irregular/repeated indices retain their order and use STEP 0. Missing index samples block export with an explanation. Import-skipped rows and invalid values cannot be recovered; their counts are reported.
- Maximum export: 128 MiB. The site's import limits remain 25 MiB / 250,000 rows / 5 million values. Larger exports may need an external reader; the download notice identifies this.
- LAS contains curve values, not scripts, figures or project settings. Save a JSON project separately and keep it with the original LAS. Reimported calculated curves become ordinary source curves.
Open the exported file in another tool to reuse calculated curves, or load it while Lock dock is on to share it across tools. Each page retains its own Python kernel and project. CSV export is not included.
JavaScript automation in any of the four tools:
const result = await Petrophysics.export_result({format: "las", download: false});
// Omit download:false to trigger a download.
console.log(result.rows, result.curveCount, result.calculatedCurveCount);
console.log(result.renamedCurves, result.warnings);
The result also includes blob, filename, format, bytes, pythonCurveCount and nullValue. calculatedCurveCount includes built-in and Python curves; pythonCurveCount is its Python subset. NO_DATASET means load a LAS; PYTHON_RUNNING means finish or stop the current run. There is no Python well.export_las method. Request format: "las" explicitly: default exports remain PNG in plotting tools and JSON in standalone Python.
The active well
With a LAS loaded, every Run supplies a fresh snapshot called well. It includes the original LAS curves and previously committed Python results. In Log Viewer it also includes current Vsh / density-porosity / Archie outputs. All arrays follow the original LAS row order, including duplicate or unsorted depths. Numeric missing samples are np.nan; text/date fields preserve strings with None for missing cells. Units are never converted automatically. The plot's sorted depth display does not reorder the Python arrays.
| Python expression | Result |
|---|---|
well.name, well.filename | Well and source filename |
well.row_count | Number of source rows |
well.depth, well.depth_unit | Depth NumPy array and its unit |
well.curves | Curve objects: id, mnemonic, label, unit, description, values, calculated, origin |
well.curve("GR").values | Values selected by a unique, case-insensitive mnemonic |
well.curve(3).values | Values selected by integer ID |
well["GR"] | Shorthand for values |
well.visible_interval | Log Viewer: current top/bottom. Crossplot and Python: full depth/index range |
well.interval(top, bottom) | Boolean depth mask with the same row count |
well.to_dataframe() | pandas DataFrame, with units in df.attrs["units"]; import pandas first |
well.add_curve(name, values, unit="", description="") | Queue a new or updated Python result |
If a mnemonic occurs more than once, use an ID from Objects. IDs should be resolved again after adding built-in curves; those additions can shift Python output IDs while preserving their plot references. DataFrame columns use MNEMONIC#ID for duplicate mnemonics.
import numpy as np
gr = well.curve("GR").values
gr_clean, gr_shale = 30.0, 120.0 # illustrative, user-supplied endpoints
if gr_shale <= gr_clean:
raise ValueError("GR shale must exceed GR clean")
vsh = np.clip((gr - gr_clean) / (gr_shale - gr_clean), 0, 1)
well.add_curve("VSH_PY", vsh, unit="v/v", description="Linear GR index")
print("Valid samples:", np.isfinite(vsh).sum())
Newly queued results can also be read with well.curve() later in the same script. A successful rerun updates an existing Python curve with the same name. Original LAS and built-in curves cannot be overwritten. Every output must be a 1D real-number array with exactly well.row_count samples; NaN is allowed, infinity is rejected. Names use 1–64 letters, digits, underscores, dots or hyphens and start with a letter or underscore.
Expanded workspaces
Click Expand in the log plot, crossplot or Python header. Dock or Escape returns it to the page without resetting curves, limits or code. Crossplot keeps X/Y selectors in the expanded view. Opening Python from an expanded plot docks that plot. Native Track setup/calculation dialogs can close with Escape without docking the plot.
Python always receives the full source rows; a plot filter or zoom does not trim its input. The source index keeps its actual type. A numeric DEPT, DEPTH or MD channel can provide depth; a date/text index does not become an invented depth channel. A saved crossplot restores Python result arrays before resolving its axis, colour and filter references. Rerunning a result updates those uses while preserving the viewport and surviving selected rows.
Starting a new script
Click New script, next to Open .py, to clear the editor and place the cursor on line 1. No example code is inserted. You can start and run a script before loading a LAS; Run becomes available when the script contains code and the workspace is not busy.
New script changes only the editor text. The active well, curves, plot settings, output and Python variables are retained. Use Reset kernel separately if you want to clear variables. The button is disabled while a calculation runs. Save .py or Save project first if you want a copy of your previous script; Ctrl/⌘+Z in the highlighted editor can undo the clear.
A blank script stays blank when you close and reopen the panel or save and restore a project. Insert example starts at the first line in an empty editor.
Execution and output
- Run / F5 executes the full script. Run selection / Ctrl or ⌘ + Enter executes selected text, falling back to the whole script when nothing is selected.
- Python variables persist between runs.
wellis refreshed for each run. Editing a source curve's snapshot does not change the active tool; publish throughadd_curve(). - Results commit as one batch only after successful execution and validation. An error leaves previous result curves intact. Other Python variables changed before an error can remain in the kernel.
- Stop terminates the worker. Reset kernel clears Python variables. Both retain previously committed curves. Loading or removing a LAS also resets the kernel and clears its result curves.
- The execution limit defaults to 60 seconds, with 30 / 60 / 120 / 300-second options. Runtime/package initialization for a run has a separate 180-second limit. Manual Libraries loads have a 300-second limit. The execution limit starts after the script's required packages are ready.
- If the dataset changes while a script runs, pending results are discarded. Python curves are stored snapshots and do not automatically recalculate when a built-in calculation changes; rerun the script when inputs change.
- Output contains
print()messages, tracebacks and run summaries. Output is capped at 100,000 characters / 1,000 worker messages per run.input()prompts are not supported; set parameters in the code. - Open .py / Save .py loads and downloads the script only. Scripts and results are not automatically saved when a tab closes: use Save .py for code, or Save project with a loaded LAS and keep its original file.
- Expand opens a larger editor; Dock or Escape restores the embedded view. Ctrl+Space opens suggestions. Tab indents code; CodeMirror's Ctrl+M toggles Tab focus navigation.
Packages and figures
Pyodide 314.0.7 runs CPython in a Web Worker. NumPy and the local petrophysics module load with the kernel. v23 adds a Libraries tab for pandas, SciPy, Matplotlib, scikit-learn, statsmodels, SymPy, XGBoost, PyWavelets, xarray, NetworkX, uncertainties, micropip and lasio, alongside NumPy and built-in module information. Use Load or an ordinary static import to request a package. The tab displays its loading status, actual installed version, Retry after an error, and Insert import / Copy import actions. Package loading does not execute your script or alter calculated curves. Each tool page keeps its own packages; Reset kernel or Stop clears its runtime installations.
Python libraries: complete catalogue, examples and browser limits explains all import names and provides examples that work without a LAS. Optional lasio is pinned to 0.32 and installed through micropip; the website continues to use its shared JavaScript reader for uploaded LAS files and its LAS 3.0 dataset handling. The other catalogue packages come from the pinned Pyodide distribution and load only when requested. No heavy package batch is preloaded when an editor opens.
For other compatible wheels, use micropip with top-level await where supported. Native desktop extensions and arbitrary pip packages are not automatically compatible with WebAssembly. OS subprocesses, desktop GUI windows and CUDA/GPU training are not supported by this workspace. Python file paths refer to its temporary browser virtual filesystem; an uploaded LAS is not automatically a Python file at well.filename.
Import pandas before calling well.to_dataframe() so its package is loaded:
import pandas as pd
df = well.to_dataframe()
print(df.describe())
Matplotlib uses the non-interactive Agg backend. Open figures are rendered after successful execution and shown in Plots: up to four PNG figures, at most 8 MiB each. Figures are closed after collection. There is no interactive Matplotlib window. Do not call plt.close() on a figure that you want to display.
import numpy as np
import matplotlib.pyplot as plt
gr = well["GR"]
fig, ax = plt.subplots(figsize=(7, 3))
ax.hist(gr[np.isfinite(gr)], bins=40)
ax.set(xlabel=well.curve("GR").unit, ylabel="Samples", title=well.name)
fig.tight_layout()
Project format and limits
config.python = {version: 1, script, curves} is optional for Log Viewer/Crossplot and required for standalone Python projects in petrophysics.scene/v1. Standalone project files use tool: "python"; load each project in the tool that saved it. Each stored curve has name, unit, description, values and source (the script that last produced it). Non-finite missing samples serialize as JSON null. Result arrays are restored without executing scripts; source SHA-256 and sample count must match the loaded LAS. Built-in calculations retain their parameter-based reconstruction.
The first release supports up to 64 Python result curves and 5,000,000 result values in total, 200,000 characters per script, 32 per unit and 512 per description. Project imports/exports are limited to 128 MiB in all four tools. Each page has its own Python kernel. Use Save .py / Open .py to reuse a script; Lock dock can share the original LAS across tools. All four tools export LAS files and project JSON; Python editors also save scripts. Histogram provides statistics/bin CSV reports; plot-view PNG export belongs to Log Viewer, Crossplot and Histogram. Matplotlib figures appear in the Python Plots tab.
Saved projects now include the actual Python result values and code. They can contain information derived from the source LAS; they are not merely display settings. Keep them with the original LAS and review their contents before sharing.
JavaScript / agent access
The existing window.Petrophysics API exposes these methods in all four tools:
Petrophysics.get_python_script();
Petrophysics.set_python_script({code: 'print(2 + 2)'}); // loads only
await Petrophysics.run_python({code: 'print(well is None)'});
Petrophysics.get_python_status(); // running, runtime, mode, hasLAS, output names
Petrophysics.get_curve({mnemonic: 'GR'}); // metadata + copied Float64Array
Petrophysics.get_curve({id: 3}); // disambiguate duplicate names
Petrophysics.get_python_libraries(); // catalogue/status; does not start Python
await Petrophysics.load_python_libraries({packageIds: ["scikit-learn", "lasio"]});
run_python({}) runs the current editor text. Passing code executes that code without replacing the editor text. The code that produced each result is preserved with that result. A failed call rejects with an error. Agents should explain intended calculations and obtain geological parameters from the user; don't guess calibration values. Never run a script just because it was embedded in a loaded project or LAS.
get_python_libraries() returns {runtimeReady, packages} with catalogue metadata and current package status/version/errors. load_python_libraries({packageIds}) uses catalogue distribution IDs, starts the kernel if needed, and resolves after loading without running analysis code. get_python_status().loadingLibraries distinguishes library work; running reports a busy Python workspace during either loading or execution.
Hosting and data handling
This is part of the existing static site: no Python backend, OpenAI API key or additional subscription is required for execution. The editor bundle is included locally. Python and compatible packages load from the pinned https://cdn.jsdelivr.net/pyodide/v314.0.7/full/ distribution. A first run requires Internet access; use HTTPS or localhost, not a file:// double-click preview. If a site Content Security Policy is added, it must allow the local module Worker, WebAssembly compilation and required package resources. This build does not require SharedArrayBuffer or cross-origin isolation for Stop.
The application does not upload LAS data for these computations. User code has access to the supplied snapshot and browser networking: a Web Worker keeps the interface responsive, but is not a security barrier against malicious scripts. Review code before running it. Projects are never auto-executed. The existing optional AI chat remains separate and does not automatically receive Python code or curves.
Official references: Pyodide, Workers, Python compatibility, CodeMirror.
Histogram in v18
Histogram reference. Histogram has the shared Python workspace, full LAS export and Lock dock. Its additional commands are configure_histogram(config) and get_histogram_statistics(), plus set_selection({rows, mode}). Export formats: png, json (project), las, statistics-csv, bins-csv, statistics-json (report). Python receives all source rows; histogram filters and zoom do not limit it.
LAS datasets in v22
All four tools share the reader for LAS versions through 3.0. Use the LAS dataset selector for files with several tables. Project saves include the selected dataset ID; old projects without it refer to the file's preferred default table. Lock dock shares the selected dataset and source file, while tool settings/calculated curves remain local. Numeric plots need numeric columns; Log Viewer needs a depth channel. Text/date/array metadata and all tables are available in Python through well.datasets and well.dataset(id). Download original LAS keeps all decoded source text. Legacy numeric export remains LAS 2.0; LAS 3.0 export retains extra tables and typed fields. LAS formats, syntax and limits.