TheTechIdea OilGas - Developer guide User guide →

Scenarios

Each scenario below is compiled and executed by the test suite (ScenarioTests.cs), so the code is known to work. The findings of the review that produced them are in Design review & status.

Desktop viewer

Load through a mapping profile, build the view, host it in a canvas, validate and export.

// Application start-up: load the customer's environment once (in an app: WellboreServices.Global = ...).
// Here it is scoped by the caller; see the multi-tenant scenario.

// 1. Load a well through a mapping profile (the environment's profile folder is searched first).
var provider = new MappedWellDataProvider(new CsvTabularSource(csvFolder), MappingProfile.Load("csv"));
WellLoadResult result = await provider.LoadWellAsync("CSV-1");
foreach (var warning in result.Warnings) Console.WriteLine("data: " + warning);

// 2. Build the view: schematic + tally + logs / pressure / core tracks from the log family.
var view = WellModelConverter.ToWellboreView(result.Model,
    new WellModelConversionOptions { ExtraTracks = WellLogTracks.FromModel, GenerateBarriers = true }, out var conversionWarnings);

// 3. Host it: WellboreView draws on any SkiaSharp canvas; wire it to your UI control (see README): zoom, pan, cursor, selection, top dragging.
var canvas = new WellboreView { Document = view, Width = 1600, Height = 1000 };
canvas.View.SetRange(view.Axis, 9000, 12000);                       // zoom to the completion
canvas.MarkerMoved += (s, move) => Console.WriteLine($"{move.Marker.Name} moved to {move.To}");

// 4. Check the data before showing it, then export what the user sees (ToPdf, ToSvg or ToPng).
IReadOnlyList<WellboreIssue> issues = canvas.Validate();
using var pdf = new MemoryStream();
int pages = WellboreExport.ToPdf(view, pdf);

Headless batch reports

A background service producing print-ready PDFs with the customer's print settings; wells with errors are skipped.

// A service producing print-ready PDFs for many wells, with the customer's print settings (paper, scale, header fields).
var environment = WellboreEnvironment.FromJson(@"{ ""printing"": { ""paper"": ""A3"", ""scaleRatio"": 1000, ""headerFields"": { ""Company"": ""Acme"" } } }");
using (WellboreServices.Scope(environment))
{
    var provider = new MappedWellDataProvider(new CsvTabularSource(csvFolder), MappingProfile.Load("csv"));
    foreach (var wellId in new[] { "CSV-1" })                        // e.g. (await provider.ListWellsAsync()).Select(w => w.Id)
    {
        var model = (await provider.LoadWellAsync(wellId)).Model;
        var view = WellModelConverter.ToWellboreView(model, new WellModelConversionOptions { ExtraTracks = WellLogTracks.FromModel }, out _);
        var blocking = WellboreValidator.Validate(view).Where(i => i.Severity == WellboreIssueSeverity.Error).ToList();
        if (blocking.Count > 0) { Console.WriteLine($"{wellId}: {blocking.Count} error(s), report skipped"); continue; }
        using var pdf = new MemoryStream();                           // File.Create($"{wellId}.pdf") in a real service
        int pages = WellboreExport.ToPdf(view, pdf, new WellborePrintOptions());   // options default from the environment
        Console.WriteLine($"{wellId}: {pages} page(s)");
        Assert.True(pages > 0);
    }
}

Import pipeline

Combine a database (or CSV), a WITSML survey and LAS logs into one canonical model and persist it. Loaders never replace data silently: replacing an existing survey is reported.

// Combine sources into one canonical model: database / CSV (mapping profile) + WITSML survey + LAS logs.
var model = (await new MappedWellDataProvider(new CsvTabularSource(csvFolder), MappingProfile.Load("csv")).LoadWellAsync("CSV-1")).Model;
var witsml = WitsmlReader.Load(witsmlTrajectory, model);             // replaces the survey - and says so
var lasResult = LasReader.Load(las, model);                          // adds a LogSet
foreach (var w in witsml.Warnings.Concat(lasResult.Warnings)) Console.WriteLine("import: " + w);

// Persist the canonical model (versioned JSON) and read it back anywhere - no UI needed.
string json = model.ToJson();
WellModel restored = WellModel.FromJson(json);

Well integrity review

Two-barrier check on every leak path, MAASP limits per annulus, cement bond log turned into reviewed barrier status, and what changed between the planned and the as-built completion.

// Barriers, leak paths, annuli / MAASP, cement evidence and planned-vs-as-built - with the customer's criteria.
var doc = WellModelConverter.ToSchematic(model, new WellModelConversionOptions { GenerateBarriers = true, GenerateAnnuli = true }, out _);

// Two-barrier check on every leak path (required count and impaired rule from the environment).
LeakPathResult leaks = LeakPathTemplates.Analyze(doc)!;
Console.WriteLine($"weakest path: {leaks.MinBarriers} barrier(s), requirement met: {leaks.MeetsRequirement}");

// MAASP screening per annulus (deratings from the environment).
foreach (var annulus in doc.Annuli)
    foreach (var limit in SchematicAnnuli.Screen(doc, annulus))
        Console.WriteLine($"{annulus.Name}: {limit.Name} {limit.Psi:0} psi ({limit.Basis})");

// Cement bond log -> evidence -> reviewed status proposals for cement barrier elements.
var intervals = CementEvaluation.Intervals(cbl, new CblCalibration());             // calibration from the environment
var evidence = CementBondTracks.Evidence(intervals);
var proposals = BarrierEvidence.ProposeCementStatus(doc.Barriers!, e => BarrierTemplates.ElementInterval(doc, e), evidence, "ft", "CBL 2026-09");
int applied = BarrierEvidence.Apply(proposals.Where(p => p.Proposed != p.Current), DateTime.UtcNow, "CBL 2026-09");

// What changed between the planned and the as-built completion.
List<WellChange> changes = WellStateDiff.Compare(planned, asBuilt);

Geology: correlation and cross-sections across naming conventions

With a stratigraphic lexicon in the environment, tops named differently by different companies correlate by unit.

// Tops named by different companies still correlate: the lexicon maps "DRAUPNE FM" and "Top Draupne" to one unit.
var a = Well("A", 85, ("Top Draupne", 9000), ("Top Hugin", 9480));
var b = Well("B", 40, ("DRAUPNE FM", 9120), ("HUGIN FM", 9650));

var panel = new CorrelationPanel { Reference = DepthReference.TVDSS, FlattenOn = "Draupne Formation" };
panel.Wells.Add(new CorrelationWell { Document = a });
panel.Wells.Add(new CorrelationWell { Document = b, DistanceFromPrevious = 4200 });
IReadOnlyList<string> shared = panel.SharedTops();                                   // Draupne, Hugin

// The same wells on a map line, at true horizontal distance (projected coordinates).
var section = new CrossSectionPanel { Name = "A-B" };
section.Line.Add((0, 0)); section.Line.Add((6000, 0));
section.Wells.Add(new CrossSectionWell { Document = a, X = 500, Y = 0 });
section.Wells.Add(new CrossSectionWell { Document = b, X = 4700, Y = 150 });

// Interpreters adjust picks on the canvas (drag, or in code) with undo.
var canvas = new WellboreView { Document = a };
canvas.MarkerEdited += (s, edit) => Console.WriteLine($"{edit.Kind}: {edit.Marker.Name}");   // save picks back to your store
var heather = canvas.AddMarker("Top Heather", 9300);
canvas.UndoMarker();                                                                   // additions and removals are undoable too

Following a log on a WITSML store

WitsmlStoreClient calls a WITSML 1.4.1.1 store over SOAP (WMLS_GetVersion, WMLS_GetFromStore) with basic authentication over https, a timeout, and retries for transient failures only; SOAP faults and negative WITSML results raise WitsmlStoreException with the server's message. WitsmlGrowingLogSource.FromStore asks for data after the last index, so polling resumes after a disconnect. The message namespace and SOAPAction prefix follow the standard WSDL and can be changed for stores that differ. (ETP 1.2 is not implemented yet.)

// Follow a log on a WITSML 1.4.1.1 store: each poll asks only for data after the last index received.
var client = new WitsmlStoreClient(new WitsmlStoreOptions
{
    Endpoint = new Uri("https://store.example/witsml"), UserName = "fahad", Password = "secret"   // https required with credentials
}, store /* omit: real HTTP */);
var version = await client.GetVersionAsync();                                    // connection check
var source = WitsmlGrowingLogSource.FromStore(client, new WitsmlLogReference { UidWell = "W1", UidWellbore = "WB1", UidLog = "L1", IndexUnit = "m" });
var added = await feed.PollAsync(source);                                        // call on a timer; transient failures are retried

Symbols: company libraries and preview

New built-in symbols are drawn in tools/symbol-library (see its README: "Adding a symbol"); CI checks that the shipped catalog matches the sources. Company symbols can stay separate: merge them over the built-in library at runtime, check them with Validate (WS070-WS075) and preview them in the symbol view's gallery.

// Company symbols over the built-in library (same id replaces); check them before use.
var catalog = SymbolCatalog.Default.Merge(SymbolCatalog.FromJson(json));
var problems = catalog.Validate();                                         // WS070-WS075
// preview: the symbol view's gallery, filtered, click or arrow keys to select
var gallery = new WellSchematicSymbolView { Catalog = catalog, GalleryMode = true, Filter = "gauge", Width = 450, Height = 600 };

Survey position uncertainty

SurveyUncertainty.Compute follows the ISCWSA structure: each error source has a size, a weighting function and a mode (random per station, systematic along the survey, global); error derivatives use balanced-tangential geometry. The result per station is a north / east / vertical covariance with horizontal and vertical-section ellipses. The default sources are a simplified MWD subset - configure your tool model's sources and values in survey.uncertainty.

// Position uncertainty per survey station (ISCWSA structure; error sources in the environment's survey.uncertainty).
var trajectory = doc.DepthReference!.Trajectory!;
var atTd = SurveyUncertainty.Compute(trajectory).Last();
var (major, minor, azimuth) = atTd.HorizontalEllipse;                    // 2-sigma ellipse, major axis azimuth from north
var sigmaTvd = atTd.SigmaVertical;
// show the ellipses in the plan or section view of a trajectory track
doc.Tracks.Add(new TrajectoryTrack { View = TrajectoryView.Plan, ShowUncertainty = true });

Pinch-outs, truncations and several sections

CrossSectionLayout.Horizons ends a surface that is missing in a neighbouring well between the two wells (TerminationFraction): against the lowest overlying top listed in Unconformities (truncation), otherwise on the next deeper surface present in both wells (pinch-out). Zones run down to the next surface present at each point, so pinch-outs taper and nothing is left unfilled. HorizonInterpolation.Smooth draws a monotone cubic through the picks.

// A top missing in a well ends between the wells: against an unconformity (truncation) or on the surface below (pinch-out).
section.Unconformities.Add("Base Cretaceous");
section.Interpolation = HorizonInterpolation.Smooth;                        // optional: smooth, never overshoots the picks
var horizons = CrossSectionLayout.Horizons(section, CrossSectionLayout.Paths(section));
var sandA = horizons.Single(h => h.Name == "Sand A").Terminations.Single();  // Truncation at the unconformity, midway to W3
// several sections: CrossSectionRenderer.DrawStacked(canvas, bounds, sections); PanelExport.ToPdf(sections, stream)

Equipment attributes and rules

Typed fields cover sizes, ratings, material and identifiers; EngineeringAttributes.Extra holds company-specific values. EquipmentRules applies the environment's rules per component type ("", prefix such as "PACKER_", exact type) and reports WE001-WE005; equipment.tallyColumns chooses the completion tally columns, attribute keys included.

// Ratings and materials live in typed fields; company-specific values go in Extra ("value unit" for quantities).
packer.Attributes.PressureRating = new Quantity(690, "bar");
packer.Attributes.Extra["elastomer"] = "HNBR";
var rating = EquipmentRules.Display(packer.Attributes, "pressureRating", "psi");     // "10007.6"
// Rules per type come from the environment (equipment.attributes); problems carry codes WE001-WE005.
var issues = EquipmentRules.Validate(model);                                     // also part of the view's validation

Change history (audit trail)

ModelAudit.Record compares two versions of a well and appends who / what / when / why to WellModel.Audit; the audited ApplyEdits overload logs schematic edits; comparisons (WellStateDiff.Compare, the changes track) show the author and date.

// Record who changed what and when; the trail is saved with the model and shown in comparisons.
ModelAudit.Record(asBuilt, afterWorkover, author: "fahad", reason: "workover 2026: isolate lower zone", source: "import");
// schematic edits written back to the model are logged too: WellModelConverter.ApplyEdits(schematic, model, "fahad", "why")
var history = ModelAudit.History(afterWorkover, "CIBP-1");                  // every entry of one item, oldest first
var changes = WellStateDiff.Compare(asBuilt, afterWorkover);                 // each change carries Author and Utc
var csv = ModelAudit.ToCsv(afterWorkover.Audit);                             // for reports / regulators

Notes, arrows and highlights

WellboreAnnotation (note, arrow, highlighted interval) is saved with the document and drawn by the shared renderer, so it appears on screen and in every export; WellboreView adds, removes and drags annotations with undo.

// Notes, arrows and highlighted intervals: saved with the document, drawn on screen and in PDF / SVG / PNG exports.
view.AddAnnotation(new WellboreAnnotation { Kind = AnnotationKind.Highlight, Depth = 10100, ToDepth = 10180, Text = "Pay", Color = "#2e7d32" });
view.AddAnnotation(new WellboreAnnotation { Kind = AnnotationKind.Note, Depth = 9950, X = 0.3f, Text = "Check cement bond", Author = "fa" });
view.AllowAnnotationEditing = true;                                   // drag to move (undoable); click raises AnnotationClicked
view.AnnotationClicked += (s, note) => Console.WriteLine(note.Text);
// view.UndoTrackEdit() / RedoTrackEdit(); view.RemoveAnnotation(id); Document.ShowAnnotations = false hides them

Crossplots

Density-neutron and Pickett crossplots from a log set (inputs found as for the computed curves), coloured by zone or by a curve, with lithology lines and saturation lines from the environment.

// Density-neutron and Pickett crossplots from the logs; points coloured by zone (tops) or by a curve.
var log = LasReader.Load(las).Log!;
var densityNeutron = Crossplots.DensityNeutron(log, tops);                   // lithology lines from crossplots.densityNeutronLines
PetrophysicsCalculator.AddTo(log);                                            // PHIT for the Pickett plot (else density porosity is computed)
var pickett = Crossplots.Pickett(log, tops, colorCurve: "GR");               // Sw lines from the petrophysics (Archie) parameters
var view = new CrossplotView { Panel = pickett };                             // host like any ViewSurface; hover shows depth, values, zone

Map view and section lines

MapView shows wells in plan view (surface locations and well paths, equal scale, north up, grid, scale bar); in draw mode a drag draws the section line and WellMap.CreateCrossSection returns the CrossSectionPanel along it.

// Wells in plan view; the user drags a line and gets the cross-section along it.
var map = new WellMap { Name = "Field", Unit = DepthUnit.Feet };
map.Wells.Add(new CrossSectionWell { Document = w1, X = 0, Y = 0 });        // projected easting / northing
map.Wells.Add(new CrossSectionWell { Document = w2, X = 5000, Y = 0 });     // (or WellMap.FromLatLon for field-scale lat / long)
var mapView = new MapView { Map = map, DrawSectionMode = true };
mapView.SectionLineDrawn += (s, line) =>
{
    var panel = map.CreateCrossSection(maxOffset: 1000);                    // wells within 1000 ft of the line
    if (panel != null) shown = new CrossSectionView { Panel = panel };      // show it in the host
};
// host wiring as for any ViewSurface: Draw, HandleMouseDown / Move / Up / Wheel / Hover, Invalidated

Editing the schematic

With AllowEditing, pressing on equipment, a casing shoe or a cement top drags it (undo / redo through the view); code edits (AddEquipment, RemoveEquipment, SetStringDepths) join the same history; WellModelConverter.ApplyEdits writes the result back to the canonical model.

// Let users drag equipment, casing shoes and cement tops; every edit is undoable.
var schematic = view.Document.FindTrack<SchematicTrack>()!;
schematic.AllowEditing = true;
schematic.EditSnap = 1;                                              // snap to whole depth units
// edits in code join the same undo history
view.RecordTrackEdit(schematic.AddEquipment(new SchematicEquipment { Id = "CIBP-1", SymbolId = "pa_cibp", ComponentType = "BRIDGE_PLUG", TopDepth = 10450, Label = "CIBP" }));
view.RecordTrackEdit(schematic.SetStringDepths("S4", cementTop: 6800)!);
// write the edited schematic back to the well model (each value keeps its unit; removed items are marked Removed)
var changes = WellModelConverter.ApplyEdits(schematic.Document, model);

Depth matching and splicing

Curves are shifted interactively (drag in shift mode, undo / redo) or in code with bulk or tie-point shifts; every shift is a recorded CurveDepthShift (who, when, why), saved with the document and available in the well model.

// Interactive: drag the curve in its track; release records a CurveDepthShift (undoable).
view.BeginCurveShift(logTrack.Id, "GR");                              // then HandleMouseDown / Move / Up from the host
view.TrackEdited += (s, edit) => Console.WriteLine(edit.Description);
// ... view.UndoTrackEdit() / view.RedoTrackEdit(); view.EndCurveShift() returns to panning.

// In code: bulk or tie-point shifts, recorded for audit, and splicing two runs.
var tieIn = new CurveDepthShift
{
    Mnemonic = "GR", Reason = "core-to-log tie-in", Interpreter = "petrophysicist",
    TiePoints = { new DepthTiePoint { From = new Quantity(1020, "m"), To = new Quantity(1021.5, "m") },
                  new DepthTiePoint { From = new Quantity(1080, "m"), To = new Quantity(1080.5, "m") } }
};
CurveEditing.Shift(gr, tieIn, "m");
logTrack.Shifts.Add(tieIn);                                           // saved with the document
var spliced = CurveEditing.Splice(gr, run2, 1060, "GR_SPLICED");

Computed curves (petrophysics)

Shale volume, porosity and Archie saturation from logged curves, with the environment's parameters; missing inputs skip only the curves that need them.

// Shale volume, porosity and Archie saturation with the environment's parameters (petrophysics section).
var log = LasReader.Load(las).Log!;
List<string> skipped = PetrophysicsCalculator.AddTo(log);          // adds VSH, PHID, PHIT, SW, BVW; missing inputs are reported
var model = new WellModel(); model.LogSets.Add(log);
var tracks = WellLogTracks.LogSetTracks(model, DepthUnit.Feet);     // VSH with gamma ray, PHIT with porosity, SW / BVW in Saturation

Real-time monitoring

The transport stays yours; the library turns rows into a live, following view with a LIVE / STALE badge.

// The transport is yours (WITSML store SOAP, ETP, ...): a delegate returning the store's XML for rows after an index.
var source = new WitsmlGrowingLogSource((afterIndex, ct) => Task.FromResult(Response()));
var feed = new LiveLogFeed(view);                                                     // stale threshold from the environment
var canvas = new WellboreView { Document = view, Live = feed, FollowLatest = true };   // newest data at the bottom, LIVE / STALE badge

// Poll on your schedule (timer, background service); re-delivered rows are ignored.
int added = await feed.PollAsync(source);

Multi-tenant server

Each request runs with its customer's services; scopes flow across awaits and do not leak between requests.

// One process, many customers: each request runs in its customer's scope (units, criteria, names, colours).
async Task<DepthUnit> HandleRequest(WellboreServices customer)
{
    using (WellboreServices.Scope(customer))
    {
        await Task.Yield();                                                           // scopes flow across awaits
        var view = WellModelConverter.ToWellboreView(model, null, out _);            // conversion defaults from the scope
        return view.Axis.Unit;
    }
}
var units = await Task.WhenAll(HandleRequest(ncs), HandleRequest(kuwait));         // concurrently, isolated

Extending

See Extending for custom tracks, sources and contracts.