Skip to main content
Glama
pyResToolbox MCP Server

pyResToolbox MCP Server

pyResToolbox MCP Server

Bring Reservoir Engineering Calculations to AI

Power your AI assistants with industry-standard petroleum engineering calculations

License: GPL v3 Python 3.10+ Tests FastMCP Production Ready

Model Context Protocol Built with pyResToolbox Buy Me A Coffee

Quick Start • Features • Examples • Documentation • Contributing


108 Production-Ready Tools | Field & Metric Units | Zero Configuration

PVT Analysis • Well Performance • Nodal Analysis • DCA • Material Balance • Simulation Support • Brine Properties • Geomechanics • Heterogeneity Analysis


A production-ready Model Context Protocol (MCP) server that gives AI agents like Claude access to the comprehensive reservoir engineering library pyResToolbox. Now Claude can perform sophisticated PVT calculations, well performance analysis, and reservoir simulation tasks through natural conversation.

pyResToolbox MCP Demo


☕ Support This Project

If you find this project useful, consider buying me a coffee! Your support helps maintain and improve this open-source tool.


Related MCP server: CalcsLive MCP Server

What is This?

This MCP server bridges the gap between AI assistants and petroleum engineering workflows. Instead of manually calculating reservoir properties or writing complex scripts, you can simply ask Claude:

"Calculate the bubble point pressure for API 35° oil at 180°F with solution GOR of 800 scf/stb and gas gravity 0.75 using the Valko-McCain correlation"

"Generate an IPR curve for my well with Pi=4000 psia, Pb=3500 psia, API 38°, 175°F, pay thickness 75 ft, permeability 150 mD"

"Create a black oil table for simulation with pressures from 500 to 5000 psia"

Claude will execute the calculations using industry-standard correlations and return accurate, formatted results.

Built On

  • pyResToolbox by Mark Burgoyne - Comprehensive Python library for reservoir engineering calculations

  • FastMCP - Modern Python framework for building MCP servers

  • Model Context Protocol by Anthropic - Standard for AI-application integration

Key Features

  • 108 Production-Ready Tools - All tools tested and validated

  • Industry-Standard Correlations - Standing, Valko-McCain, Velarde, DAK, Beggs-Robinson, Corey, LET, and more

  • Dual Unit Support - Field units (psia, °F, ft) and Metric units (barsa, °C, m)

  • Array Support - Calculate properties at multiple pressures simultaneously

  • Zero Configuration - Works out of the box with Claude Desktop

  • GPL-3.0 Licensed - Free and open source


Quick Start

Installation

Prerequisites: Python 3.10+ (UV package manager recommended but optional)

# 1. Clone the repository
git clone https://github.com/gabrielserrao/pyrestoolbox-mcp.git
cd pyrestoolbox-mcp

# 2. Install UV (optional but 10-100x faster than pip)
curl -LsSf https://astral.sh/uv/install.sh | sh

# 3. Setup and test
make uv-install    # Creates venv and installs dependencies
make uv-test       # Verifies all 108 tools work correctly

Connect to Claude Desktop

Add this to your Claude Desktop config file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json

IMPORTANT: Use absolute paths for both uv and the project directory. GUI applications like Claude Desktop don't inherit your terminal's PATH.

Find your UV path:

# macOS/Linux
which uv

# Windows (PowerShell)
Get-Command uv | Select-Object -ExpandProperty Source

Configuration:

{
  "mcpServers": {
    "pyrestoolbox": {
      "command": "/absolute/path/to/uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/pyrestoolbox-mcp",
        "fastmcp",
        "run",
        "server.py"
      ]
    }
  }
}

Common UV paths:

  • macOS/Linux: /Users/username/.local/bin/uv or /home/username/.local/bin/uv

  • Windows: C:\Users\username\.cargo\bin\uv.exe

Example (macOS):

{
  "mcpServers": {
    "pyrestoolbox": {
      "command": "/Users/john/.local/bin/uv",
      "args": [
        "run",
        "--directory",
        "/Users/john/projects/pyrestoolbox-mcp",
        "fastmcp",
        "run",
        "server.py"
      ]
    }
  }
}

Example (Linux):

{
  "mcpServers": {
    "pyrestoolbox": {
      "command": "/home/john/.local/bin/uv",
      "args": [
        "run",
        "--directory",
        "/home/john/projects/pyrestoolbox-mcp",
        "fastmcp",
        "run",
        "server.py"
      ]
    }
  }
}

Example (Windows):

{
  "mcpServers": {
    "pyrestoolbox": {
      "command": "C:\\Users\\john\\.cargo\\bin\\uv.exe",
      "args": [
        "run",
        "--directory",
        "C:\\Users\\john\\projects\\pyrestoolbox-mcp",
        "fastmcp",
        "run",
        "server.py"
      ]
    }
  }
}

Restart Claude Desktop completely (Quit and reopen, not just close the window) and you're ready to go!


The SKILL/ folder in this repository contains a pre-built skill that teaches your AI assistant exactly how to use all 108 tools — correct parameter names, valid method codes, validation constraints, and multi-step workflows.

What's included:

File

Purpose

SKILL/pyrestoolbox-mcp.skill

Ready-to-install skill bundle (zip format)

SKILL/SKILL.md

Skill definition with YAML front-matter trigger conditions

SKILL/tools-reference.md

Complete parameter reference for all 108 tools

Installation (Claude Code):

Copy the skill file to your Claude skills directory:

cp SKILL/SKILL.md ~/.claude/skills/pyrestoolbox-mcp.md

# Optional but recommended — full parameter reference
mkdir -p ~/.claude/skills/references
cp SKILL/tools-reference.md ~/.claude/skills/references/tools-reference.md

Once installed, the skill activates automatically when you ask about reservoir engineering calculations, PVT analysis, well performance, geomechanics, or any pyResToolbox topic.

What the skill teaches the AI:

  • Exact parameter names (psd not pwf, sg not sg_g for gas tools, zmethod vs method)

  • All valid enum strings ("VALMC", "DAK", "SWOF", "COR", etc.)

  • Required vs optional parameters for every tool

  • Numeric validation constraints (API 0–100, gas SG 0.5–2.0, Poisson's ratio 0–0.5)

  • Common multi-step workflows (PVT analysis, well performance, simulation input, geomechanics drilling window)


Your First Query

Open Claude Desktop and try:

"What's the bubble point pressure for a 35° API oil at 180°F with 800 scf/stb solution GOR and 0.75 gas gravity?"

Claude will use the oil_bubble_point tool and return results like:

Bubble Point Pressure: 3,456.7 psia
Method: Valko-McCain (VALMC)
Inputs: API=35°, T=180°F, Rs=800 scf/stb, SG_gas=0.75

What Can You Do?

Oil PVT Analysis

  • Calculate bubble point pressure (Standing, Valko-McCain, Velarde)

  • Solution GOR, formation volume factor, viscosity, density, compressibility

  • Generate comprehensive black oil tables for simulators

Gas PVT Analysis

  • Z-factor calculations (DAK, Hall-Yarborough, WYW, BUR/Peng-Robinson EOS)

  • Hydrogen-capable gas PVT via BUR method (SPE-229932-MS) - handles arbitrary mixtures including pure CO₂ and 30%+ H₂

  • Critical properties with contaminants (CO₂, H₂S, N₂, H₂)

  • Gas viscosity, density, compressibility, pseudopressure

  • Formation volume factors, hydrate prediction, water content

Well Performance & IPR

  • Oil and gas production rates (radial and linear flow)

  • IPR curve generation for vertical and horizontal wells

  • Vogel IPR for pressures below bubble point

  • Sensitivity analysis for permeability, skin, reservoir pressure

Reservoir Simulation Support

  • Relative permeability tables (SWOF, SGOF, SGWFN) with Corey, LET, and Jerauld curve families

  • Rel perm fitting - fit lab data to any model family, or auto-select best fit

  • LET physical feasibility checking

  • PVDO/PVDG/PVTO black oil tables and PVTW water PVT generation

  • VFPPROD/VFPINJ lift curve tables for ECLIPSE

  • Van Everdingen & Hurst aquifer influence functions (AQUTAB)

  • Rachford-Rice flash calculations for phase behavior

Nodal Analysis & VLP

  • Four multiphase VLP correlations: Woldesemayat-Ghajar (WG), Hagedorn-Brown (HB), Gray, Beggs & Brill (BB)

  • Multi-segment deviated and horizontal completions (not just vertical pipes)

  • IPR curve generation (gas, oil, water wells)

  • VLP outflow curves and operating point calculation

  • Production and injection modes supported

  • VFPPROD/VFPINJ table generation for ECLIPSE/Intersect simulators

  • GasPVT and OilPVT wrapper classes for consistent fluid characterization

Decline Curve Analysis (DCA)

  • Arps decline (exponential, hyperbolic, harmonic)

  • Rate and cumulative production forecasting

  • EUR estimation

  • Duong tight/unconventional decline

  • Production ratio analysis (WOR, GOR, WGR)

Material Balance

  • P/Z gas material balance for OGIP estimation

  • Havlena-Odeh oil material balance for OOIP estimation

  • Cole plot diagnostics and regression

Geomechanics & Wellbore Stability (27 tools)

  • Vertical/horizontal stress, pore pressure prediction (Eaton)

  • Fracture gradient, breakdown pressure, mud weight window

  • Borehole breakout, sand production, fault stability

  • Elastic moduli, rock strength, compaction, thermal stress

  • UCS from logs, stress polygon, critical drawdown

Brine Properties

  • CH₄-saturated brine properties (density, viscosity, FVF, compressibility)

  • CO₂-brine mutual solubility for sequestration studies

  • Soreide-Whitson VLE for multi-gas brine systems (CO₂, H₂S, N₂, H₂) with Sechenov salting-out corrections

  • IAPWS-IF97 freshwater density, Spivey/McCain salinity corrections

  • Per-component solubility, water content, and thermodynamic properties from a single framework

Advanced Calculations

  • Reservoir heterogeneity analysis (Lorenz coefficient, beta parameter)

  • Layer permeability distributions

  • Component library (critical properties for 100+ hydrocarbons)

  • Sensitivity analysis (parameter sweeps, tornado plots)

  • Method recommendation engine

Configuration & Help

  • Query available calculation methods and correlations

  • Access unit system documentation

  • Get physical constants

  • Comprehensive usage guides


Example Queries for Claude

Basic PVT Calculations

"Calculate Z-factor for gas with SG 0.7 at 3500 psia and 180°F using DAK method"

"What's the oil formation volume factor for 38° API oil at 3000 psia, 175°F with Rs=600?"

"Compare bubble point pressures using Standing, Valko-McCain, and Velarde for 35° API oil"

Well Performance Analysis

"Generate IPR curve for well: Pi=4000 psia, Pb=3500 psia, API 38, T=175°F,
 h=75 ft, k=150 mD, skin=-2, re=1500 ft, rw=0.5 ft"

"Calculate oil production rate at 2000 psia flowing pressure for the same well"

"Show me how permeability affects production - test 50, 100, 150, 200, 250 mD"

Simulation Preparation

"Generate a SWOF relative permeability table using Corey correlation with 25 rows,
 kromax=1.0, krwmax=0.25, swc=0.15, sorw=0.15, no=2.5, nw=1.5"

"Create aquifer influence functions for dimensionless radius 10.0"

"Generate black oil table from 500 to 5000 psia for 38° API oil at 175°F"

Reservoir Heterogeneity

"Convert Lorenz coefficient 0.5 to Dykstra-Parsons beta"

"Generate layered permeability distribution for Lorenz coefficient 0.6,
 10 layers, average permeability 100 mD"

Multi-Step Workflows

"Perform complete reservoir analysis: Calculate bubble point, generate PVT table,
 create IPR curve, and analyze well performance for 38° API oil at 175°F with
 initial pressure 4000 psia"

"Design a well completion: Calculate optimal flowing pressure, generate IPR,
 and compare different skin factors"

"Evaluate a gas reservoir: Calculate critical properties, generate IPR,
 and compare different Z-factor methods"

Advanced Queries

Comprehensive PVT Workflows

"Generate a complete PVT table for API 38 oil at 175°F with gas gravity 0.68
 and solution GOR 750 scf/stb. Include pressures from 500 to 4000 psia and
 show Rs, Bo, viscosity, and density"

"Compare bubble point pressures using Standing, Valko-McCain, and Velarde
 correlations for API 35 oil at 180°F with GOR 800 scf/stb"

"Calculate PVT properties at multiple pressures: 1000, 2000, 3000, and 4000 psia
 for API 38 oil at 175°F"

Gas Analysis

"Calculate the critical properties (Tc and Pc) for a gas with specific gravity 0.7
 containing 2% CO2, 1% H2S, and 3% N2"

"Compare Z-factors using DAK, HY, and WYW methods for a gas at 3500 psia and 180°F"

"Calculate gas pseudopressure from 1000 to 3500 psia for a gas with SG 0.7 at 180°F"

Well Performance & IPR

"Generate an IPR curve for an oil well with reservoir pressure 4000 psia,
 bubble point 3500 psia, API 38 oil at 175°F. Well has 75 ft net pay,
 150 mD permeability, skin -2, drainage radius 1500 ft"

"What's the oil production rate at 2000 psia flowing pressure for a well with
 Pi=4000 psia, Pb=3500 psia, API 35, 180°F, 50 ft pay, 100 mD permeability?"

"Generate a Vogel IPR curve for pressures below bubble point for API 38 oil"

Sensitivity Analysis

"How does oil rate change with permeability? Test values from 50 to 250 mD"

"What's the impact of skin factor on production? Compare rates for skin values
 from -5 to +10"

"Analyze the effect of net pay thickness on production rate: test 25, 50, 75,
 and 100 ft"

"How does reservoir pressure depletion affect production? Calculate rates at
 4000, 3500, 3000, and 2500 psia"

Brine & CO₂ Sequestration

"Calculate brine properties for fresh water at 3000 psia and 175°F"

"What are the properties of saline brine (5% NaCl) at reservoir conditions:
 3000 psia, 175°F?"

"Calculate CO₂-brine mutual solubility at 3000 psia and 180°F with salinity
 50000 ppm"

"Compare brine properties with and without CO₂ saturation at sequestration conditions"

Reservoir Heterogeneity

"Convert Lorenz coefficient 0.5 to Dykstra-Parsons beta parameter"

"Calculate Lorenz coefficient from production logging data: flow fractions
 [0.45, 0.25, 0.15, 0.10, 0.05] and permeability fractions [0.30, 0.25, 0.20, 0.15, 0.10]"

"Generate a layered permeability distribution for Lorenz coefficient 0.5,
 10 layers, average permeability 100 mD"

Phase Behavior & Flash Calculations

"Solve Rachford-Rice flash for a mixture with compositions [0.5, 0.3, 0.2]
 and K-values [2.5, 1.8, 0.6]"

"Calculate vapor-liquid equilibrium for a three-component system"

Component Library

"What are the critical properties for methane?"

"Get critical temperature and pressure for ethane, propane, and butane"

"What's the molecular weight of n-heptane?"

Economic & Optimization

"What's the optimal flowing pressure to maximize production? Generate IPR
 and find the sweet spot"

"Compare production rates for stimulated (skin -2) vs damaged (skin +5) wells"

"Analyze the impact of reservoir pressure depletion on well performance over time"

Comparison & Benchmarking

"Compare Standing vs Valko-McCain vs Velarde bubble point correlations for the same oil"

"Compare DAK vs HY vs WYW Z-factor methods and their impact on gas rate calculations"

"Compare radial vs linear flow geometries for the same reservoir properties"

Educational Queries

"Explain what bubble point pressure means and calculate it for API 35 oil"

"What's the difference between solution GOR and producing GOR? Calculate both"

"How does gas gravity affect Z-factor? Show me calculations for different gravities"

"Explain Lorenz coefficient and calculate it for a heterogeneous reservoir"

Troubleshooting & Validation

"Validate my PVT data: bubble point 3500 psia, API 38, 175°F, GOR 750 scf/stb -
 does this make sense?"

"Check if my gas composition is realistic: SG 0.7 with 5% CO2, 3% H2S, 2% N2"

"Verify my well performance calculation: Are these rates reasonable for the
 given reservoir properties?"

Tips for Better Queries

  1. Be Specific - Include all relevant parameters (API, temperature, pressure, etc.)

  2. Specify Methods - Mention which correlation you want (VALMC, DAK, Corey, LET, etc.)

  3. Include Units - Always specify units (psia, degF, mD, ft, etc.)

  4. Ask for Comparisons - Request comparisons between methods or scenarios

  5. Request Tables - Ask for tabulated results when you need multiple values

  6. Follow-up Questions - Build on previous answers for complex workflows


Unit System

All calculations default to Field Units (US Oilfield) per industry standard. Set metric: true on any tool to use Metric Units (Eclipse METRIC conventions: barsa, °C, metres, sm³/d) with no manual conversion needed. ECLIPSE keyword output automatically switches to METRIC headers.

Property

Unit

Example

Pressure

psia

3000 psia

Temperature

°F

180°F

Permeability

mD

100 mD

Pay Thickness

ft

50 ft

Viscosity

cP

0.85 cP

Oil Rate

STB/day

542 STB/day

Gas Rate

MSCF/day

1250 MSCF/day

Oil Gravity

API° or SG

35° API

Gas Gravity

SG (air=1)

0.75

Solution GOR

scf/stb

800 scf/stb

Oil FVF

rb/stb

1.25 rb/stb

Gas FVF

rcf/scf

0.0045 rcf/scf

Compressibility

1/psi

1.2×10⁻⁵ 1/psi

Density

lb/ft³

42.5 lb/ft³

Access complete unit documentation anytime by asking Claude: "What units does pyRestToolbox use?"


Architecture

Project Structure

pyrestoolbox-mcp/
├── src/pyrestoolbox_mcp/
│   ├── server.py              # Main MCP server (FastMCP)
│   ├── config.py              # Server configuration & constants
│   ├── tools/                 # 108 MCP tool implementations
│   │   ├── oil_tools.py       # 19 oil PVT tools
│   │   ├── gas_tools.py       # 15 gas PVT tools
│   │   ├── inflow_tools.py    # 4 well performance tools
│   │   ├── simtools_tools.py  # 11 simulation support tools
│   │   ├── nodal_tools.py     # 6 nodal analysis / VLP tools
│   │   ├── dca_tools.py       # 9 decline curve analysis tools
│   │   ├── matbal_tools.py    # 2 material balance tools
│   │   ├── brine_tools.py     # 3 brine property tools
│   │   ├── geomech_tools.py   # 27 geomechanics tools
│   │   ├── layer_tools.py     # 5 heterogeneity tools
│   │   ├── recommend_tools.py # 4 method recommendation tools
│   │   ├── sensitivity_tools.py # 2 sensitivity analysis tools
│   │   ├── library_tools.py   # 1 component library tool
│   │   └── gas_fixes.py       # Upstream bug workarounds
│   ├── models/                # Pydantic validation models
│   │   ├── oil_models.py
│   │   ├── gas_models.py
│   │   ├── inflow_models.py
│   │   ├── simtools_models.py
│   │   ├── nodal_models.py
│   │   ├── dca_models.py
│   │   ├── matbal_models.py
│   │   ├── brine_models.py
│   │   ├── geomech_models.py
│   │   ├── layer_models.py
│   │   ├── recommend_models.py
│   │   ├── sensitivity_models.py
│   │   ├── library_models.py
│   │   └── common_models.py
│   └── resources/             # MCP configuration resources
│       └── config_resources.py
├── tests/                     # Test suite (52 pytest tests)
│   ├── test_oil_tools.py
│   ├── test_gas_tools.py
│   ├── test_geomech_tools.py
│   ├── test_simtools_new.py
│   ├── test_dca_tools.py
│   ├── test_brine_new.py
│   ├── test_nodal_tools.py
│   ├── test_matbal_tools.py
│   ├── test_recommend_tools.py
│   └── conftest.py
├── examples/                  # 12 comprehensive workflow examples
│   ├── basic_usage.py
│   ├── pvt_workflow.py
│   ├── gas_well_analysis.py
│   └── ...
├── server.py                  # Entry point
├── pyproject.toml            # UV/pip configuration
├── Makefile                  # Development commands
├── Dockerfile                # Docker deployment
└── docker-compose.yml        # Multi-transport deployment

How It Works

  1. FastMCP Server - Handles MCP protocol communication (STDIO, HTTP, SSE)

  2. Pydantic Models - Validate all inputs with descriptive error messages

  3. Tool Layer - 108 functions wrapping pyrestoolbox calculations

  4. pyRestToolbox - Performs actual reservoir engineering calculations

  5. Type Conversion - Handles numpy/pandas/mpmath serialization for JSON

Tool Categories

Category

Count

Description

Oil PVT

19

Bubble point, Rs, Bo, viscosity, density, compressibility, black oil tables, PVT harmonization

Gas PVT

15

Z-factor, critical properties, Bg, viscosity, density, pseudopressure, hydrate prediction

Inflow

4

Oil/gas rates for radial/linear flow, IPR generation

Simulation

11

Relative permeability (Corey, LET, Jerauld), aquifer functions, flash, PVTW, black oil OG

Nodal / VLP

6

Flowing BHP, IPR/VLP curves, operating point, VFPPROD/VFPINJ tables

DCA

9

Arps decline, forecasting, EUR, Duong, ratio analysis

Material Balance

2

Gas P/Z and oil Havlena-Odeh OOIP/OGIP estimation

Brine

3

CH₄ and CO₂ saturated brine, Soreide-Whitson VLE

Geomechanics

27

Stress, pore pressure, fracture gradient, wellbore stability, sand production

Heterogeneity

5

Lorenz coefficient, beta conversion, layer distributions

Recommend

4

Method recommendation for gas, oil, VLP correlations

Sensitivity

2

Parameter sweeps and tornado sensitivity analysis

Library

1

Critical properties for 100+ components

Config

4

Units, methods, constants, help resources


pyResToolbox v3 Feature Coverage

This MCP server wraps pyResToolbox v3.0.4. The following table shows coverage of the major v3 features announced in the v3 release post:

v3 Feature

MCP Coverage

Details

Nodal Analysis - 4 VLP correlations (WG, HB, BB, Gray)

Full

flowing_bhp, ipr_curve, outflow_curve, operating_point tools with vlp_method parameter

Multi-segment deviated/horizontal completions

Full

WellSegment and Completion classes exposed via segments parameter in nodal tools

Production and injection modes

Full

injection flag on flowing_bhp; generate_vfp_inj_table for injection VLP

GasPVT and OilPVT wrapper classes

Full

Used internally by nodal tools for consistent fluid characterization

VFPPROD/VFPINJ table generation

Full

generate_vfp_prod_table, generate_vfp_inj_table tools

Multi-gas brine (Soreide-Whitson VLE)

Full

soreide_whitson_vle tool with CO₂, H₂S, N₂, H₂ mole fractions

IAPWS-IF97 freshwater density

Full

Handled internally by pyRestToolbox brine functions

Hydrogen-capable gas PVT (BUR/Peng-Robinson)

Full

gas_z_factor with method: BUR and h2 parameter; all gas tools support H₂

Metric unit support

Full

metric: true flag on all tools using Eclipse METRIC conventions

Simulation tables (PVDO/PVDG/PVTO/PVTW)

Full

generate_black_oil_table_og, generate_pvtw_table, black_oil_table tools

Rel perm fitting (Corey, LET, Jerauld)

Full

fit_relative_permeability, fit_relative_permeability_best, evaluate_jerauld, check_let_physical tools

Input validation & proper exceptions

Full

Pydantic models with field constraints on all 108 tools

DCA (Arps, Duong, ratio analysis)

Full

9 DCA tools covering all decline types

Material Balance (gas P/Z, oil Havlena-Odeh)

Full

gas_material_balance, oil_material_balance tools

Functions Not Exposed as MCP Tools

Some pyResToolbox functions are used internally but not exposed as standalone MCP tools:

Function

Reason

GasPVT / OilPVT classes

Used internally by nodal tools; individual PVT tools cover same calculations

darcy_gas

Low-level function; gas_rate_radial / gas_rate_linear provide higher-level access

oil_rs_bub / oil_rs_st / sg_st_gas

Specialized functions covered by oil_solution_gor tool

oil_harmonize_pb_rsb

Covered by oil_harmonize tool

gas_ponz2p

Inverse P/Z lookup; covered by gas_pressure_from_pz tool

brine_props / make_pvtw_table (brine)

Covered by calculate_brine_properties and generate_pvtw_table tools

validate_methods

Internal validation utility


Development

Running Tests

# Quick validation (all 108 tools)
make uv-test
# or
uv run python test_tools.py

# Full pytest suite
uv run pytest

# With coverage report
uv run pytest --cov=pyrestoolbox_mcp --cov-report=html

# Specific test modules
uv run pytest tests/test_oil_tools.py
uv run pytest tests/test_gas_tools.py

See TEST_RESULTS.md for complete validation report.

Running Examples

# Run all examples
make uv-examples

# Run specific example
make uv-example EXAMPLE=basic_usage.py
make uv-example EXAMPLE=gas_well_analysis.py

# Or manually
cd examples
uv run python basic_usage.py

Code Quality

# Format code
uv run black src/ tests/

# Lint
uv run ruff check src/ tests/

# Type checking (if mypy added)
uv run mypy src/

Docker Deployment

# Build image
make docker-build

# Run HTTP server (port 8000)
make docker-up-http

# Run SSE server (port 8001)
make docker-up-sse

# View logs
make docker-logs

# Stop services
make docker-down

See DOCKER.md for complete Docker documentation.

Adding New Tools

See CONTRIBUTING.md for detailed instructions. Quick overview:

  1. Define Pydantic Model in src/pyrestoolbox_mcp/models/

  2. Implement Tool Function in appropriate src/pyrestoolbox_mcp/tools/ file

  3. Register Tool in the module's register_*_tools() function

  4. Add Tests to test_tools.py and appropriate pytest file

  5. Update Documentation in README and examples


Available Calculation Methods

Oil Correlations

Bubble Point Pressure

  • VALMC - Valko & McCain (2003) - Recommended for most applications

  • STAN - Standing (1947) - Classic correlation

  • VELAR - Velarde (1997) - For specific regions

Solution GOR (Rs)

  • VELAR - Velarde (1997)

  • STAN - Standing (1947)

  • VALMC - Valko & McCain (2003)

Formation Volume Factor (Bo)

  • MCAIN - McCain et al. (1988) - Recommended

  • STAN - Standing (1947)

Viscosity

  • BR - Beggs & Robinson (1975)

Gas Correlations

Z-Factor

  • DAK - Dranchuk & Abou-Kassem (1975) - Recommended for hydrocarbon gases

  • HY - Hall & Yarborough (1973) - Fast, good for most conditions

  • WYW - Wang, Ye & Wu (2021) - Reasonably fast

  • BUR - Burgoyne, Nielsen & Stanko (2025) - Universal EOS-based correlation (5-component Peng-Robinson), best for high concentrations of non-hydrocarbons (CO₂, H₂S, N₂, H₂), including pure CO₂ and up to 30%+ hydrogen. Only method supporting H₂. (SPE-229932-MS)

Critical Properties

  • PMC - Piper, McCain & Corredor (1993) - Recommended for hydrocarbon gases

  • SUT - Sutton (1985)

  • BUR - Burgoyne, Nielsen & Stanko (2025) - Universal correlation, best for gases with high non-hydrocarbon content (SPE-229932-MS)

Viscosity

  • LGE - Lee, Gonzalez & Eakin (1966)

Relative Permeability

Curve Types

  • COR - Corey (1954) - Power law, simple

  • LET - Lomeland, Ebeltoft & Thomas (2005) - Flexible, complex shapes

Table Types

  • SWOF - Water-oil saturation functions

  • SGOF - Gas-oil saturation functions

  • SGWFN - Gas-water saturation functions (3-phase)


Programmatic Usage

While this server is designed for Claude Desktop integration, you can also use it programmatically:

Python Client

import asyncio
from fastmcp.client import InMemoryTransport
from pyrestoolbox_mcp import mcp

async def calculate_pvt():
    transport = InMemoryTransport(mcp)

    async with transport.get_client() as client:
        # Calculate bubble point
        pb_result = await client.call_tool(
            "oil_bubble_point",
            {
                "api": 35.0,
                "degf": 180.0,
                "rsb": 800.0,
                "sg_g": 0.75,
                "method": "VALMC"
            }
        )
        pb = pb_result['value']
        print(f"Bubble Point: {pb:.2f} psia")

        # Calculate Rs at multiple pressures
        rs_result = await client.call_tool(
            "oil_solution_gor",
            {
                "api": 35.0,
                "degf": 180.0,
                "p": [1000, 2000, 3000, pb, 4000],
                "sg_g": 0.75,
                "pb": pb,
                "rsb": 800.0,
                "method": "VELAR"
            }
        )
        print(f"Rs values: {rs_result['value']}")

        # Access configuration resources
        methods = await client.read_resource("config://methods")
        print(f"Available methods:\n{methods.content}")

asyncio.run(calculate_pvt())

HTTP/SSE Transport

# Start HTTP server
uv run fastmcp run server.py --transport http --port 8000

# Or using Docker
docker-compose --profile http up -d

Then connect using any MCP client or HTTP client supporting the MCP protocol.


Troubleshooting

Installation Issues

"uv: command not found"

  • Close and reopen terminal after installing UV

  • Verify: uv --version

  • Alternative: Use pip instead (pip install -e .)

"make: command not found" (Windows)

  • Use manual commands from Makefile

  • Or install Make for Windows via Chocolatey: choco install make

UV sync fails

  • Clear cache: rm -rf .venv && make uv-install

  • Check Python version: python --version (needs 3.10+)

Claude Desktop Integration

Error: "spawn uv ENOENT"

  • This means Claude Desktop cannot find the uv command

  • GUI applications don't inherit your terminal's PATH

  • Solution: Use absolute path to uv in your config

  • Find UV path: which uv (macOS/Linux) or Get-Command uv (Windows)

  • Common locations:

    • macOS/Linux: /Users/username/.local/bin/uv or /home/username/.local/bin/uv

    • Windows: C:\Users\username\.cargo\bin\uv.exe

Claude doesn't see the tools

  1. Use absolute paths for both uv command and project directory (no ~, use full path)

  2. Verify paths are correct: ls /path/to/uv and ls /path/to/pyrestoolbox-mcp

  3. Completely restart Claude Desktop (Quit, not just close window)

  4. Check Claude Desktop logs:

    • macOS: ~/Library/Logs/Claude/

    • Windows: %APPDATA%\Claude\logs\

    • Linux: ~/.config/Claude/logs/

  5. Test server manually: cd /path/to/pyrestoolbox-mcp && make uv-server

Tools fail with errors

  • Verify all inputs use Field Units (psia, °F, ft, mD)

  • Check parameter names match exactly (case-sensitive)

  • Run validation: uv run python test_tools.py

Runtime Issues

Import errors

# Reinstall dependencies
make uv-install
# or
uv sync --force

Calculation errors

  • Check units (must be psia, °F, etc.)

  • Verify inputs are realistic (e.g., API 10-50, temperatures 60-300°F)

  • Some correlations have valid ranges - try different methods

  • Check pyResToolbox docs for correlation limits

Performance issues

  • Array calculations are optimized via numpy

  • For large datasets, consider batching requests

  • Docker deployment adds minimal overhead

Getting Help


Contributing

Contributions are welcome! This project follows the GPL-3.0 license of the upstream pyResToolbox library.

How to Contribute

  1. Fork the repository

  2. Create a feature branch (git checkout -b feature/amazing-feature)

  3. Make your changes (follow code style guidelines)

  4. Test thoroughly (uv run pytest - all tests must pass)

  5. Format code (uv run black src/ tests/)

  6. Commit (git commit -m 'Add amazing feature')

  7. Push (git push origin feature/amazing-feature)

  8. Open a Pull Request

Development Setup

git clone https://github.com/gabrielserrao/pyrestoolbox-mcp.git
cd pyrestoolbox-mcp
make uv-install
uv run python test_tools.py  # Verify all 108 tools pass

Guidelines

  • Use type hints for all function parameters and return values

  • Write Google-style docstrings

  • Add tests for all new tools

  • Follow existing code structure

  • Update documentation

See CONTRIBUTING.md for detailed guidelines.


License

GNU General Public License v3.0 (GPL-3.0)

This MCP server is built on pyResToolbox, which is licensed under GPL-3.0. This project maintains full compliance with GPL-3.0 license terms.

Key Points:

  • Free and open source software

  • You may use, modify, and distribute under GPL-3.0 terms

  • Any modifications must also be released under GPL-3.0

  • No warranty provided (see LICENSE for details)

  • Commercial use is permitted under GPL-3.0 terms

See LICENSE for complete license text.


Project Status

Aspect

Status

Details

Tests

Tests

100% tool coverage

Production

✅ Ready

All tools validated

Documentation

✅ Complete

README, examples, guides

License

GPL-3.0

Matches upstream

Python

3.10+

Type hints throughout

Framework

FastMCP 3.1+

Modern MCP implementation

See PRODUCTION_READY.md for detailed verification results.

Version History

v2.0.0 (2026-03-11) - Major upgrade to pyResToolbox 3.0.4

  • 108 production-ready tools (up from 47)

  • Dual unit support (Field + Metric)

  • New modules: DCA, Material Balance, Nodal Analysis, Geomechanics, Sensitivity, Recommend

  • FastMCP 3.x compatibility

  • 52 pytest tests passing

v1.0.0 (2024-11-15) - Initial production release

  • 47 production-ready tools

  • Docker deployment support

  • GPL-3.0 license compliance

See CHANGELOG.md for detailed version history.


Roadmap

Planned Features

  • Web UI for HTTP transport with interactive forms

  • Additional workflow examples for common tasks

  • Performance benchmarking suite

  • Extended simulation tools (grid processing, ECLIPSE utilities)

  • Jupyter notebook integration with examples

  • API documentation site (Sphinx/MkDocs)

  • Rate limiting and authentication for HTTP deployments

  • Prometheus metrics export

See open issues for full list of proposed features and known issues.

Upstream Integration

We're exploring opportunities to contribute improvements back to pyResToolbox, including:

  • Standalone gas_grad2sg implementation (bug fix)

  • Enhanced type hints

  • Additional validation utilities


Core Dependencies

Similar MCP Servers

Petroleum Engineering Tools

  • PVTpy - PVT calculations in Python

  • petbox - Petroleum engineering toolbox


Acknowledgments

This project wouldn't exist without:

  • Mark Burgoyne - Creator of pyResToolbox, the foundation of this MCP server

  • Marvin AI Team - Developers of FastMCP framework

  • Anthropic - For Claude and the Model Context Protocol specification

  • The reservoir engineering community - For developing and refining the correlations implemented in this project

Special thanks to all contributors who help improve this project!


Citation

If you use this MCP server in academic or commercial work, please cite the original pyResToolbox library:

@software{pyrestoolbox,
  author = {Burgoyne, Mark W.},
  title = {pyResToolbox: A Collection of Reservoir Engineering Utilities},
  url = {https://github.com/mwburgoyne/pyResToolbox},
  version = {3.0.4},
  year = {2025}
}

For this MCP server:

@software{pyrestoolbox_mcp,
  author = {Serrao, Gabriel},
  title = {pyResToolbox MCP Server: AI-Powered Reservoir Engineering Calculations},
  url = {https://github.com/gabrielserrao/pyrestoolbox-mcp},
  version = {2.0.0},
  year = {2026},
  note = {Built on pyResToolbox by Mark W. Burgoyne}
}

Support

Getting Help

For MCP server issues:

For calculation accuracy or pyResToolbox features:

For FastMCP framework:

For Model Context Protocol:

Community


Support & Star

⭐ Star This Project

If you find this project useful, please give it a star on GitHub! Stars help others discover this project and motivate continued development.

☕ Buy Me a Coffee

Support the development and maintenance of this project:

Your support helps keep this project free and open source for the petroleum engineering community!

📈 Star History

Star History Chart



Built with ❤️ for the petroleum engineering community

Created by Gabriel Serrao


Report Bug · Request Feature · Documentation · Examples

GitHub Stars LinkedIn Buy Me A Coffee

Available Tools

45 tools
beta_to_lorenzA

Convert Dykstra-Parsons beta to Lorenz coefficient.

HETEROGENEITY CONVERSION - Converts beta parameter to Lorenz coefficient. Essential for converting literature data and comparing reservoirs using different heterogeneity metrics.

Parameters:

  • value (float, required): Dykstra-Parsons beta coefficient (0-1). Must be 0 ≤ β ≤ 1. Typical: 0.3-0.8. Example: 0.6 for moderate heterogeneity.

Dykstra-Parsons Beta (β):

  • Permeability variation coefficient (dimensionless, 0-1)

  • β = (k50 - k84.1) / k50

  • Based on log-normal permeability distribution

  • Requires permeability data (core, logs)

  • Common in literature and older studies

Lorenz Coefficient (L):

  • Ranges from 0 (homogeneous) to 1 (completely heterogeneous)

  • Based on cumulative flow capacity vs cumulative storage capacity

  • Directly measurable from production data

  • More intuitive for production analysis

Typical Ranges:

  • β < 0.5: Low heterogeneity (L ~ 0.2-0.3)

  • β = 0.5-0.7: Moderate (L ~ 0.3-0.5)

  • β > 0.7: High heterogeneity (L > 0.5)

Use Cases:

  • Literature Conversion: Convert published beta values to Lorenz

  • Reservoir Comparison: Compare reservoirs using different metrics

  • Simulation Input: Convert beta to Lorenz for simulation models

  • Reservoir Analog Studies: Use analog beta values with Lorenz-based tools

  • Historical Data: Convert old Dykstra-Parsons studies to modern metrics

Returns: Dictionary with:

  • lorenz_coefficient (float): Lorenz coefficient (0-1)

  • beta (float): Input beta coefficient

  • method (str): "Dykstra-Parsons to Lorenz conversion"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Beta coefficient outside valid range (must be 0-1)

  • Confusing beta with other variation coefficients

  • Using beta from wrong distribution (must be log-normal)

  • Not understanding that conversion is approximate (depends on distribution)

Example Usage:

{
    "value": 0.6
}

Result: L ≈ 0.4-0.5 (moderate heterogeneity).

Note: Conversion assumes log-normal permeability distribution. For non-log-normal distributions, conversion may be less accurate. Always validate against actual production data when possible.

Inputs: request (required). Returns: object

calculate_brine_propertiesA

Calculate properties of CH4 or CO2 saturated brine.

BRINE PVT TOOL - Computes comprehensive brine properties including density, viscosity, compressibility, and formation volume factor. Essential for aquifer analysis, water injection, and CO2 sequestration studies.

Parameters:

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0 or [1000, 2000, 3000].

  • degf (float, required): Temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • wt (float, required): Salinity in weight percent NaCl (0-30). Typical: 0-20 wt%. Example: 5.0 for 5% NaCl brine.

  • ch4 (float, optional, default=0.0): CH4 saturation fraction (0-1). Typical: 0-0.1. Example: 0.05 for 5% CH4 saturation.

  • co2 (float, optional, default=0.0): CO2 saturation fraction (0-1). Typical: 0-0.1. Example: 0.03 for 3% CO2 saturation.

Properties Calculated:

  • Density (ρw): Brine density in lb/cuft. Increases with salinity, pressure. Typical: 60-70 lb/cuft.

  • Viscosity (μw): Brine viscosity in cP. Decreases with temperature, increases with salinity. Typical: 0.3-1.5 cP.

  • Compressibility (cw): Brine compressibility in 1/psi. Critical for aquifer influx. Typical: 2e-6 to 5e-6 1/psi.

  • Formation Volume Factor (Bw): Volume ratio rb/stb. Slightly > 1.0. Typical: 1.01-1.05 rb/stb.

  • Solution GOR (Rw): Gas dissolved in brine in scf/stb. Increases with pressure. Typical: 0-20 scf/stb.

Dissolved Gas Effects:

  • CH4-saturated: Methane dissolved in formation water (typical in aquifers)

  • CO2-saturated: CO2 dissolution (sequestration, EOR, geothermal)

  • Mixed systems supported (CH4 + CO2)

  • Dissolved gas reduces density and increases compressibility

Salinity Range: 0-30 wt% NaCl (fresh water to highly saline)

  • Fresh water: 0 wt%

  • Brackish: 0.1-1 wt%

  • Seawater: ~3.5 wt%

  • Formation brine: 5-20 wt%

  • Highly saline: 20-30 wt%

Correlations: Uses industry-standard correlations accounting for:

  • Pressure effects on density and viscosity

  • Temperature effects (viscosity decreases with T)

  • Salinity variations (density and viscosity increase with salinity)

  • Dissolved gas concentrations (reduces density)

Applications:

  • Aquifer Influx: Calculate water influx rates and volumes

  • Water Injection: Design injection projects and pressure maintenance

  • CO2 Sequestration: Evaluate CO2 storage capacity and brine properties

  • Geothermal Reservoirs: Analyze geothermal brine properties

  • Pressure Maintenance: Evaluate aquifer pressure support

  • Material Balance: Include water drive in material balance calculations

Returns: Dictionary with:

  • formation_volume_factor_rb_stb (float or list): Bw (matches input p shape)

  • density_lb_cuft (float or list): Brine density (matches input p shape)

  • viscosity_cp (float or list): Brine viscosity (matches input p shape)

  • compressibility_1_psi (float or list): Brine compressibility (matches input p shape)

  • solution_gor_scf_stb (float or list): Gas dissolved in brine (matches input p shape)

  • method (str): "Industry standard correlations"

  • salinity_wt_percent (float): Input salinity

  • dissolved_gas_saturation (float): Combined CH4+CO2 saturation

  • note (str): Usage guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Salinity in ppm instead of wt% (must convert: wt% = ppm/10000)

  • Not accounting for dissolved gas (affects density and compressibility)

  • Temperature in Celsius instead of Fahrenheit

  • Confusing CH4 and CO2 saturation fractions

Example Usage:

{
    "p": [1000, 2000, 3000],
    "degf": 180.0,
    "wt": 5.0,
    "ch4": 0.05,
    "co2": 0.0
}

Result: Brine density increases with pressure, viscosity decreases with temperature. Dissolved CH4 reduces density compared to pure brine.

Note: Brine properties are critical for accurate aquifer modeling. Always account for dissolved gas (CH4 or CO2) as it significantly affects density and compressibility. Salinity has major impact on density and viscosity - use correct formation water salinity.

Inputs: request (required). Returns: object

co2_brine_mutual_solubilityA

Calculate CO2-brine mutual solubilities and properties.

CRITICAL CO2-BRINE SYSTEM TOOL - Computes comprehensive properties for CO2-saturated brine systems using the Duan & Sun (2003) model. Essential for CO2 sequestration, CO2-EOR, and geothermal applications. Accounts for mutual solubility (CO2 in brine, H2O in CO2-rich phase).

Parameters:

  • pres (float, required): Pressure in psia (field) or bar (metric). Must be > 0. Typical: 1000-5000 psia. Example: 3000.0 psia.

  • temp (float, required): Temperature in °F (field) or °C (metric). Typical: 100-400°F. Example: 180.0°F.

  • ppm (float, required): Salinity in parts per million (ppm) NaCl. Typical: 0-200000 ppm. Example: 50000 ppm (5 wt%).

  • metric (bool, optional, default=False): Unit system flag. False = field units (psia, °F), True = metric (bar, °C).

  • cw_sat (bool, optional, default=True): Compressibility calculation flag. True = saturated compressibility, False = undersaturated.

Properties Calculated:

  • Phase Equilibrium:

    • Aqueous phase mole fractions (x_CO2, x_H2O)

    • Vapor phase mole fractions (y_CO2, y_H2O)

    • Salt mole fraction

  • Densities:

    • CO2-rich gas density (gm/cm³)

    • Brine CO2-saturated density (gm/cm³)

    • Brine pure density (gm/cm³)

    • Fresh water density (gm/cm³)

  • Viscosities:

    • Brine CO2-saturated viscosity (cP)

    • Brine pure viscosity (cP)

    • Fresh water viscosity (cP)

  • Formation Volume Factors:

    • Bw CO2-saturated (rb/stb)

    • Bw pure (rb/stb)

    • Bw fresh (rb/stb)

  • Compressibility:

    • Undersaturated compressibility (1/psi or 1/bar)

    • Saturated compressibility (1/psi or 1/bar)

  • Solution GOR: CO2 dissolved in brine (scf/stb or m³/m³)

Mutual Solubility: CO2-brine systems exhibit mutual solubility:

  • CO2 dissolves in brine (increases with pressure, decreases with salinity)

  • H2O dissolves in CO2-rich phase (increases with temperature)

  • Both solubilities depend on pressure, temperature, and salinity

Physics: Uses Duan & Sun (2003) model for CO2-H2O-NaCl systems accounting for:

  • Pressure effects on solubility (higher P = more CO2 dissolved)

  • Temperature effects (higher T = less CO2 dissolved, more H2O in vapor)

  • Salinity effects (higher salinity = less CO2 dissolved)

  • Mutual solubility (both phases contain both components)

Applications:

  • CO2 Sequestration: CCS project design, storage capacity evaluation

  • CO2-EOR: Enhanced oil recovery with CO2 injection, miscibility studies

  • Geothermal: CO2-based geothermal systems, supercritical CO2

  • Aquifer Storage: Underground CO2 storage capacity, leakage assessment

  • Material Balance: CO2-brine material balance calculations

Salinity Conversion:

  • 1 wt% = 10,000 ppm

  • Seawater ≈ 35,000 ppm (3.5 wt%)

  • Formation brine: 50,000-200,000 ppm (5-20 wt%)

Returns: Dictionary with:

  • phase_equilibrium (dict): Mole fractions in aqueous and vapor phases

  • densities (dict): All density values (CO2-rich, saturated, pure, fresh)

  • viscosities (dict): All viscosity values (saturated, pure, fresh)

  • formation_volume_factors (dict): Bw values (saturated, pure, fresh)

  • compressibility (dict): Undersaturated and saturated compressibility

  • solution_gor_co2 (float): CO2 dissolved in brine

  • viscosibility_per_bar_or_psi (float): Viscosibility coefficient

  • method (str): "Duan & Sun (2003) CO2-H2O-NaCl model"

  • units (str): "metric" or "field"

  • note (str): Usage guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using wrong unit system (check metric flag)

  • Salinity in wt% instead of ppm (must convert: ppm = wt% × 10000)

  • Pressure in barg/psig instead of psia (must be absolute)

  • Temperature in wrong units (check metric flag)

  • Not accounting for mutual solubility (both phases contain both components)

  • Using wrong compressibility (saturated vs undersaturated)

Example Usage (Field Units):

{
    "pres": 3000.0,
    "temp": 180.0,
    "ppm": 50000,
    "metric": False,
    "cw_sat": True
}

Result: CO2 solubility in brine ≈ 20-40 scf/stb, H2O in CO2-rich phase ≈ 0.1-1 mol%.

Note: CO2-brine mutual solubility is critical for CCS and CO2-EOR projects. Always use correct unit system (field vs metric). The model accounts for mutual solubility which is significant at high pressures and temperatures. Salinity significantly reduces CO2 solubility - use correct formation water salinity.

Inputs: request (required). Returns: object

evolved_gas_sgA

Calculate evolved gas specific gravity.

Computes the specific gravity of gas evolved from oil as pressure decreases below bubble point. This is important for:

  • Material balance calculations

  • Surface facility design

  • Gas sales forecasting

The evolved gas composition changes with pressure, and this function accounts for that variation.

Returns dimensionless specific gravity (air = 1.0).

Args: request: Evolved gas parameters including oil properties, pressure(s), and separator conditions

Returns: Dictionary with evolved gas SG value(s), units, and inputs

Inputs: request (required). Returns: object

extract_eclipse_problem_cellsA

Extract convergence problem cells from ECLIPSE/Intersect PRT file.

SIMULATION DIAGNOSTICS TOOL - Parse ECLIPSE/Intersect PRT output files to extract cells with convergence failures, material balance errors, or other simulation problems.

What It Does:

  • Scans ECLIPSE .PRT files for error/warning messages

  • Identifies problem cells by (I, J, K) grid coordinates

  • Extracts timestep and iteration information

  • Reports error types and severity

Applications:

  • Convergence Debugging: Find cells causing timestep cuts

  • Model QC: Identify grid initialization issues

  • Performance Tuning: Locate problematic regions

  • Numerical Stability: Track material balance errors

Common Problems Detected:

  • Material balance errors

  • Negative saturations

  • Pressure/temperature out of range

  • Flash calculation failures

  • Linear solver issues

  • Severe saturation changes

Workflow:

  1. Run ECLIPSE/Intersect simulation

  2. Locate the .PRT output file

  3. Use this tool to extract problem cell locations

  4. Investigate problematic cells in pre-processor

  5. Refine initialization or grid properties

Output Format: List of problem cells with timestep, iteration, cell coordinates (I,J,K), error type, and severity.

Args: request: Path to PRT file and output options

Returns: Dictionary with list of problem cells and summary statistics

Inputs: request (required). Returns: object

flow_fractions_from_lorenzA

Generate flow fractions from Lorenz coefficient.

SYNTHETIC FLOW PROFILE - Creates idealized flow distribution matching a specified Lorenz coefficient. Generates a Lorenz curve (cumulative flow vs cumulative capacity) that honors the target heterogeneity level.

Parameters:

  • value (float, required): Target Lorenz coefficient (0-1). Must be 0 ≤ L ≤ 1. Typical: 0.2-0.7. Example: 0.5 for moderate heterogeneity.

Lorenz Curve Generation: Creates a curve showing:

  • X-axis: Cumulative storage capacity (kh fraction)

  • Y-axis: Cumulative flow capacity (flow fraction)

  • Curve shape: Determined by Lorenz coefficient

  • Points: 20 points along the curve for visualization

Curve Behavior:

  • L = 0: Straight diagonal line (perfect conformance)

  • L > 0: Curved line below diagonal (flow imbalance)

  • Higher L: More curvature, greater flow imbalance

Applications:

  • Reservoir Simulation: Generate layer properties for simulation models

  • Waterflood Prediction: Predict sweep efficiency from heterogeneity

  • Sweep Efficiency Estimation: Estimate vertical sweep from Lorenz

  • Sensitivity Analysis: Test impact of heterogeneity on performance

  • Conceptual Models: Create idealized reservoir models for studies

  • Visualization: Plot Lorenz curve to visualize heterogeneity

Returns: Dictionary with:

  • cumulative_flow_capacity (list): Y-axis values (cumulative flow fractions)

  • cumulative_storage_capacity (list): X-axis values (cumulative kh fractions)

  • lorenz_coefficient (float): Target Lorenz coefficient

  • method (str): "Generated Lorenz curve"

  • note (str): Visualization guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Lorenz coefficient outside valid range (must be 0-1)

  • Confusing cumulative fractions with incremental fractions

  • Not understanding that curve represents idealized distribution

  • Using curve for non-log-normal distributions (may be inaccurate)

Example Usage:

{
    "value": 0.5
}

Result: Lorenz curve with 20 points showing cumulative flow vs cumulative capacity. Curve is below diagonal, indicating flow imbalance (high-k layers produce more than their capacity fraction).

Note: This generates an idealized Lorenz curve. For actual reservoirs, use lorenz_from_flow_fractions with measured production data. The curve assumes log-normal permeability distribution. Plot cumulative flow vs cumulative storage to visualize heterogeneity.

Inputs: request (required). Returns: object

gas_compressibilityA

Calculate gas compressibility (Cg).

CRITICAL GAS PVT PROPERTY - Computes gas compressibility coefficient, which measures how much gas volume changes with pressure. Essential for material balance calculations, pressure transient analysis, and reserve estimation. Gas compressibility is much higher than oil compressibility (typically 100-1000 × 10⁻⁶ 1/psi vs 5-50 × 10⁻⁶).

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3500.0 or [1000, 2000, 3000, 4000].

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01.

  • zmethod (str, optional, default="DAK"): Z-factor method for compressibility. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Compressibility Behavior:

  • Decreases with increasing pressure (gas becomes less compressible)

  • Typical range: 50-500 × 10⁻⁶ 1/psi at reservoir conditions

  • At low pressure: Cg ≈ 1/P (ideal gas behavior)

  • At high pressure: Cg decreases significantly

Formula: Cg = (1/Z) × (∂Z/∂P) - (1/P)

Where Z-factor and its pressure derivative are calculated using specified method.

Returns: Dictionary with:

  • value (float or list): Compressibility in 1/psi (matches input p shape)

  • method (str): Z-factor method used

  • units (str): "1/psi"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions

  • Confusing gas compressibility (high, 100-1000 × 10⁻⁶) with oil compressibility (low, 5-50 × 10⁻⁶)

  • Using ideal gas approximation (Cg = 1/P) instead of real gas

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p": [1000, 2000, 3000, 4000],
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "zmethod": "DAK"
}

Result: Cg decreases from ~1000 × 10⁻⁶ 1/psi at 1000 psia to ~250 × 10⁻⁶ 1/psi at 4000 psia.

Note: Gas compressibility is critical for material balance calculations. Always use reservoir conditions. Account for all non-hydrocarbon components. Cg values are small (micro-1/psi), so results are typically in scientific notation.

Inputs: request (required). Returns: object

gas_critical_propertiesA

Calculate gas pseudo-critical properties (Tc and Pc).

CRITICAL GAS PROPERTY CALCULATION - Computes pseudo-critical temperature and pressure for real gas mixtures. Required for Z-factor calculations and all gas property correlations. Pseudo-critical properties are weighted averages of pure component critical properties, adjusted for non-hydrocarbon components.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7 for dry gas.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02 for 2% H2S. High H2S significantly affects Tc/Pc.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05 for 5% CO2.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01 for 1% N2.

  • method (str, optional, default="PMC"): Correlation method. Options: "PMC", "SUT", "BUR". PMC recommended.

Pseudo-Critical Properties:

  • Tc (Pseudo-critical Temperature): Temperature above which gas cannot be liquefied regardless of pressure. Typical: 300-500°R for natural gas.

  • Pc (Pseudo-critical Pressure): Pressure at critical temperature. Typical: 600-800 psia for natural gas.

Method Selection:

  • PMC (Piper, McCain & Corredor 1993): RECOMMENDED. Most accurate for wide range of gas compositions. Accounts for non-hydrocarbon effects.

  • SUT (Sutton 1985): Classic method. Use for compatibility with older methods.

  • BUR (Burrows 1981): Alternative method. Use for specific applications.

Non-Hydrocarbon Effects:

  • H2S: Increases both Tc and Pc significantly

  • CO2: Increases Tc, decreases Pc slightly

  • N2: Increases Pc, decreases Tc slightly

  • Always account for non-hydrocarbons for accurate Z-factor calculations

Returns: Dictionary with:

  • value (dict): Contains "tc" (degR) and "pc" (psia)

  • method (str): Method used

  • units (dict): {"tc": "degR", "pc": "psia"}

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Not accounting for non-hydrocarbon fractions (H2S, CO2, N2)

  • Using wrong gas gravity (must be separator gas, not sales gas)

  • Confusing pseudo-critical with true critical properties

  • Using critical properties for pure components instead of mixtures

Example Usage:

{
    "sg": 0.7,
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "method": "PMC"
}

Result: Tc ≈ 380-420°R, Pc ≈ 650-750 psia for typical natural gas.

Note: Critical properties are used internally by gas_z_factor and other gas property tools. Always use PMC method unless specific compatibility required. Account for all non-hydrocarbon components - even small amounts affect results.

Inputs: request (required). Returns: object

gas_densityA

Calculate gas density (ρg) at reservoir conditions.

CRITICAL GAS PVT PROPERTY - Computes gas density from real gas equation of state. Essential for gradient calculations, well pressure analysis, and material balance. Gas density increases significantly with pressure due to compressibility.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3500.0 or [1000, 2000, 3000, 4000].

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01.

  • zmethod (str, optional, default="DAK"): Z-factor method for density calculation. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Density Formula: ρg = (P × MW) / (Z × R × T)

Where:

  • P = pressure (psia)

  • MW = molecular weight = sg × 28.97 lb/lbmol

  • Z = gas compressibility factor

  • R = gas constant = 10.732 psia·ft³/(lbmol·°R)

  • T = temperature (°R = °F + 460)

Density Behavior:

  • Increases with pressure (gas compresses)

  • Decreases with temperature (gas expands)

  • Typical range: 5-20 lb/cuft at reservoir conditions

  • At standard conditions: ~0.05-0.1 lb/cuft

Returns: Dictionary with:

  • value (float or list): Density in lb/cuft (matches input p shape)

  • method (str): Z-factor method used

  • units (str): "lb/cuft"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions

  • Using ideal gas law (Z=1) instead of real gas (Z<1)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p": [1000, 2000, 3000, 4000],
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "zmethod": "DAK"
}

Result: Density increases from ~8 lb/cuft at 1000 psia to ~18 lb/cuft at 4000 psia.

Note: Gas density is much lower than oil density (typically 5-20 lb/cuft vs 40-60 lb/cuft). Always use reservoir conditions. Account for all non-hydrocarbon components - they significantly affect molecular weight and density.

Inputs: request (required). Returns: object

gas_formation_volume_factorA

Calculate gas formation volume factor (Bg).

CRITICAL GAS PVT PROPERTY - Computes ratio of gas volume at reservoir conditions to volume at standard conditions. Bg << 1.0 because gas compresses significantly at reservoir pressure. Essential for material balance, reserve calculations, and production forecasting.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3500.0 or [1000, 2000, 3000, 4000].

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01.

  • zmethod (str, optional, default="DAK"): Z-factor method for Bg calculation. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Bg Behavior:

  • Bg decreases with increasing pressure (gas compresses)

  • Bg increases with increasing temperature (gas expands)

  • Typical range: 0.001-0.01 rcf/scf at reservoir conditions

  • At standard conditions (14.7 psia, 60°F): Bg = 1.0 rcf/scf

Formula: Bg = (Z × T × Psc) / (P × Tsc) = 0.02827 × Z × T / P (field units)

Where:

  • Z = gas compressibility factor (from gas_z_factor tool)

  • T = reservoir temperature (°R)

  • P = reservoir pressure (psia)

  • Psc = 14.7 psia, Tsc = 520°R (standard conditions)

Returns: Dictionary with:

  • value (float or list): Bg in rcf/scf (matches input p shape)

  • method (str): Z-factor method used

  • units (str): "rcf/scf"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions

  • Confusing Bg (gas FVF) with Bo (oil FVF)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p": [1000, 2000, 3000, 4000],
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "zmethod": "DAK"
}

Result: Bg decreases from ~0.005 rcf/scf at 1000 psia to ~0.002 rcf/scf at 4000 psia.

Note: Bg is inversely proportional to pressure. Always use reservoir conditions, not separator conditions. Account for all non-hydrocarbon components for accuracy.

Inputs: request (required). Returns: object

gas_pressure_from_pzA

Calculate pressure from P/Z value.

MATERIAL BALANCE TOOL - Solves for pressure given a P/Z (pressure/Z-factor) value. Essential for gas material balance analysis where P/Z vs cumulative production is plotted. Uses iterative solution to find pressure that yields the specified P/Z value.

Parameters:

  • pz (float or list, required): P/Z value(s) in psia. Must be > 0. Can be scalar or array. Example: 5000.0 or [4000, 5000, 6000].

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.0.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.0.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.0.

  • zmethod (str, optional, default="DAK"): Z-factor method for calculation. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

P/Z Method Applications:

  • Volumetric Gas Reserves: P/Z vs Gp plot gives GIIP (Gas Initially In Place)

  • Aquifer Influx Detection: Deviation from straight line indicates water drive

  • Drive Mechanism Identification: Volumetric vs water drive vs gas cap

  • Production Forecasting: Extrapolate P/Z to abandonment pressure

Material Balance Principle: For volumetric gas reservoirs: P/Z = (Pi/Zi) × (1 - Gp/G) Where Gp = cumulative production, G = GIIP

A straight line on P/Z vs Gp indicates volumetric depletion. Deviation suggests water influx, changing pore volume, or gas cap expansion.

Solution Method: Iterative Newton-Raphson method to solve: P/Z - pz_target = 0 Converges rapidly for well-posed problems.

Returns: Dictionary with:

  • value (float or list): Pressure in psia (matches input pz shape)

  • method (str): Iterative solution method with Z-factor method

  • units (str): "psia"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Not accounting for non-hydrocarbon fractions

  • Confusing P/Z (pressure/Z-factor) with pressure

  • Using wrong Z-factor method (must match method used in material balance)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "pz": 5000.0,
    "sg": 0.7,
    "degf": 180.0,
    "h2s": 0.0,
    "co2": 0.0,
    "n2": 0.0,
    "zmethod": "DAK"
}

Result: Pressure ≈ 4500-5500 psia (depends on Z-factor at that pressure).

Note: P/Z method is fundamental to gas material balance. Always use the same Z-factor method throughout your analysis for consistency. Account for all non-hydrocarbon components as they affect Z-factor and thus P/Z values.

Inputs: request (required). Returns: object

gas_pseudopressureA

Calculate gas pseudopressure difference (m(p)).

CRITICAL GAS ANALYSIS TOOL - Computes pseudopressure difference, a pressure transformation that linearizes the gas diffusivity equation. This makes gas flow analysis mathematically similar to liquid flow, enabling use of liquid flow solutions for gas systems. Essential for accurate gas well performance analysis.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p1 (float, required): Initial pressure in psia. Must be > 0. Typically reservoir pressure. Example: 1000.0.

  • p2 (float, required): Final pressure in psia. Must be > 0. Typically sandface pressure. Example: 3500.0.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.0.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.0.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.0.

  • zmethod (str, optional, default="DAK"): Z-factor method for integration. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Pseudopressure Formula: m(p) = 2∫(p/(μZ))dp from p1 to p2

Where:

  • p = pressure (psia)

  • μ = gas viscosity (cP)

  • Z = gas compressibility factor

Why Pseudopressure: Gas properties (Z, μ) vary significantly with pressure, making gas flow non-linear. Pseudopressure transformation accounts for these variations, enabling:

  • Use of liquid flow solutions for gas

  • Linear pressure analysis

  • Accurate well test interpretation

  • Material balance calculations

Applications:

  • Gas Well Testing: Pressure transient analysis, rate transient analysis

  • Material Balance: P/Z vs cumulative production plots

  • Reservoir Simulation: Input for gas flow calculations

  • IPR Curves: Inflow performance relationship generation

Returns: Dictionary with:

  • value (float): Pseudopressure difference in psia²/cP

  • method (str): Integration method with Z-factor method used

  • units (str): "psia²/cP"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions

  • Confusing pseudopressure with actual pressure

  • Using wrong pressure order (p1 should be lower than p2 typically)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p1": 1000.0,
    "p2": 3500.0,
    "h2s": 0.0,
    "co2": 0.0,
    "n2": 0.0,
    "zmethod": "DAK"
}

Result: Pseudopressure difference ≈ 1-5 × 10⁶ psia²/cP (typical range).

Note: Pseudopressure is essential for accurate gas flow calculations. Always use reservoir conditions. Account for all non-hydrocarbon components. The integration is performed numerically, so results are approximate but highly accurate.

Inputs: request (required). Returns: object

gas_rate_linearA

Calculate gas production rate for linear flow.

INFLOW PERFORMANCE TOOL - Computes gas production rate for horizontal wells or wells with linear flow geometry using real gas pseudopressure formulation. This accounts for pressure-dependent gas properties (Z-factor, viscosity) which are significant for gas systems. More accurate than simplified Darcy's law for gas.

Parameters:

  • pi (float, required): Initial/reservoir pressure in psia. Must be > 0. Example: 5000.0.

  • sg (float, required): Gas specific gravity (air=1). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • psd (float or list, required): Sandface/draining pressure(s) in psia. Must be > 0 and < pi. Can be scalar or array. Example: 2000.0 or [1000, 2000, 3000].

  • h (float, required): Net pay thickness in feet. Must be > 0. Typical: 10-200 ft. Example: 50.0.

  • k (float, required): Permeability in millidarcies (mD). Must be > 0. Typical: 1-1000 mD. Example: 100.0.

  • area (float, required): Cross-sectional flow area in square feet. Must be > 0. Typical: 100-10000 ft². Example: 1000.0.

  • length (float, required): Flow length in feet. Must be > 0. Typical: 100-5000 ft. Example: 500.0.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.0.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.0.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.0.

Flow Geometry: Linear flow occurs in:

  • Horizontal wells (early-time flow)

  • Hydraulically fractured vertical wells (fracture flow)

  • Channelized gas reservoirs

  • Edge water drive systems

Pseudopressure Method: Uses real gas pseudopressure (m(p)) which linearizes the gas diffusivity equation: m(p) = 2∫(p/(μZ))dp from pb to p

This accounts for:

  • Z-factor variation with pressure

  • Gas viscosity variation with pressure

  • Non-linear pressure behavior

Flow Formula (Linear): qg = (k × area × (m(pi) - m(pwf))) / (1422 × T × length)

Where PVT properties are integrated over pressure range.

Linear vs Radial Flow:

  • Linear: Flow perpendicular to wellbore (horizontal wells)

  • Radial: Flow converging to wellbore (vertical wells)

  • Linear flow typically has higher productivity than radial

Returns: Dictionary with:

  • value (float or list): Gas rate in MSCF/day (matches input psd shape)

  • method (str): "Pseudopressure linear flow"

  • units (str): "MSCF/day"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions (H2S, CO2, N2)

  • Confusing flow area (perpendicular to flow) with wellbore area

  • Using wrong flow length (should be distance from boundary to well)

  • Confusing linear flow (horizontal wells) with radial flow (vertical wells)

  • Not accounting for net pay thickness correctly

Example Usage:

{
    "pi": 5000.0,
    "sg": 0.7,
    "degf": 180.0,
    "psd": [2000, 3000, 4000],
    "h": 50.0,
    "k": 100.0,
    "area": 1000.0,
    "length": 500.0,
    "h2s": 0.0,
    "co2": 0.0,
    "n2": 0.0
}

Result: Gas rate decreases as sandface pressure increases (typical IPR curve).

Note: This tool uses pseudopressure method which is more accurate than simplified Darcy's law for gas. Always account for non-hydrocarbon components (H2S, CO2, N2) as they affect Z-factor and flow calculations significantly. Linear flow is characteristic of horizontal wells and hydraulically fractured wells.

Inputs: request (required). Returns: object

gas_rate_radialA

Calculate gas production rate for radial flow (vertical well).

INFLOW PERFORMANCE TOOL - Computes gas production rate for vertical wells with radial flow geometry using real gas pseudopressure formulation. This accounts for pressure-dependent gas properties (Z-factor, viscosity) which are significant for gas systems. More accurate than simplified Darcy's law for gas.

Parameters:

  • pi (float, required): Initial/reservoir pressure in psia. Must be > 0. Example: 5000.0.

  • sg (float, required): Gas specific gravity (air=1). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • psd (float or list, required): Sandface/draining pressure(s) in psia. Must be > 0 and < pi. Can be scalar or array. Example: 2000.0 or [1000, 2000, 3000].

  • h (float, required): Net pay thickness in feet. Must be > 0. Typical: 10-200 ft. Example: 50.0.

  • k (float, required): Permeability in millidarcies (mD). Must be > 0. Typical: 1-1000 mD. Example: 100.0.

  • s (float, optional, default=0.0): Skin factor (dimensionless). Negative = stimulation, positive = damage. Typical: -5 to +20. Example: 0.0 for undamaged well.

  • re (float, required): Drainage radius in feet. Must be > rw. Typical: 500-5000 ft. Example: 1000.0.

  • rw (float, required): Wellbore radius in feet. Must be > 0. Typical: 0.25-0.5 ft. Example: 0.5.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.0.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.0.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.0.

Pseudopressure Method: Uses real gas pseudopressure (m(p)) which linearizes the gas diffusivity equation: m(p) = 2∫(p/(μZ))dp from pb to p

This accounts for:

  • Z-factor variation with pressure

  • Gas viscosity variation with pressure

  • Non-linear pressure behavior

Flow Formula: qg = (kh × (m(pi) - m(pwf))) / (1422 × T × (ln(re/rw) + S))

Where PVT properties are integrated over pressure range.

Returns: Dictionary with:

  • value (float or list): Gas rate in MSCF/day (matches input psd shape)

  • method (str): "Pseudopressure radial flow"

  • units (str): "MSCF/day"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions (H2S, CO2, N2)

  • Using wrong drainage radius (re) - should be well spacing/2

  • Confusing net pay (h) with gross thickness

  • Not accounting for skin factor (s)

Example Usage:

{
    "pi": 5000.0,
    "sg": 0.7,
    "degf": 180.0,
    "psd": [2000, 3000, 4000],
    "h": 50.0,
    "k": 100.0,
    "s": 0.0,
    "re": 1000.0,
    "rw": 0.5,
    "h2s": 0.0,
    "co2": 0.0,
    "n2": 0.0
}

Result: Gas rate decreases as sandface pressure increases (typical IPR curve).

Note: This tool uses pseudopressure method which is more accurate than simplified Darcy's law for gas. Always account for non-hydrocarbon components (H2S, CO2, N2) as they affect Z-factor and flow calculations significantly.

Inputs: request (required). Returns: object

gas_sg_from_compositionA

Calculate gas specific gravity from composition.

COMPOSITIONAL GAS CHARACTERIZATION - Computes gas specific gravity from hydrocarbon molecular weight and non-hydrocarbon mole fractions. Uses molecular weight weighted average method. Essential when gas composition is known but SG measurement is unavailable or unreliable.

Parameters:

  • hc_mw (float, required): Hydrocarbon molecular weight in lb/lbmol. Valid: 10-200. Typical: 16-50. Example: 18.5 for typical natural gas.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05 for 5% CO2.

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02 for 2% H2S (sour gas).

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01 for 1% N2.

  • h2 (float, optional, default=0.0): H2 mole fraction (0-1). Typical: 0-0.01. Example: 0.0 (rare in natural gas).

Calculation Method: Weighted average based on molecular weights:

  • HC fraction: User-provided MW (hc_mw)

  • CO2: MW = 44.01 lb/lbmol

  • H2S: MW = 34.08 lb/lbmol

  • N2: MW = 28.01 lb/lbmol

  • H2: MW = 2.02 lb/lbmol

  • Air: MW = 28.97 lb/lbmol (reference for SG)

Formula: MW_avg = hc_fraction × hc_mw + co2 × 44.01 + h2s × 34.08 + n2 × 28.01 + h2 × 2.02 SG = MW_avg / 28.97

Typical Hydrocarbon MW:

  • Pure methane: 16.04

  • Dry gas (C1-C2): 16-18

  • Associated gas (C1-C4): 18-25

  • Wet gas (C1-C6): 25-35

  • Condensate gas: 35-50

Applications:

  • Compositional Simulation: Convert composition to SG for black oil models

  • Gas Plant Feed: Characterize feed gas from composition analysis

  • Sales Gas Specs: Calculate SG for pipeline specifications

  • Contaminated Gas: Analyze gas with high non-hydrocarbon content

  • Laboratory Data: Convert GC analysis to SG

Non-Hydrocarbon Effects:

  • CO2 increases SG (MW=44.01 > air MW=28.97)

  • H2S increases SG (MW=34.08 > air MW=28.97)

  • N2 slightly decreases SG (MW=28.01 ≈ air MW=28.97)

  • H2 significantly decreases SG (MW=2.02 << air MW=28.97)

Returns: Dictionary with:

  • gas_specific_gravity (float): Gas SG (dimensionless, air=1)

  • composition (dict): Detailed composition breakdown

    • hydrocarbon_fraction: Mole fraction of hydrocarbons

    • hydrocarbon_mw: Provided hydrocarbon MW

    • co2_fraction: CO2 mole fraction

    • h2s_fraction: H2S mole fraction

    • n2_fraction: N2 mole fraction

    • h2_fraction: H2 mole fraction

  • method (str): "Molecular weight weighted average"

  • units (str): "dimensionless (air=1)"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using weight fraction instead of mole fraction

  • Incorrect hydrocarbon MW (must be average MW of HC fraction)

  • Mole fractions don't sum to 1.0 (should sum to 1.0)

  • Using component MW instead of mixture MW for hydrocarbons

  • Not accounting for all non-hydrocarbon components

Example Usage:

{
    "hc_mw": 18.5,
    "co2": 0.05,
    "h2s": 0.0,
    "n2": 0.01,
    "h2": 0.0
}

Result: SG ≈ 0.65-0.70 (typical natural gas with 5% CO2, 1% N2).

Note: Mole fractions must sum to 1.0. If only HC fraction is provided, ensure hc_fraction = 1.0 - (co2 + h2s + n2 + h2). Hydrocarbon MW should be the average MW of the hydrocarbon fraction, not individual component MW.

Inputs: request (required). Returns: object

gas_sg_from_gradientA

Calculate gas specific gravity from pressure gradient.

DIAGNOSTIC TOOL - Determines gas specific gravity from measured pressure gradient in a gas column. Uses standalone Newton-Raphson solver (fixed implementation) to solve the inverse problem. Essential for formation fluid identification and gas property verification when only gradient data is available.

Parameters:

  • gradient (float, required): Pressure gradient in psi/ft. Must be > 0. Typical: 0.05-0.15 psi/ft. Example: 0.1 psi/ft.

  • degf (float, required): Temperature in °F at measurement depth. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float, required): Pressure in psia at measurement depth. Must be > 0. Example: 3500.0.

  • method (str, optional, default="DAK"): Z-factor method for calculation. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Gradient Principle: Gas gradient = dP/dh = (ρg × g) / 144 = (P × MW) / (Z × R × T × 144)

Where:

  • ρg = gas density (lb/cuft)

  • MW = molecular weight = sg × 28.97 lb/lbmol

  • Z = gas compressibility factor

  • R = gas constant = 10.732 psia·ft³/(lbmol·°R)

  • T = temperature (°R = °F + 460)

Applications:

  • Formation Fluid ID: Identify gas vs oil vs water from gradient

  • Gas Density Verification: Check measured gas gravity against gradient

  • Completion Fluid Design: Design mud weight based on gas gradient

  • Wellbore Pressure Modeling: Calculate pressure profiles in gas columns

Typical Gradients:

  • Dry gas (sg=0.6): ~0.08 psi/ft

  • Associated gas (sg=0.8): ~0.11 psi/ft

  • Heavy gas (sg=1.0): ~0.14 psi/ft

Solution Method: Uses Newton-Raphson iterative solver to find sg that yields the specified gradient. This is a standalone fixed implementation that avoids upstream library bugs.

Returns: Dictionary with:

  • value (float): Gas specific gravity (dimensionless, air=1)

  • method (str): "Gradient correlation (Newton-Raphson)"

  • units (str): "dimensionless (air=1)"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions (affects MW and Z)

  • Using wrong gradient units (must be psi/ft, not psi/100ft)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "gradient": 0.1,
    "degf": 180.0,
    "p": 3500.0,
    "method": "DAK"
}

Result: Gas SG ≈ 0.7-0.8 for typical natural gas gradient.

Note: This tool uses a standalone fixed implementation to avoid upstream bugs. Always use reservoir conditions (pressure and temperature at measurement depth). Gradient is sensitive to temperature - use correct temperature for accurate results.

Inputs: request (required). Returns: object

gas_viscosityA

Calculate gas viscosity (μg).

CRITICAL GAS PVT PROPERTY - Computes gas viscosity at reservoir conditions using Lee, Gonzalez & Eakin (1966) correlation, industry standard for natural gas. Viscosity affects flow rates, pressure drops, and well performance. Gas viscosity increases with pressure and temperature, opposite to liquid behavior.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3500.0 or [1000, 2000, 3000, 4000].

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01.

  • zmethod (str, optional, default="DAK"): Z-factor method for viscosity calculation. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Viscosity Behavior:

  • Increases with pressure (gas molecules closer together)

  • Increases with temperature (molecular motion increases)

  • Typical range: 0.01-0.05 cP at reservoir conditions

  • At standard conditions: ~0.01 cP

Lee-Gonzalez-Eakin Correlation: Uses Z-factor internally to account for real gas behavior. More accurate than ideal gas assumptions, especially at high pressures.

Returns: Dictionary with:

  • value (float or list): Viscosity in cP (matches input p shape)

  • method (str): "Lee-Gonzalez-Eakin"

  • units (str): "cP"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions

  • Confusing gas viscosity (increases with P) with oil viscosity (decreases with P)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p": [1000, 2000, 3000, 4000],
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "zmethod": "DAK"
}

Result: Viscosity increases from ~0.012 cP at 1000 psia to ~0.025 cP at 4000 psia.

Note: Gas viscosity is much lower than oil viscosity (typically 0.01-0.05 cP vs 0.5-10 cP). Always use reservoir conditions, not separator conditions. Account for all non-hydrocarbon components for accuracy.

Inputs: request (required). Returns: object

gas_water_contentA

Calculate water content of natural gas.

CRITICAL GAS PROCESSING TOOL - Computes the amount of water vapor that natural gas can hold at given pressure and temperature conditions. Essential for hydrate prevention, dehydration unit design, and pipeline operation. Water content decreases with increasing pressure and decreasing temperature.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7.

  • degf (float, required): Temperature in °F. Valid: -460 to 1000. Typical: 40-200°F. Example: 100.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 1000.0 or [500, 1000, 2000].

Water Content Behavior:

  • Decreases with increasing pressure (less water can dissolve)

  • Decreases with decreasing temperature (less water vapor)

  • Typical range: 5-200 lb/MMSCF at pipeline conditions

  • At high pressure/low temperature: <10 lb/MMSCF

Hydrate Formation: Gas-water systems form solid hydrates (ice-like structures) at certain P-T conditions. Hydrates can block pipelines and equipment. Gas must be dehydrated below:

  • Hydrate formation temperature at operating pressure

  • Typical target: <7 lb/MMSCF for pipeline operation

  • Typical target: <0.1 lb/MMSCF for LNG/cryogenic processes

Correlation: Uses McCain correlation (1990) based on experimental data for sweet natural gas. Valid for typical pipeline and processing conditions.

Applications:

  • Hydrate Prevention: Determine minimum dehydration requirement

  • Dehydration Unit Design: Size glycol contactors and regenerators

  • Pipeline Corrosion: Assess water-related corrosion risk

  • Gas Processing: Design dehydration systems for sales gas

  • Sales Gas Specs: Ensure compliance with water content limits

Returns: Dictionary with:

  • value (float or list): Water content in lb/MMSCF (matches input p shape)

  • method (str): "McCain (1990) correlation"

  • units (str): "lb/MMSCF"

  • inputs (dict): Echo of input parameters

  • note (str): Hydrate prevention guidance

Common Mistakes:

  • Using separator temperature instead of pipeline/processing temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not understanding hydrate formation conditions

  • Confusing water content (lb/MMSCF) with water dew point (°F)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 100.0,
    "p": [500, 1000, 2000]
}

Result: Water content decreases from ~50 lb/MMSCF at 500 psia to ~20 lb/MMSCF at 2000 psia.

Note: Water content is critical for pipeline operation. Always check against hydrate formation curve. For hydrate prevention, compare to hydrate formation temperature at operating pressure. Typical pipeline requirement: <7 lb/MMSCF.

Inputs: request (required). Returns: object

gas_z_factorA

Calculate gas compressibility factor (Z-factor).

CRITICAL GAS PVT PROPERTY - The Z-factor corrects the ideal gas law (PV=nRT) for real gas behavior. Z = 1.0 for ideal gas, Z < 1.0 for most real gases at reservoir conditions. Essential for all gas reservoir calculations including material balance, reserve estimation, and flow calculations.

Parameters:

  • sg (float, required): Gas specific gravity (air=1.0). Valid: 0.55-3.0. Typical: 0.6-1.2. Example: 0.7 for dry gas, 0.85 for associated gas.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Typical: 100-400°F. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3500.0 or [1000, 2000, 3000, 4000].

  • h2s (float, optional, default=0.0): H2S mole fraction (0-1). Typical: 0-0.05. Example: 0.02 for 2% H2S. High H2S requires special handling.

  • co2 (float, optional, default=0.0): CO2 mole fraction (0-1). Typical: 0-0.20. Example: 0.05 for 5% CO2.

  • n2 (float, optional, default=0.0): N2 mole fraction (0-1). Typical: 0-0.10. Example: 0.01 for 1% N2.

  • method (str, optional, default="DAK"): Correlation method. Options: "DAK", "HY", "WYW", "BUR". DAK recommended.

Z-Factor Behavior:

  • Low pressure: Z ≈ 1.0 (ideal gas behavior)

  • Medium pressure: Z < 1.0 (attractive forces dominate)

  • High pressure: Z > 1.0 (repulsive forces dominate)

  • Typical range: 0.7-1.2 for reservoir conditions

Method Selection:

  • DAK (Dranchuk & Abou-Kassem 1975): RECOMMENDED. Most accurate, widely validated. Use for: All applications, high accuracy requirements.

  • HY (Hall & Yarborough 1973): Classic method, fast. Use for: Quick estimates, compatibility with older methods.

  • WYW (Wang, Ye & Wu 2021): Newer correlation. Use for: Comparison studies, modern applications.

  • BUR (Burrows 1981): Alternative method. Use for: Specific regional correlations.

Non-Hydrocarbon Effects:

  • H2S and CO2 increase Z-factor (reduce compressibility)

  • N2 has minimal effect

  • For sour gas (H2S > 5%), use Wichert-Aziz correction (not included here)

Returns: Dictionary with:

  • value (float or list): Z-factor (dimensionless, matches input p shape)

  • method (str): Method used

  • units (str): "dimensionless"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not accounting for non-hydrocarbon fractions (H2S, CO2, N2)

  • Using wrong gas gravity (must be separator gas gravity, not sales gas)

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "sg": 0.7,
    "degf": 180.0,
    "p": [1000, 2000, 3000, 4000],
    "h2s": 0.0,
    "co2": 0.05,
    "n2": 0.01,
    "method": "DAK"
}

Result: Z decreases from ~0.95 at 1000 psia to ~0.85 at 3000 psia, then increases to ~0.90 at 4000 psia (typical behavior).

Note: Z-factor is critical for accurate gas calculations. Always use DAK method unless specific compatibility requirements exist. Account for all non-hydrocarbon components for accurate results.

Inputs: request (required). Returns: object

generate_aquifer_influenceA

Generate Van Everdingen & Hurst aquifer influence functions.

CRITICAL AQUIFER MODELING TOOL - Creates dimensionless aquifer influence functions for AQUTAB keyword in ECLIPSE/Intersect. These functions quantify water influx from surrounding aquifers into hydrocarbon reservoirs.

Parameters:

  • res (float or list, required): Dimensionless aquifer radius (ReD). Must be > 1.0. Can be scalar or list. Typical: 5-100. Example: 10.0. ReD = re/rw where re = aquifer outer radius, rw = reservoir radius.

  • start (float, required): Minimum dimensionless time (tD_min). Must be > 0. Typical: 0.01-1.0. Example: 0.1.

  • end (float, required): Maximum dimensionless time (tD_max). Must be > start. Typical: 10-1000. Example: 100.0.

  • rows (int, required): Number of time points in table. Must be > 0. Typical: 20-100. Example: 50. More rows = smoother curves.

Background: Van Everdingen & Hurst (1949) developed analytical solutions for aquifer influx using diffusivity equation. These functions relate:

  • Dimensionless time (tD) = (k × t) / (φ × μ × ct × rw²)

  • Dimensionless pressure (pD) = aquifer response function

  • Dimensionless radius (ReD) = aquifer geometry

Influence Function: The influence function pD(tD, ReD) represents the dimensionless pressure response at the reservoir-aquifer boundary. It depends on:

  • Aquifer geometry (radial vs linear, finite vs infinite)

  • Boundary conditions (constant rate vs constant pressure)

  • Aquifer properties (permeability, porosity, compressibility)

Applications:

  • Material Balance: Quantify aquifer support in material balance analysis

  • Pressure Maintenance: Evaluate aquifer pressure support

  • Water Influx: Calculate cumulative water influx over time

  • History Matching: Match production history with aquifer model

  • Production Forecasting: Predict future aquifer influx

Integration Method: Uses numerical integration (Gaussian quadrature) of diffusivity equation with high-resolution integration (M=8) for accuracy. The solution is computed at specified dimensionless time points.

Returns: Dictionary with:

  • dimensionless_time (list): Dimensionless time values (tD)

  • dimensionless_pressures (list): List of pD arrays (one per ReD)

  • rows (int): Number of time points

  • dimensionless_radii (list): ReD values used

  • time_range (dict): Start and end dimensionless times

  • note (str): Usage guidance for ECLIPSE

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • ReD < 1.0 (aquifer radius must be > reservoir radius)

  • tD_max < tD_min (end must be > start)

  • Too few rows (<10) causing poor resolution

  • Wrong dimensionless radius (must match aquifer geometry)

  • Confusing dimensionless time with actual time

  • Not accounting for aquifer compressibility

Example Usage:

{
    "res": 10.0,
    "start": 0.1,
    "end": 100.0,
    "rows": 50
}

Result: Table with 50 time points from tD=0.1 to tD=100.0 for ReD=10.0.

Note: AQUTAB keyword is ready for direct inclusion in ECLIPSE DATA file. The influence functions are dimensionless and must be scaled using reservoir and aquifer properties. For multiple aquifers, generate separate tables for each aquifer with different ReD values.

Inputs: request (required). Returns: object

generate_black_oil_tableA

Generate comprehensive black oil PVT table.

COMPREHENSIVE PVT TABLE GENERATOR - Creates complete black oil PVT table with all properties (Rs, Bo, μo, ρo, Co) at pressures from 14.7 psia to specified maximum. This is the most comprehensive PVT tool, generating complete tables for reservoir simulation input or analysis. Optionally exports ECLIPSE-compatible keywords.

Parameters:

  • pi (float, required): Initial reservoir pressure in psia. Must be > 0. Example: 4000.0. Table starts from 14.7 psia and goes up to pmax.

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 38.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 175.0.

  • sg_g (float, required): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.68.

  • pmax (float, optional, default=0.0): Maximum pressure for table in psia. If 0, auto-calculates as pi × 1.5. Must be > pi. Example: 5000.0.

  • pb (float, optional, default=0.0): Bubble point pressure in psia. If 0, will be calculated. Example: 3900.0.

  • rsb (float, optional, default=0.0): Solution GOR at bubble point in scf/stb. If 0, will be calculated. Example: 2300.0.

  • nrows (int, optional, default=50): Number of table rows. Valid: 1-200. More rows = finer resolution. Typical: 20-100. Example: 50.

  • export (bool, optional, default=False): Export ECLIPSE-compatible files. If True, creates PVTO.INC, PVDO.INC, DENSITY.INC files. Example: False.

  • pb_method (str, optional, default="VALMC"): Bubble point method. Options: "STAN", "VALMC", "VELAR". VALMC recommended.

  • rs_method (str, optional, default="VELAR"): Solution GOR method. Options: "VELAR", "STAN", "VALMC". VELAR recommended.

  • bo_method (str, optional, default="MCAIN"): Oil FVF method. Options: "MCAIN", "STAN". MCAIN recommended.

  • uo_method (str, optional, default="BR"): Oil viscosity method. Only "BR" available.

Generated Properties:

  • Rs: Solution gas-oil ratio (scf/stb) - increases with pressure up to pb

  • Bo: Formation volume factor (rb/stb) - peaks at bubble point

  • μo: Oil viscosity (cP) - minimum at bubble point

  • ρo: Oil density (lb/cuft) - calculated from mass balance

  • Co: Oil compressibility (1/psi) - increases near bubble point

Table Structure: Pressure values are logarithmically spaced from 14.7 psia to pmax, with finer spacing near bubble point for accuracy.

ECLIPSE Export: When export=True, generates:

  • PVTO.INC: Pressure-dependent oil properties (for undersaturated oil)

  • PVDO.INC: Dead oil properties (for heavy oils)

  • DENSITY.INC: Oil density table

Returns: Dictionary with:

  • table (list of dicts): PVT table data, each dict contains pressure and all properties

  • summary (dict): Key values (bubble point, rsb, Bob, μob, etc.)

  • columns (list): Column names in table

  • methods (dict): Methods used for each property

  • export_files (dict, optional): File names if export=True

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Setting pmax too low (should be > pi for complete table)

  • Not providing pb and rsb when known (reduces accuracy)

  • Using wrong correlation methods (use recommended defaults)

  • Too few rows (nrows < 20) causing poor resolution

  • Not understanding table format for simulation input

Example Usage:

{
    "pi": 4000.0,
    "api": 38.0,
    "degf": 175.0,
    "sg_g": 0.68,
    "pmax": 5000.0,
    "pb": 3900.0,
    "rsb": 2300.0,
    "nrows": 50,
    "export": False,
    "pb_method": "VALMC",
    "rs_method": "VELAR",
    "bo_method": "MCAIN",
    "uo_method": "BR"
}

Result: Complete PVT table with 50 rows covering 14.7-5000 psia with all properties.

Note: This is the most comprehensive PVT tool. Use for complete reservoir analysis or simulation input preparation. Always provide pb and rsb when available for best accuracy. For simulation, set export=True to generate ECLIPSE keywords.

Inputs: request (required). Returns: object

generate_layer_distributionA

Generate layered permeability distribution from Lorenz coefficient.

LAYER PROPERTY GENERATION - Creates detailed layer-by-layer permeability and thickness distribution matching specified heterogeneity. Essential for building reservoir simulation models and predicting waterflood performance.

Parameters:

  • lorenz (float, required): Lorenz coefficient (0-1). Must be 0 ≤ L ≤ 1. Typical: 0.2-0.7. Example: 0.6 for moderate heterogeneity.

  • nlay (int, required): Number of layers to generate. Must be > 0. Typical: 5-50. Example: 10 for 10-layer model.

  • k_avg (float, required): Average permeability in mD. Must be > 0. Typical: 10-1000 mD. Example: 100.0 mD.

  • h (float, optional, default=100.0): Total thickness in feet. Must be > 0. Typical: 50-500 ft. Example: 100.0 ft.

Method: Uses Dykstra-Parsons log-normal permeability distribution with correlation to Lorenz coefficient to generate realistic layer properties:

  1. Convert Lorenz to beta parameter

  2. Generate log-normal permeability distribution

  3. Sort layers by permeability (ascending)

  4. Assign equal thickness to each layer

  5. Calculate layer statistics

Output Properties: For each layer:

  • Thickness (ft): Layer thickness (equal for all layers)

  • Permeability (mD): Layer permeability (log-normal distribution)

  • Thickness Fraction: Fraction of total thickness

  • kh Fraction: Fraction of total flow capacity (k × h)

Statistics Calculated:

  • k_min, k_max: Minimum and maximum permeability

  • k_avg, k_median: Average and median permeability

  • k_std: Standard deviation

  • Heterogeneity ratio: k_max / k_min

Critical for:

  • Reservoir Simulation: Generate layer properties for simulation models

  • Waterflood Prediction: Predict sweep efficiency and recovery

  • Vertical Sweep Efficiency: Analyze vertical conformance

  • Conformance Studies: Evaluate production allocation

  • Upscaling: Create coarse-scale models from fine-scale data

  • Sensitivity Analysis: Test impact of heterogeneity on performance

Usage Example: For 10-layer simulation model with Lorenz=0.6:

{
    "lorenz": 0.6,
    "nlay": 10,
    "k_avg": 100.0,
    "h": 100.0
}

Result: 10 layers with permeabilities ranging from ~20 mD (low-k) to ~500 mD (high-k), each with 10 ft thickness. High-k layers have higher kh fractions.

Returns: Dictionary with:

  • layers (list): List of dicts with layer properties (thickness, permeability, fractions)

  • statistics (dict): Permeability statistics (min, max, avg, median, std, ratio)

  • total_thickness_ft (float): Total thickness

  • average_permeability_md (float): Average permeability

  • lorenz_coefficient (float): Input Lorenz coefficient

  • number_of_layers (int): Number of layers

  • method (str): "Dykstra-Parsons log-normal distribution"

  • note (str): Usage guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Lorenz coefficient outside valid range (must be 0-1)

  • Too few layers (<5) causing poor resolution

  • Too many layers (>50) causing unnecessary complexity

  • Wrong average permeability (must match reservoir average)

  • Not understanding that layers are sorted by permeability

  • Confusing thickness fraction with absolute thickness

Example Usage:

{
    "lorenz": 0.6,
    "nlay": 10,
    "k_avg": 100.0,
    "h": 100.0
}

Result: 10 layers with log-normal permeability distribution, each 10 ft thick. Permeability ranges from ~20 mD to ~500 mD, matching Lorenz=0.6 heterogeneity.

Note: This generates idealized layer properties assuming log-normal permeability distribution and equal layer thickness. For actual reservoirs, use measured core or log data when available. Layer properties are ready for direct use in reservoir simulation models.

Inputs: request (required). Returns: object

generate_rel_perm_tableA

Generate relative permeability table for reservoir simulation.

CRITICAL SIMULATION TOOL - Creates saturation-dependent relative permeability curves for ECLIPSE, Intersect, CMG, or other simulators. Relative permeability is essential for multiphase flow simulation and determines fluid mobility.

Parameters:

  • rows (int, required): Number of saturation points in table. Must be > 0. Typical: 20-50. Example: 25. More rows = smoother curves but larger files.

  • krtable (str, required): Table type. Options: "SWOF", "SGOF", "SGWFN". Example: "SWOF" for water-oil systems.

  • krfamily (str, required): Correlation family. Options: "COR" (Corey), "LET". Example: "COR" for simple power-law, "LET" for flexible fitting.

  • kromax (float, required): Maximum oil relative permeability (0-1). Typical: 0.5-1.0. Example: 1.0.

  • swc (float, required): Connate water saturation (0-1). Must be < 1. Typical: 0.1-0.3. Example: 0.15.

  • krwmax (float, optional): Maximum water rel perm for SWOF (0-1). Typical: 0.1-0.5. Example: 0.25.

  • krgmax (float, optional): Maximum gas rel perm for SGOF/SGWFN (0-1). Typical: 0.5-1.0. Example: 1.0.

  • sorw (float, optional): Residual oil saturation to water (0-1). Typical: 0.1-0.3. Example: 0.15.

  • sorg (float, optional): Residual oil saturation to gas (0-1). Typical: 0.05-0.2. Example: 0.1.

  • sgc (float, optional): Critical gas saturation (0-1). Typical: 0.05-0.15. Example: 0.1.

  • swcr (float, optional): Critical water saturation for Corey (0-1). Typical: 0.15-0.25. Example: 0.2.

  • no (float, optional): Corey exponent for oil (Corey only). Must be > 0. Typical: 2.0-4.0. Example: 2.5. Higher = more curved.

  • nw (float, optional): Corey exponent for water (Corey only). Must be > 0. Typical: 1.5-3.0. Example: 1.5.

  • ng (float, optional): Corey exponent for gas (Corey only). Must be > 0. Typical: 2.0-3.5. Example: 2.0.

  • Lo, Eo, To (float, optional): LET parameters for oil (LET only). Typical: Lo=1-3, Eo=1-2, To=1-3. Example: Lo=2.5, Eo=1.25, To=1.75.

  • Lw, Ew, Tw (float, optional): LET parameters for water (LET only). Typical: Lw=1-3, Ew=1-2, Tw=1-3. Example: Lw=1.5, Ew=1.0, Tw=2.0.

  • Lg, Eg, Tg (float, optional): LET parameters for gas (LET only). Typical: Lg=1-3, Eg=1-2, Tg=1-3. Example: Lg=1.2, Eg=1.5, Tg=2.0.

Correlation Families:

  • Corey (1954): Simple power-law model, fast, widely used. Formula: Kr = krmax * ((S - Sc) / (1 - Swc - Sor))^n Use for: Quick estimates, standard cases, compatibility.

  • LET (2005): Flexible 3-parameter model, better curve fitting. Formula: Kr = krmax * (S^L) / (S^L + E * (1-S)^T) Use for: History matching, complex curves, accuracy.

Table Types:

  • SWOF: Water-Oil (waterflood, aquifer influx). Columns: Sw, Krw, Kro, Pcow.

  • SGOF: Gas-Oil (gas cap expansion, gas injection). Columns: Sg, Krg, Krog, Pcog.

  • SGWFN: Three-phase gas-water (gas cycling, WAG). Columns: Sg, Krg, Krw, Pcog, Pcow.

Saturation Endpoints:

  • Swc: Connate water (immobile water)

  • Sorw: Residual oil to water (trapped oil after waterflood)

  • Sorg: Residual oil to gas (trapped oil after gas injection)

  • Sgc: Critical gas (minimum gas saturation for flow)

Workflow:

  1. Choose correlation family (Corey or LET)

  2. Select table type (SWOF, SGOF, SGWFN)

  3. Specify saturation endpoints (Swc, Sor, Sgc)

  4. Set maximum rel perms (kromax, krwmax, krgmax)

  5. Define correlation parameters (Corey exponents or LET params)

  6. Generate table with specified number of rows

Returns: Dictionary with:

  • table (list): List of dicts with saturation and rel perm values

  • columns (list): Column names (e.g., ["Sw", "Krw", "Kro", "Pcow"])

  • rows (int): Number of rows in table

  • table_type (str): Table type (SWOF, SGOF, SGWFN)

  • correlation (str): Correlation family (COR, LET)

  • note (str): Usage guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Saturation endpoints don't sum correctly (Swc + Sor < 1.0)

  • Using wrong table type for simulation (check simulator requirements)

  • Corey exponents too high (>5) causing unrealistic curves

  • Not specifying required parameters for chosen table type

  • Too few rows (<10) causing poor curve resolution

  • Maximum rel perms > 1.0 (must be dimensionless 0-1)

Example Usage (Corey SWOF):

{
    "rows": 25,
    "krtable": "SWOF",
    "krfamily": "COR",
    "kromax": 1.0,
    "krwmax": 0.25,
    "swc": 0.15,
    "swcr": 0.2,
    "sorw": 0.15,
    "no": 2.5,
    "nw": 1.5
}

Example Usage (LET SGOF):

{
    "rows": 25,
    "krtable": "SGOF",
    "krfamily": "LET",
    "kromax": 1.0,
    "krgmax": 1.0,
    "swc": 0.2,
    "sorg": 0.15,
    "sgc": 0.1,
    "Lo": 2.5,
    "Eo": 1.25,
    "To": 1.75,
    "Lg": 1.2,
    "Eg": 1.5,
    "Tg": 2.0
}

Note: Relative permeability tables are critical for accurate simulation. Always validate endpoints against core data or literature. Use LET for history matching when Corey doesn't fit data well. Table format is ECLIPSE-compatible and ready for direct inclusion in simulation decks.

Inputs: request (required). Returns: object

get_component_propertiesA

Get critical properties for hydrocarbon components from database.

COMPONENT DATABASE - Access to comprehensive database of critical properties for standard hydrocarbon components and common non-hydrocarbons. Essential for compositional analysis, EOS calculations, and phase behavior modeling.

Parameters:

  • component (str, required): Component name. Case-insensitive. Examples: "methane", "C1", "ethane", "C2", "propane", "C3", "n-butane", "nC4", "i-butane", "iC4", "benzene", "toluene", "N2", "CO2", "H2S", "H2O".

  • eos (str, optional, default="PR79"): Equation of State model. Options: "PR79", "PR77", "SRK", "RK". PR79 recommended.

Available Components:

  • Light Ends: Methane (C1), Ethane (C2), Propane (C3), Butane (C4), Pentane (C5)

  • Normal Paraffins: n-C4 through n-C45 (n-butane to n-pentatetracontane)

  • Branched Alkanes: iC4 (isobutane), iC5 (isopentane), neoC5 (neopentane)

  • Aromatics: Benzene (C6H6), Toluene (C7H8), Xylenes (C8H10)

  • Naphthenes: Cyclopentane, Cyclohexane

  • Non-Hydrocarbons: N2 (nitrogen), CO2 (carbon dioxide), H2S (hydrogen sulfide), H2O (water)

Properties Returned:

  • MW: Molecular weight in lb/lbmol. Example: 16.04 for methane.

  • Tc: Critical temperature in °R. Example: 343.0 for methane.

  • Pc: Critical pressure in psia. Example: 667.8 for methane.

  • Zc: Critical compressibility factor (dimensionless). Example: 0.286 for methane.

  • Omega: Acentric factor ω (dimensionless). Example: 0.011 for methane.

  • Vcritical: Critical volume in cuft/lbmol. Example: 1.59 for methane.

  • Tb: Normal boiling point in °R. Example: 201.6 for methane.

  • SG: Specific gravity (dimensionless, relative to water). Example: 0.554 for methane.

EOS Models:

  • PR79 (Peng-Robinson 1979): RECOMMENDED. Most widely used, best accuracy. Use for: Most applications, hydrocarbon systems, gas processing.

  • PR77 (Peng-Robinson 1977): Original version. Use for: Compatibility, older models.

  • SRK (Soave-Redlich-Kwong 1972): Alternative EOS. Use for: Specific applications, comparison.

  • RK (Redlich-Kwong 1949): Older EOS. Use for: Historical compatibility, simple systems.

Critical Properties Usage: Critical properties are essential for:

  • EOS phase behavior calculations (PR, SRK, RK)

  • Flash calculations (bubble point, dew point)

  • Phase envelope generation

  • Compressibility factor calculations

  • Vapor-liquid equilibrium

Applications:

  • Compositional Simulation: Input component properties for compositional models

  • EOS Phase Behavior: Calculate phase envelopes and phase boundaries

  • Flash Calculations: Solve vapor-liquid equilibrium problems

  • PVT Modeling: Build compositional PVT models

  • Gas Processing Design: Design separation and processing facilities

  • Material Balance: Compositional material balance calculations

Source: Industry-standard component database with properties from:

  • NIST (National Institute of Standards and Technology)

  • API (American Petroleum Institute) data

  • EOS calibrations and literature values

Returns: Dictionary with:

  • component (str): Component name

  • eos_model (str): EOS model used

  • properties (dict): All critical properties (MW, Tc, Pc, Zc, Omega, Vcritical, Tb, SG)

  • method (str): "Component database lookup"

  • note (str): Usage guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Component name misspelled (check spelling, try common aliases like "C1" for methane)

  • Wrong EOS model (use PR79 unless specific requirement)

  • Case sensitivity (component names are case-insensitive, but use standard capitalization)

  • Component not in database (check available components list)

  • Using properties from wrong EOS (properties are EOS-specific)

Example Usage:

{
    "component": "methane",
    "eos": "PR79"
}

Result: Returns all critical properties for methane calibrated for PR79 EOS.

Note: Component properties are EOS-specific. Always use properties from the same EOS model throughout your calculations. PR79 is recommended for most applications. For components not in database, use external sources or estimate from correlations.

Inputs: request (required). Returns: object

lorenz_from_flow_fractionsA

Calculate Lorenz coefficient from flow and permeability fractions.

LORENZ FROM PRODUCTION DATA - Computes Lorenz coefficient from layer-by-layer flow and permeability data. Essential for analyzing actual production data and quantifying vertical conformance from measured production allocation.

Parameters:

  • flow_frac (list, required): Flow fractions from each layer (0-1). Must sum to 1.0. Length must match perm_frac. Example: [0.1, 0.2, 0.3, 0.4].

  • perm_frac (list, required): Permeability-thickness fractions (kh fractions) for each layer (0-1). Must sum to 1.0. Length must match flow_frac. Example: [0.05, 0.15, 0.25, 0.55].

Input Data Sources:

  • PLT (Production Logging Tool): Flow rate per layer from production logs

  • Tracer Tests: Flow allocation from tracer response

  • Production Allocation: Flow rates from well test analysis

  • Core Data: Permeability and thickness from core analysis

  • Log Data: Permeability from well logs, thickness from formation tops

Lorenz Coefficient Calculation: Constructs Lorenz curve from data:

  1. Sort layers by kh fraction (ascending)

  2. Calculate cumulative kh fraction (x-axis)

  3. Calculate cumulative flow fraction (y-axis)

  4. Calculate area between curve and diagonal (45° line)

  5. L = 2 × area (normalized to 0-1)

Interpretation:

  • L < 0.3: High conformance (flow matches capacity)

  • L = 0.3-0.6: Moderate conformance (some flow imbalance)

  • L ≥ 0.6: Poor conformance (severe flow imbalance)

Applications:

  • Production Allocation Analysis: Quantify vertical conformance from PLT data

  • PLT Interpretation: Convert PLT flow rates to heterogeneity measure

  • Tracer Test Analysis: Evaluate sweep efficiency from tracer response

  • Vertical Conformance Evaluation: Assess waterflood performance

  • History Matching: Match simulation to measured production allocation

  • Performance Diagnosis: Identify layers with poor conformance

Returns: Dictionary with:

  • lorenz_coefficient (float): Lorenz coefficient (0-1)

  • number_of_layers (int): Number of layers analyzed

  • method (str): "Lorenz from flow and permeability fractions"

  • interpretation (str): Conformance level guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Flow fractions don't sum to 1.0 (must normalize)

  • Perm fractions don't sum to 1.0 (must normalize)

  • Length mismatch between flow_frac and perm_frac

  • Using weight fractions instead of flow fractions

  • Not sorting layers correctly (must sort by kh)

  • Using wrong kh calculation (must be k × h, not just k)

Example Usage:

{
    "flow_frac": [0.1, 0.2, 0.3, 0.4],
    "perm_frac": [0.05, 0.15, 0.25, 0.55]
}

Result: L ≈ 0.4-0.5 (moderate conformance - high-k layers produce more than their capacity fraction, low-k layers produce less).

Note: This is the most direct way to calculate Lorenz from actual production data. Always ensure fractions sum to 1.0 and layers are correctly matched. High L indicates poor vertical conformance (flow imbalance).

Inputs: request (required). Returns: object

lorenz_to_betaA

Convert Lorenz coefficient to Dykstra-Parsons beta parameter.

HETEROGENEITY QUANTIFICATION - Converts between two common measures of reservoir heterogeneity. Essential for comparing reservoirs using different heterogeneity metrics and for literature data conversion.

Parameters:

  • value (float, required): Lorenz coefficient (0-1). Must be 0 ≤ L ≤ 1. Typical: 0.2-0.7. Example: 0.5 for moderate heterogeneity.

Lorenz Coefficient (L):

  • Ranges from 0 (homogeneous) to 1 (completely heterogeneous)

  • Based on cumulative flow capacity vs cumulative storage capacity

  • Geometric interpretation: area between Lorenz curve and 45° line

  • L = 2 × area between curve and diagonal

  • Directly measurable from production data (PLT, tracer tests)

Dykstra-Parsons Beta (β):

  • Permeability variation coefficient (dimensionless, 0-1)

  • β = (k50 - k84.1) / k50

  • Based on log-normal permeability distribution

  • Requires permeability data (core, logs)

  • Common in literature and older studies

Conversion Relationship: Beta and Lorenz are related through log-normal distribution statistics. Higher Lorenz = higher Beta (both indicate more heterogeneity).

Typical Ranges:

  • L < 0.3 (homogeneous): β < 0.5

  • L = 0.3-0.6 (moderate): β = 0.5-0.7

  • L > 0.6 (heterogeneous): β > 0.7

Applications:

  • Waterflood Sweep Efficiency: Predict vertical sweep from heterogeneity

  • Vertical Conformance Analysis: Evaluate production allocation

  • Reservoir Characterization: Compare reservoirs using different metrics

  • Performance Prediction: Use beta in Dykstra-Parsons calculations

  • Literature Conversion: Convert published beta values to Lorenz

Returns: Dictionary with:

  • beta (float): Dykstra-Parsons beta coefficient (0-1)

  • lorenz_coefficient (float): Input Lorenz coefficient

  • method (str): "Lorenz to Dykstra-Parsons conversion"

  • interpretation (dict): Heterogeneity level guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Lorenz coefficient outside valid range (must be 0-1)

  • Confusing Lorenz with other heterogeneity measures

  • Using beta from wrong distribution (must be log-normal)

  • Not understanding that conversion is approximate (depends on distribution)

Example Usage:

{
    "value": 0.5
}

Result: β ≈ 0.6-0.7 (moderate to high heterogeneity).

Note: Conversion assumes log-normal permeability distribution. For non-log-normal distributions, conversion may be less accurate. Always validate against actual permeability data when possible.

Inputs: request (required). Returns: object

oil_api_from_sgA

Convert oil specific gravity to API gravity.

UNIT CONVERSION TOOL - Converts oil specific gravity (dimensionless, water=1.0) to API gravity (degrees). API gravity is an inverse measure of density - higher API means lighter oil. Essential for standardizing oil property reporting.

Parameters:

  • sg (float or list, required): Oil specific gravity (water=1.0). Valid range: 0.1-1.5. Typical: 0.8-1.0. Example: 0.85 or [0.80, 0.85, 0.90]. Can be scalar or array.

Conversion Formula: API = (141.5 / SG) - 131.5

API Gravity Ranges:

  • Heavy oil: API < 22° (SG > 0.922)

  • Medium oil: API 22-35° (SG 0.922-0.850)

  • Light oil: API > 35° (SG < 0.850)

  • Water: API = 10° (SG = 1.0)

Returns: Dictionary with:

  • value (float or list): API gravity in degrees (matches input sg shape)

  • method (str): "Standard conversion"

  • units (str): "degrees API"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using gas specific gravity instead of oil specific gravity

  • Confusing API gravity with specific gravity (inverse relationship)

  • Using density (lb/cuft) instead of specific gravity

  • Not understanding that higher API = lighter oil

Example Usage:

{
    "sg": 0.85
}

Result: API = (141.5 / 0.85) - 131.5 ≈ 35.0° (medium gravity oil)

Note: API gravity is the industry standard for oil classification. Use this conversion when you have specific gravity but need API gravity for correlations or reporting.

Inputs: request (required). Returns: object

oil_bubble_pointA

Calculate oil bubble point pressure (Pb).

CRITICAL PVT PROPERTY - The bubble point is the pressure at which gas first begins to evolve from solution in oil. Essential for all oil reservoir calculations.

Parameters:

  • api (float, required): Oil API gravity in degrees. Valid range: 0-100. Typical values: 20-50. Example: 35.0 for medium gravity crude.

  • degf (float, required): Reservoir temperature in degrees Fahrenheit. Valid range: -460 to 1000. Typical: 100-300°F. Example: 180.0.

  • rsb (float, required): Solution gas-oil ratio at bubble point in scf/stb. Must be ≥ 0. Typical: 100-3000 scf/stb. Example: 800.0.

  • sg_g (float, optional, default=0.0): Gas specific gravity (air=1.0). Valid range: 0-3. Typical: 0.6-1.2. Example: 0.75 for associated gas.

  • method (str, optional, default="VALMC"): Correlation method. Options: "STAN", "VALMC", "VELAR". VALMC recommended for wider applicability.

Method Selection:

  • VALMC (Valko-McCain 2003): Recommended. Best for wide range of conditions. Use for: Most applications, high GOR oils, wide temperature ranges.

  • STAN (Standing 1947): Classic correlation. Use for: Standard conditions, quick estimates, compatibility with older methods.

  • VELAR (Velarde 1997): Alternative method. Use for: Specific regional correlations, comparison studies.

Returns: Dictionary with:

  • value (float): Bubble point pressure in psia

  • method (str): Method used

  • units (str): "psia"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Confusing rsb (solution GOR at bubble point) with separator GOR

  • Using gas gravity from wrong separator stage

  • Temperature in Celsius instead of Fahrenheit

Example Usage:

{
    "api": 35.0,
    "degf": 180.0,
    "rsb": 800.0,
    "sg_g": 0.75,
    "method": "VALMC"
}

Expected result: Pb ≈ 3000-4000 psia for typical oil.

Note: If Pb > reservoir pressure, reservoir is undersaturated (no free gas). If Pb < reservoir pressure, reservoir is saturated (gas cap present).

Inputs: request (required). Returns: object

oil_compressibilityA

Calculate oil compressibility (Co).

CRITICAL PVT PROPERTY - Computes oil compressibility coefficient, which measures how much oil volume changes with pressure. Essential for material balance calculations, pressure transient analysis, and reserve estimation. Co is typically 5-50 × 10⁻⁶ 1/psi.

Parameters:

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0 or [2000, 3000, 4000].

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • pb (float, required): Bubble point pressure in psia. Must be ≥ 0. Example: 3500.0.

  • sg_g (float, required): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • rs (float or list, optional, default=0.0): Solution GOR at pressure p in scf/stb. If 0, will be calculated. Must match p shape. Example: 600.0.

  • rsb (float, optional, default=0.0): Solution GOR at bubble point in scf/stb. Required if pb provided. Example: 800.0.

Compressibility Behavior:

  • p < pb: Co is relatively constant (oil + dissolved gas compressibility)

  • p = pb: Co increases sharply (gas evolution begins)

  • p > pb: Co decreases with pressure (gas compressibility dominates)

Typical Ranges:

  • Undersaturated oil: 5-20 × 10⁻⁶ 1/psi

  • At bubble point: 20-50 × 10⁻⁶ 1/psi

  • Above bubble point: 10-30 × 10⁻⁶ 1/psi

Returns: Dictionary with:

  • value (float or list): Compressibility in 1/psi (matches input p shape)

  • method (str): "McCain"

  • units (str): "1/psi"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Not providing pb (required for accurate calculation)

  • Using wrong pressure (must be reservoir pressure, not separator)

  • Confusing oil compressibility with gas compressibility

  • Not accounting for dissolved gas effects

Example Usage:

{
    "p": [2000, 3000, 4000],
    "api": 35.0,
    "degf": 180.0,
    "pb": 3500.0,
    "sg_g": 0.75,
    "rs": [400, 600, 800],
    "rsb": 800.0
}

Result: Co ≈ 10-15 × 10⁻⁶ 1/psi below bubble point, increases near pb.

Note: Compressibility is critical for material balance calculations. Always provide pb for accurate results. Co values are small (micro-1/psi), so results are typically in scientific notation.

Inputs: request (required). Returns: object

oil_densityA

Calculate oil density (ρo) at reservoir conditions.

CRITICAL PVT PROPERTY - Computes oil density from PVT properties using mass balance approach. Essential for gradient calculations, well pressure analysis, and material balance calculations.

Parameters:

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0.

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • rs (float or list, required): Solution GOR at pressure p in scf/stb. Must match p shape. Example: 600.0 or [400, 600, 800].

  • sg_g (float, required): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • bo (float or list, required): Oil formation volume factor at pressure p in rb/stb. Must match p shape. Calculate using oil_formation_volume_factor tool first. Example: 1.25 or [1.15, 1.25, 1.30].

Calculation Method: Density = (Stock tank oil mass + Dissolved gas mass) / Reservoir volume ρo = (sg_o × 62.372 + 0.01357 × Rs × sg_g) / Bo

Where:

  • sg_o = oil specific gravity (calculated from API)

  • 62.372 = water density at standard conditions (lb/cuft)

  • 0.01357 = gas density conversion factor

Typical Ranges:

  • Light oils: 40-50 lb/cuft

  • Medium oils: 50-55 lb/cuft

  • Heavy oils: 55-65 lb/cuft

Returns: Dictionary with:

  • value (float or list): Density in lb/cuft (matches input p shape)

  • method (str): "Standard"

  • units (str): "lb/cuft"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using stock tank density instead of reservoir density

  • Not providing matching rs and bo arrays

  • Using wrong bo value (must be at same pressure as p)

  • Confusing density (mass/volume) with specific gravity (dimensionless)

Example Usage:

{
    "p": 3000.0,
    "api": 35.0,
    "degf": 180.0,
    "rs": 600.0,
    "sg_g": 0.75,
    "bo": 1.25
}

Result: Density ≈ 48-52 lb/cuft for typical medium gravity oil.

Note: Always calculate Bo first using oil_formation_volume_factor tool, then use matching rs and bo values for accurate density calculation.

Inputs: request (required). Returns: object

oil_formation_volume_factorA

Calculate oil formation volume factor (Bo).

CRITICAL PVT PROPERTY - Computes ratio of oil volume at reservoir conditions to volume at standard conditions. Bo > 1.0 because oil expands due to dissolved gas and thermal expansion. Essential for material balance, reserve calculations, and production forecasting.

Parameters:

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0 or [2000, 3000, 4000].

  • sg_g (float, optional, default=0.0): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • pb (float, optional, default=0.0): Bubble point pressure in psia. Required for accurate calculation. Example: 3500.0.

  • rs (float or list, optional, default=0.0): Solution GOR at pressure p in scf/stb. If 0, will be calculated from p. Must match p shape. Example: 600.0 or [400, 600, 800].

  • rsb (float, optional, default=0.0): Solution GOR at bubble point in scf/stb. Required if pb provided. Example: 800.0.

  • method (str, optional, default="MCAIN"): Correlation method. Options: "MCAIN", "STAN". MCAIN recommended.

Pressure Behavior:

  • p < pb: Bo increases with pressure (more gas dissolves)

  • p = pb: Bo reaches maximum (Bob, typically 1.2-2.0 rb/stb)

  • p > pb: Bo decreases with pressure (oil compressibility dominates)

Method Selection:

  • MCAIN (McCain et al. 1988): Recommended. More accurate, wider range.

  • STAN (Standing 1947): Classic method. Use for compatibility.

Returns: Dictionary with:

  • value (float or list): Bo in rb/stb (matches input p shape)

  • method (str): Method used

  • units (str): "rb/stb"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Not providing rs when p < pb (will calculate incorrectly)

  • Using separator GOR instead of solution GOR at reservoir pressure

  • Pressure in barg/psig instead of psia

  • Confusing Bo (reservoir volume) with Bg (gas FVF)

Example Usage:

{
    "api": 35.0,
    "degf": 180.0,
    "p": [2000, 3000, 4000],
    "sg_g": 0.75,
    "pb": 3500.0,
    "rs": [400, 600, 800],
    "rsb": 800.0,
    "method": "MCAIN"
}

Result: Bo increases from ~1.15 rb/stb at 2000 psia to ~1.35 rb/stb at 3500 psia, then decreases to ~1.33 rb/stb at 4000 psia (above bubble point).

Note: Always provide rs for pressures below bubble point. If rs=0, tool will calculate it, but providing it explicitly improves accuracy.

Inputs: request (required). Returns: object

oil_rate_linearA

Calculate oil production rate for linear flow.

INFLOW PERFORMANCE TOOL - Computes oil production rate for horizontal wells or wells with linear flow geometry using Darcy's law. Automatically calculates PVT properties (Rs, Bo, μo) at average pressure. Essential for horizontal well performance analysis and completion design.

Parameters:

  • pi (float, required): Initial/reservoir pressure in psia. Must be > 0. Example: 4000.0.

  • pb (float, required): Bubble point pressure in psia. Must be ≥ 0. Example: 3500.0. If pi < pb, reservoir is saturated (gas cap present).

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • sg_g (float, required): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • psd (float or list, required): Sandface/draining pressure(s) in psia. Must be > 0 and < pi. Can be scalar or array. Example: 1500.0 or [1000, 1500, 2000].

  • h (float, required): Net pay thickness in feet. Must be > 0. Typical: 10-200 ft. Example: 50.0.

  • k (float, required): Permeability in millidarcies (mD). Must be > 0. Typical: 1-1000 mD. Example: 100.0.

  • area (float, required): Cross-sectional flow area in square feet. Must be > 0. Typical: 100-10000 ft². Example: 1000.0.

  • length (float, required): Flow length in feet. Must be > 0. Typical: 100-5000 ft. Example: 500.0.

  • rsb (float, required): Solution GOR at bubble point in scf/stb. Must be ≥ 0. Example: 800.0.

Flow Geometry: Linear flow occurs in:

  • Horizontal wells (early-time flow)

  • Hydraulically fractured vertical wells (fracture flow)

  • Channelized reservoirs

  • Edge water drive systems

Darcy's Law Formula (Linear): qo = (0.001127 × k × area × (pi - pwf)) / (μo × Bo × length)

Where PVT properties (μo, Bo) are calculated at average pressure (pi + pwf)/2.

Linear vs Radial Flow:

  • Linear: Flow perpendicular to wellbore (horizontal wells)

  • Radial: Flow converging to wellbore (vertical wells)

  • Linear flow typically has higher productivity than radial

Returns: Dictionary with:

  • value (float or list): Oil rate in STB/day (matches input psd shape)

  • method (str): "Darcy linear flow"

  • units (str): "STB/day"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Confusing flow area (perpendicular to flow) with wellbore area

  • Using wrong flow length (should be distance from boundary to well)

  • Not accounting for net pay thickness correctly

  • Confusing linear flow (horizontal wells) with radial flow (vertical wells)

Example Usage:

{
    "pi": 4000.0,
    "pb": 3500.0,
    "api": 35.0,
    "degf": 180.0,
    "sg_g": 0.75,
    "psd": [1500, 2000, 2500],
    "h": 50.0,
    "k": 100.0,
    "area": 1000.0,
    "length": 500.0,
    "rsb": 800.0
}

Result: Oil rate decreases as sandface pressure increases (typical IPR curve).

Note: This tool automatically calculates PVT properties. You don't need to provide Rs, Bo, or μo - they are computed internally at average pressure. Linear flow is characteristic of horizontal wells and hydraulically fractured wells.

Inputs: request (required). Returns: object

oil_rate_radialA

Calculate oil production rate for radial flow (vertical well).

INFLOW PERFORMANCE TOOL - Computes oil production rate for vertical wells with radial flow geometry using Darcy's law. Automatically calculates PVT properties (Rs, Bo, μo) at average pressure. Optionally applies Vogel IPR model for two-phase flow below bubble point.

Parameters:

  • pi (float, required): Initial/reservoir pressure in psia. Must be > 0. Example: 4000.0.

  • pb (float, required): Bubble point pressure in psia. Must be ≥ 0. Example: 3500.0. If pi < pb, reservoir is saturated (gas cap present).

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • sg_g (float, required): Gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • psd (float or list, required): Sandface/draining pressure(s) in psia. Must be > 0 and < pi. Can be scalar or array. Example: 1500.0 or [1000, 1500, 2000].

  • h (float, required): Net pay thickness in feet. Must be > 0. Typical: 10-200 ft. Example: 50.0.

  • k (float, required): Permeability in millidarcies (mD). Must be > 0. Typical: 1-1000 mD. Example: 100.0.

  • s (float, optional, default=0.0): Skin factor (dimensionless). Negative = stimulation, positive = damage. Typical: -5 to +20. Example: 0.0 for undamaged well.

  • re (float, required): Drainage radius in feet. Must be > rw. Typical: 500-5000 ft. Example: 1000.0.

  • rw (float, required): Wellbore radius in feet. Must be > 0. Typical: 0.25-0.5 ft. Example: 0.5.

  • rsb (float, required): Solution GOR at bubble point in scf/stb. Must be ≥ 0. Example: 800.0.

  • vogel (bool, optional, default=False): Apply Vogel IPR model. Set True when pi < pb (saturated reservoir). Example: False.

Flow Regime:

  • Undersaturated (pi > pb): Single-phase oil flow, Darcy's law applies

  • Saturated (pi < pb): Two-phase flow, use Vogel=True for accurate IPR

Darcy's Law Formula: qo = (0.00708 × k × h × (pi - pwf)) / (μo × Bo × (ln(re/rw) + S))

Where PVT properties (μo, Bo) are calculated at average pressure (pi + pwf)/2.

Returns: Dictionary with:

  • value (float or list): Oil rate in STB/day (matches input psd shape)

  • method (str): "Darcy radial flow" or "Vogel IPR"

  • units (str): "STB/day"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator temperature instead of reservoir temperature

  • Pressure in barg/psig instead of psia (must be absolute)

  • Not setting vogel=True when pi < pb (underestimates rate)

  • Using wrong drainage radius (re) - should be well spacing/2

  • Confusing net pay (h) with gross thickness

  • Not accounting for skin factor (s)

Example Usage:

{
    "pi": 4000.0,
    "pb": 3500.0,
    "api": 35.0,
    "degf": 180.0,
    "sg_g": 0.75,
    "psd": [1500, 2000, 2500],
    "h": 50.0,
    "k": 100.0,
    "s": 0.0,
    "re": 1000.0,
    "rw": 0.5,
    "rsb": 800.0,
    "vogel": False
}

Result: Oil rate decreases as sandface pressure increases (typical IPR curve).

Note: This tool automatically calculates PVT properties. You don't need to provide Rs, Bo, or μo - they are computed internally at average pressure. For saturated reservoirs (pi < pb), set vogel=True for accurate two-phase flow.

Inputs: request (required). Returns: object

oil_rs_at_bubble_pointA

Calculate solution GOR at bubble point using Standing correlation.

Computes Rs specifically at the bubble point pressure based on reservoir fluid properties. Uses Standing (1947) correlation.

This is useful when you know the bubble point pressure and need to calculate the corresponding solution GOR.

Returns Rs in scf/stb.

Args: request: Bubble point parameters (API, temperature, bubble point, gas gravity)

Returns: Dictionary with Rs at bubble point, method, units, and inputs

Inputs: request (required). Returns: object

oil_sg_from_apiA

Convert API gravity to oil specific gravity.

UNIT CONVERSION TOOL - Converts API gravity (degrees) to specific gravity (dimensionless, water=1.0). Specific gravity is the ratio of oil density to water density at standard conditions. Essential for calculations requiring specific gravity.

Parameters:

  • api (float or list, required): Oil API gravity in degrees. Valid range: 0-100. Typical: 20-50. Example: 35.0 or [30, 35, 40]. Can be scalar or array.

Conversion Formula: SG = 141.5 / (API + 131.5)

Specific Gravity Ranges:

  • Heavy oil: SG > 0.922 (API < 22°)

  • Medium oil: SG 0.850-0.922 (API 22-35°)

  • Light oil: SG < 0.850 (API > 35°)

  • Water: SG = 1.0 (API = 10°)

Returns: Dictionary with:

  • value (float or list): Specific gravity (dimensionless, matches input api shape)

  • method (str): "Standard conversion"

  • units (str): "dimensionless (water=1)"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using gas API gravity instead of oil API gravity

  • Confusing API gravity with specific gravity (inverse relationship)

  • Not understanding that lower SG = lighter oil (higher API)

  • Using wrong conversion formula

Example Usage:

{
    "api": 35.0
}

Result: SG = 141.5 / (35.0 + 131.5) ≈ 0.850 (medium gravity oil)

Note: Most PVT correlations use API gravity directly, but some require specific gravity. Use this conversion when needed. Remember: API and SG are inversely related - higher API means lower SG (lighter oil).

Inputs: request (required). Returns: object

oil_sg_from_jacobyA

Calculate oil specific gravity from molecular weight and Jacoby aromaticity.

HYDROCARBON CHARACTERIZATION TOOL - Estimates specific gravity for undefined petroleum fractions using molecular weight and aromaticity.

Jacoby Aromaticity Factor (JA):

  • 0.0 = Pure paraffinic (alkanes)

  • 0.5 = Mixed (typical crude oils)

  • 1.0 = Pure aromatic

Applications:

  • Plus fraction (C7+) characterization

  • Undefined heavy end lumping

  • EOS fluid modeling

  • Pseudo-component generation

Returns specific gravity (dimensionless, water=1).

Args: request: Molecular weight and Jacoby aromaticity factor

Returns: Dictionary with specific gravity, method, and inputs

Inputs: request (required). Returns: object

oil_solution_gorA

Calculate solution gas-oil ratio (Rs) at specified pressure.

CRITICAL PVT PROPERTY - Computes volume of gas dissolved in oil at given pressure and temperature. Rs increases with pressure up to bubble point, then remains constant (equal to rsb) above bubble point.

Parameters:

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0 or [2000, 3000, 4000].

  • sg_g (float, optional, default=0.0): Separator gas specific gravity (air=1). Valid: 0-3. Typical: 0.6-1.2. Example: 0.75.

  • pb (float, optional, default=0.0): Bubble point pressure in psia. If 0, will be calculated. Must be ≥ 0. Example: 3500.0.

  • rsb (float, optional, default=0.0): Solution GOR at bubble point in scf/stb. If 0 and pb provided, will be calculated. Must be ≥ 0. Example: 800.0.

  • method (str, optional, default="VELAR"): Correlation method. Options: "VELAR", "STAN", "VALMC".

Pressure Behavior:

  • p < pb: Rs calculated from correlation (increases with pressure)

  • p ≥ pb: Rs = rsb (constant, no additional gas dissolves)

Method Selection:

  • VELAR (Velarde 1997): Default, good accuracy. Use for most cases.

  • STAN (Standing 1947): Classic, widely used. Use for compatibility.

  • VALMC (Valko-McCain 2003): Alternative method.

Returns: Dictionary with:

  • value (float or list): Rs in scf/stb (matches input p shape)

  • method (str): Method used

  • units (str): "scf/stb"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Using separator gas gravity instead of separator gas gravity (sg_g parameter)

  • Not providing pb when p > pb (will calculate incorrectly)

  • Pressure in barg/psig instead of psia (must be absolute)

  • Confusing rsb (at bubble point) with separator GOR

Example Usage:

{
    "api": 35.0,
    "degf": 180.0,
    "p": [2000, 3000, 4000],
    "sg_g": 0.75,
    "pb": 3500.0,
    "rsb": 800.0,
    "method": "VELAR"
}

Result: Rs increases from ~400 scf/stb at 2000 psia to 800 scf/stb at 3500 psia, then remains 800 scf/stb at 4000 psia (above bubble point).

Note: Always provide pb and rsb when available for accurate results. If unknown, set pb=0 and rsb=0 to auto-calculate, but accuracy may be reduced.

Inputs: request (required). Returns: object

oil_twu_critical_propertiesA

Calculate critical properties using Twu (1984) correlation.

CRITICAL PROPERTIES ESTIMATION - Most widely used method for estimating Tc, Pc, Vc for petroleum fractions and plus fractions.

Twu Method:

  • More accurate than older correlations (Riazi-Daubert, Kesler-Lee)

  • Uses molecular weight and specific gravity

  • Optional boiling point for improved accuracy

  • Damping factor for heavy ends

Returns:

  • Tc: Critical temperature (°R)

  • Pc: Critical pressure (psia)

  • Vc: Critical volume (cuft/lbmol)

  • Also returns: SG, Tb (if not provided)

Critical for:

  • EOS (PR, SRK) fluid characterization

  • Plus fraction splitting

  • Compositional simulation

  • Phase behavior modeling

Args: request: Molecular weight, specific gravity, optional boiling point, damping

Returns: Dictionary with all critical properties

Inputs: request (required). Returns: object

oil_viscosityA

Calculate oil viscosity (μo).

CRITICAL PVT PROPERTY - Computes oil viscosity at reservoir conditions. Viscosity affects flow rates, pressure drops, and recovery efficiency. Uses Beggs-Robinson (1975) correlation, industry standard for oil viscosity.

Parameters:

  • api (float, required): Oil API gravity in degrees. Valid: 0-100. Example: 35.0. Higher API = lighter oil = lower viscosity.

  • degf (float, required): Reservoir temperature in °F. Valid: -460 to 1000. Example: 180.0. Higher temperature = lower viscosity.

  • p (float or list, required): Pressure(s) in psia. Must be > 0. Can be scalar or array. Example: 3000.0 or [2000, 3000, 4000].

  • pb (float, optional, default=0.0): Bubble point pressure in psia. Required for accurate calculation. Example: 3500.0.

  • rs (float or list, optional, default=0.0): Solution GOR at pressure p in scf/stb. If 0, will be calculated. Must match p shape. Example: 600.0.

  • rsb (float, optional, default=0.0): Solution GOR at bubble point in scf/stb. Required if pb provided. Example: 800.0.

  • method (str, optional, default="BR"): Correlation method. Only "BR" available.

Viscosity Behavior:

  • p < pb: Viscosity decreases with pressure (more gas dissolves, oil thins)

  • p = pb: Viscosity reaches minimum (μob, typically 0.5-5 cP)

  • p > pb: Viscosity increases with pressure (oil compression)

Typical Ranges:

  • Light oils (API > 35): 0.5-2 cP at bubble point

  • Medium oils (API 25-35): 1-10 cP at bubble point

  • Heavy oils (API < 25): 10-1000+ cP at bubble point

Returns: Dictionary with:

  • value (float or list): Viscosity in cP (matches input p shape)

  • method (str): "BR" (Beggs-Robinson)

  • units (str): "cP"

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Not providing rs when p < pb (will calculate incorrectly)

  • Using dead oil viscosity instead of live oil viscosity

  • Temperature in Celsius instead of Fahrenheit

  • Pressure in barg/psig instead of psia

Example Usage:

{
    "api": 35.0,
    "degf": 180.0,
    "p": [2000, 3000, 4000],
    "pb": 3500.0,
    "rs": [400, 600, 800],
    "rsb": 800.0,
    "method": "BR"
}

Result: Viscosity decreases from ~1.2 cP at 2000 psia to ~0.8 cP at 3500 psia, then increases to ~0.85 cP at 4000 psia (above bubble point).

Note: Viscosity is highly sensitive to temperature and dissolved gas content. Always use reservoir temperature, not separator temperature.

Inputs: request (required). Returns: object

rachford_rice_flashA

Solve Rachford-Rice equation for vapor-liquid equilibrium.

PHASE BEHAVIOR TOOL - Calculates vapor fraction (beta) and phase compositions for two-phase flash at specified pressure and temperature. Essential for compositional analysis, separator design, and phase behavior calculations.

Parameters:

  • zis (list, required): Overall mole fractions of components (0-1). Must sum to 1.0. Length must match Kis. Example: [0.5, 0.3, 0.2] for 3 components.

  • Kis (list, required): Equilibrium ratios (K-values) for components. Ki = yi/xi where yi = vapor mole fraction, xi = liquid mole fraction. Length must match zis. Example: [2.5, 1.8, 0.6]. K > 1 = light component.

Rachford-Rice Equation: Σ[zi(Ki - 1) / (1 + β(Ki - 1))] = 0

Where:

  • zi = overall mole fraction of component i

  • Ki = equilibrium ratio (yi/xi) for component i

  • β = vapor mole fraction (0 to 1)

Phase Behavior:

  • β = 0: All liquid (subcooled)

  • 0 < β < 1: Two-phase (vapor + liquid)

  • β = 1: All vapor (superheated)

K-Value Behavior:

  • K > 1: Component prefers vapor phase (light components)

  • K = 1: Component equally distributed (critical component)

  • K < 1: Component prefers liquid phase (heavy components)

  • K-values depend on pressure, temperature, and composition

Solution Method: Iterative Newton-Raphson method with bounds checking (0 ≤ β ≤ 1). Converges rapidly for well-posed problems. Typically converges in 3-10 iterations.

Applications:

  • Gas-Oil Separator Design: Determine separator conditions for phase split

  • Phase Envelope: Calculate bubble/dew points and phase boundaries

  • Compositional Simulation: Flash calculations in compositional models

  • EOS Flash: Solve equation of state flash calculations

  • Surface Facility Design: Design separation trains and processing units

  • Material Balance: Phase split in material balance calculations

Returns: Dictionary with:

  • vapor_fraction (float): Vapor mole fraction β (0-1)

  • liquid_composition (list): Liquid phase mole fractions xi

  • vapor_composition (list): Vapor phase mole fractions yi

  • method (str): "Rachford-Rice (Newton-Raphson)"

  • note (str): Interpretation guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Mole fractions don't sum to 1.0 (must normalize)

  • K-values don't match components (length mismatch)

  • K-values at wrong P-T conditions (must match flash conditions)

  • Using weight fractions instead of mole fractions

  • Not accounting for non-hydrocarbon components

  • K-values from wrong correlation/EOS

Example Usage:

{
    "zis": [0.5, 0.3, 0.2],
    "Kis": [2.5, 1.8, 0.6]
}

Result: β ≈ 0.3-0.5 (two-phase), with light components enriched in vapor, heavy components enriched in liquid.

Note: Rachford-Rice equation assumes ideal mixing. For real systems, K-values must account for non-ideality (activity coefficients, fugacity). K-values are typically obtained from EOS (Peng-Robinson, Soave-Redlich-Kwong) or correlations (Wilson, Standing). Always ensure K-values match flash conditions.

Inputs: request (required). Returns: object

stock_tank_gas_sgA

Calculate stock tank gas specific gravity.

Computes the specific gravity of gas liberated at stock tank conditions. This is the gas that comes out of solution when oil reaches atmospheric pressure and temperature.

Stock tank gas properties are needed for:

  • Sales gas quality specifications

  • Flare gas calculations

  • VOC emissions estimation

  • Safety assessments

Returns dimensionless specific gravity (air = 1.0).

Args: request: Stock tank gas parameters including oil properties and separator conditions

Returns: Dictionary with stock tank gas SG value(s), units, and inputs

Inputs: request (required). Returns: object

stock_tank_incremental_gorA

Calculate incremental GOR from separator to stock tank.

SEPARATOR DESIGN TOOL - Estimates gas evolved between separator and stock tank conditions.

Physics: As oil flows from separator (higher P, T) to stock tank (14.7 psia, ~60°F), additional gas comes out of solution.

Applications:

  • Separator optimization

  • Gas recovery calculations

  • Tank venting requirements

  • VOC emissions estimation

Returns stock tank incremental GOR in scf/stb.

Args: request: Separator pressure, temperature, and oil API

Returns: Dictionary with incremental GOR and guidance

Inputs: request (required). Returns: object

validate_gas_gravitiesA

Validate and impute missing gas gravities.

DATA VALIDATION TOOL - Checks consistency of gas gravities and calculates missing values when one is unknown.

Logic:

  • If sg_g provided: Calculate sg_sp from sg_g

  • If sg_sp provided: Calculate sg_g from sg_sp

  • If both provided: Validate consistency

Use Cases:

  • QC PVT data before analysis

  • Fill gaps in incomplete data

  • Validate separator gas measurements

Returns tuple of (sg_g, sg_sp) with calculated/validated values.

Args: request: Available gas gravities and GORs

Returns: Dictionary with validated/calculated gas gravities

Inputs: request (required). Returns: object

validate_simulation_deckA

Validate and process ECLIPSE simulation deck with INCLUDE files.

DECK MANAGEMENT TOOL - Recursively process ECLIPSE/Intersect simulation decks to find all INCLUDE files, validate references, and optionally create a complete archive.

What It Does:

  • Parses main DATA file for INCLUDE keywords

  • Recursively follows INCLUDE chains

  • Validates all referenced files exist

  • Identifies missing or broken references

  • Optionally creates zip archive with all files

Applications:

  • Deck Validation: Ensure all files present before submission

  • Deck Transfer: Create complete archive for sharing

  • Version Control: Bundle all files for archiving

  • QC Check: Verify deck completeness before cluster runs

Workflow:

  1. Specify main DATA file(s) to check

  2. Tool recursively finds all INCLUDE files

  3. Validates each file exists

  4. Reports missing files or broken paths

  5. Optionally creates zip with all referenced files

INCLUDE File Support:

  • Absolute paths: /full/path/to/file.inc

  • Relative paths: ../INCLUDE/GRID.GRDECL

  • Same directory: SCHEDULE.INC

  • Nested INCLUDE chains: INCLUDE files that reference other INCLUDE files

Output Formats:

  • Summary of all files found

  • List of missing/broken references

  • Optional: ZIP archive with complete deck

Args: request: List of DATA files, zip option, console output preference

Returns: Dictionary with file inventory, validation results, and optional zip path

Inputs: request (required). Returns: object

weighted_average_gas_sgA

Calculate weighted average gas specific gravity from separator stages.

SURFACE FACILITIES CALCULATION - Combines gas gravities from separator and stock tank weighted by GORs.

Use Cases:

  • Multi-stage separation optimization

  • Surface facility design

  • Gas sales allocation

  • Material balance

Formula: sg_avg = (sg_sp * rsp + sg_st * rst) / (rsp + rst)

Returns weighted average gas SG (dimensionless, air=1).

Args: request: Separator and stock tank gas properties

Returns: Dictionary with weighted average SG and breakdown

Inputs: request (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.3/5.0

    Scored across 45 tools

    Disambiguation4/5

    Most tools have distinct purposes within reservoir engineering, but there is some overlap between gas property tools (e.g., gas_z_factor, gas_critical_properties, gas_compressibility) which could cause confusion if an agent doesn't carefully read descriptions. However, each tool targets a specific calculation, and descriptions are detailed enough to differentiate them.

    Naming Consistency5/5

    Tool names follow a consistent snake_case pattern with clear verb_noun structure (e.g., calculate_brine_properties, gas_formation_volume_factor, oil_bubble_point). There are no deviations in naming conventions, making the set predictable and easy to parse.

    Tool Count2/5

    With 45 tools, the count is excessive for a single server, even for a comprehensive reservoir engineering toolkit. This many tools can overwhelm agents and increase selection complexity, suggesting the server should be split into more focused sub-servers (e.g., gas PVT, oil PVT, simulation tools).

    Completeness5/5

    The tool set provides extensive coverage of reservoir engineering domains, including PVT properties for oil, gas, and brine, flow calculations, heterogeneity analysis, simulation support, and phase behavior. There are no obvious gaps; it supports full workflows from data conversion to simulation input generation.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      D
      maintenance
      Enables AI assistants to perform complex chemical engineering calculations including thermodynamic modeling, equation of state calculations, phase equilibrium computations, and vapor-liquid equilibrium analysis. Built on the MoziChem framework to bridge AI language models with specialized chemical engineering tools.
      6
      4
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to perform unit-aware engineering calculations with automatic unit conversion, dependency resolution, and access to 500+ units across 75+ categories through the CalcsLive calculation engine.
      3
      15 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides AI agents with physics-based corrosion engineering calculations, from rapid handbook lookups to mechanistic electrochemical models with dual-tier pitting assessment for material compatibility screening and corrosion rate prediction.
      1
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      MCP server that gives LLMs access to petroleum engineering data and tools. Parse well logs, query production data, fit decline curves, calculate EUR, and run nodal analysis -- all through natural language with any MCP-compatible AI assistant.
      83
      1
      MIT