From the Reservoir to the Plant¶
In this tutorial you will run an oil field for ten years with the OPM Flow reservoir simulator and couple it to a DWSIM flowsheet: the gathering network of the wells and a production plant with separation, gas compression for injection and water injection. At every report step the network tells the reservoir how much pressure each well has to deliver at the wellhead, and the plant tells it how much gas and water it can inject and how much liquid it can take. You will run the same field first on its own, with a fixed wellhead pressure, and then coupled to the plant, and see how much oil the reservoir run on its own overestimates and which part of the surface causes the difference.
What you will learn
- What the wellhead pressure (THP), the bottom-hole pressure (BHP) and the lift table (VFP) of a well are, and how they tie the reservoir to the surface
- How to set up OPM Flow in WSL and check it from DWSIM
- How DWSIM generates the black-oil PVT and the lift table of the reservoir model from the flowsheet's own fluid
- How the Reservoir Coupling tool maps the wells to the sources of a Pipe Network and returns the plant's injection and capacity to the reservoir
- How the coupled run differs from the reservoir run on its own, and how to tell whether the wellhead pressure or the plant holds the wells back
Prerequisites
- Completed Gas Gathering Network and PVT Analysis of a Reservoir Oil
- DWSIM 10.3.0 or later on Windows, with WSL (Ubuntu 24.04), or on Linux
- The Reservoir Coupling tool and the Pipe Network are part of the Patreon edition, and running a coupled case needs the Premium+ level
Process Overview¶
A reservoir simulator computes how the pressure and the saturations of the rock change as the wells produce and inject. Each producer is set to an oil rate, but it can only deliver that rate while the reservoir pushes the fluid up the well against the pressure the surface asks for at the wellhead. Three terms describe this:
Tubing head pressure (THP): the pressure at the top of the well, where the flowline to the plant starts. The higher the gathering network and the plant hold it, the less the well can produce.
Bottom-hole pressure (BHP): the pressure at the bottom of the well, in front of the reservoir. The fluid flows from the rock into the well because the BHP is lower than the reservoir pressure.
Lift table (VFP): the vertical flow performance of the well, a table that gives the BHP needed to lift a given oil rate, water cut and gas-oil ratio up the tubing against a given THP. The reservoir simulator reads it from the reservoir model file, so it can turn a THP limit into a BHP limit at every step.
A reservoir model run on its own usually holds the THP of every well at one fixed value. In a real field the THP comes from the network: it is the pressure the flowlines, the trunk line and the inlet separator need to carry the fluid of all the wells to the plant, and it changes as the rates, the gas and the water change. The plant also sets limits of its own: the gas and the water it can inject, and the liquid it can handle.
The Reservoir Coupling tool closes that loop. OPM Flow runs one report step and returns the rates of each well. DWSIM puts those rates on the sources of the network, solves the flowsheet, and reads the pressure the network needs at each wellhead and the gas and water the plant has for injection. Those values become the THP limits and the injection targets of the next report step.
graph LR
R["OPM Flow<br/>reservoir model"] -- "rates of P1, P2, P3" --> N["NET<br/>gathering network"]
N --> P["Plant<br/>V-100, V-200, K-101, K-102, P-200"]
N -- "wellhead pressure<br/>(next THP limit)" --> R
P -- "injection gas and water,<br/>liquid capacity" --> R
The field: a box of 10 x 10 x 3 cells, 10000 ft on each side and 110 ft thick, with an undersaturated oil at 4800 psia over an aquifer. Producers P1, P2 and P3 sit at three corners, the gas injector GI1 at the fourth and the water injector WI1 two cells away from P1. Each producer is set to 8000 STB/d of oil and is shut when its oil rate falls below 1000 STB/d or its water cut passes 0.8. The numbers were made up for the example: it isn't a model of any real field.
The plant: the inlet separator V-100 holds 20 bar at the end of the trunk line. The oil is flashed again at 3 bar in V-200 and exported, the flash gas is compressed back to 20 bar, and all the gas is compressed in two stages to 250 bar. 5 % of it is fuel gas and the rest is the injection gas. The produced water and 25 kg/s of make-up water are pumped to 250 bar for injection.
What You Need: OPM Flow in WSL¶
OPM Flow is the open-source reservoir simulator of the Open Porous Media project. Its Python packages exist for Linux only, so on Windows DWSIM runs it inside the Windows Subsystem for Linux (WSL) and talks to it through a small script that ships with the tool.
- In a terminal opened as administrator, run
wsl --install -d Ubuntu-24.04, restart the computer, and create the Linux user when Ubuntu asks for it. - In DWSIM, open Tools > Reservoir Coupling (OPM Flow). The Python environment box says where the OPM packages go,
~/dwsim-opm/venvinside WSL by default. - Press Check. If the status says that the environment doesn't exist yet, press Install: it creates the environment and downloads the
opmandopm-simulatorspackages (about 300 MB). If Python 3 or itsvenvmodule is missing, the status tells you to runsudo apt install python3 python3-venvin Ubuntu. - Press Check again. The status turns green and gives the OPM Flow version.
You can check the same thing from a Windows terminal:
wsl -e bash -lc "~/dwsim-opm/venv/bin/python -c 'import opm.simulators; print(\"OPM Flow is ready\")'"
On Linux the tool uses the system's own shell, and the same environment path applies.
Key Design Parameters¶
| Parameter | Value |
|---|---|
| Compounds | Methane, Ethane, Propane, N-butane, N-octane, N-decane, N-dodecane, N-tetradecane, Water |
| Property package | Peng-Robinson |
| Stock tank oil | n-octane 0.25, n-decane 0.30, n-dodecane 0.25, n-tetradecane 0.20 (mole fractions), 735.3 kg/m³ |
| Separator gas | methane 0.80, ethane 0.10, propane 0.07, n-butane 0.03 (mole fractions) |
| Flowlines | FL-P1 and FL-P3 6000 m, FL-P2 3000 m, all 6 in, 10 m of rise |
| Trunk line | 4000 m of 10 in, 10 m of rise, to V-100 at 20 bar |
| Plant | V-200 at 3 bar, K-200 to 20 bar, K-101 to 70 bar, K-102 to 250 bar, coolers to 40 and 50 °C, P-100 to 30 bar, P-200 to 250 bar |
| Wells | 8000 STB/d of oil each, BHP at least 1000 psia, THP 300 psia in the reservoir model, lift table 1 |
| Lift table | 2560 m of 5 in tubing, 93 °C at the bottom; oil rates 500 to 12000 STB/d, THP 200 to 1500 psia, water cuts 0 to 0.9, gas-oil ratios 0.8 to 3 Mscf/STB |
| Report steps | 20 of 182.625 days (ten years) |
| Coupling | relaxation 0.5, at most 100 psi of THP change per step |
| Returns | injection gas to group GINJ, injection water to group WINJ, 20000 STB/d of liquid on group PROD |
Step-by-Step in the Classic UI¶
1. Set up¶
File > New Chemical Process Model: add Methane, Ethane, Propane, N-butane, N-octane, N-decane, N-dodecane, N-tetradecane and Water, and choose Peng-Robinson. A cubic equation of state suits light hydrocarbons and water from 3 to 250 bar, which is the whole range of this flowsheet.
2. The surface fluids¶
The reservoir model describes the oil as a black oil: a stock tank oil, a separator gas dissolved in it, and water. DWSIM needs the compositions behind those three names to turn the rates of a well back into a stream. Add two material streams at 15.56 °C and 1 atm:
stock-tank-oil, with the oil composition of the table above;separator-gas, with the gas composition.
The flows don't matter: the tool reads only the compositions. When a well produces, the tool recombines the stock tank oil, the gas and the water at the well's rates and puts the result on the source of that well.
3. The gathering network¶
Add a Pipe Network named NET, open the Network Designer, and in Settings set Flow Model to Compositional (multiphase), as in the gas gathering tutorial. Then build:
- three Source blocks
WH-P1,WH-P2andWH-P3, each with Specified VariableMass Flowand an inlet stream (wellstream-P1toP3) at 60 °C and 40 bar. Give each stream about 15 kg/s of well fluid to start with; the coupling overwrites it at every step; - after each source a Node (
N-P1toN-P3) and a flowline (FL-P1toFL-P3) to the manifold nodeMAN; - the trunk line
TRUNK, the nodeDELand a SinkSEPwith Specified VariablePressure, 20 bar, whose outlet streamto-separatorgoes to the plant.
The tool finds the producers' sources by name: a source whose tag contains the name of the well (WH-P1 for P1) is mapped to it.
4. The plant¶
Build the plant on to-separator as in the table above:
- Separation: three-phase separator
V-100, valveLV-100to 3 bar, three-phase separatorV-200, pumpP-100to 30 bar for the oil export; - Flash gas: compressor
K-200to 20 bar, coolerE-200to 40 °C, and mixerMIX-100with the gas of V-100; - Injection compression: scrubber
V-101, compressorK-101to 70 bar, coolerE-101to 40 °C, scrubberV-102, compressorK-102to 250 bar, coolerE-102to 50 °C, and splitterSPL-100that sends 5 % tofuel-gasand 95 % toinjection-gas. The scrubbers are three-phase vessels: once the wells produce water, the gas carries enough of it to condense after the coolers; - Water injection: mixer
MIX-200with the water of V-100, V-200, V-101 and V-102 and 25 kg/s ofmakeup-water, and pumpP-200to 250 bar, whose outlet isinjection-water.
Solve the flowsheet once. The first solve takes about two minutes, because the network starts from the guessed well streams.

5. The black-oil PVT of the reservoir model¶
Open Tools > Reservoir Coupling (OPM Flow), choose NET in Pipe Network of the wells, stock-tank-oil and separator-gas for the two compositions and Water as the water compound. Then press Black-oil PVT....
The dialog generates the DENSITY, PVTO, PVDG and PVTW keywords of the reservoir model from the flowsheet's property package at the reservoir temperature, 93 °C: the solution gas, the formation volume factors and the viscosities of the oil and the gas over the pressure range of the field. Keep the default axes, press Generate and Save as... pvt_dwsim.inc. With this table the reservoir and the plant use the same fluid, so a stock tank barrel in the reservoir is the same mass of oil in the plant.
The generator reports two notes. Peng-Robinson gives the liquid density of n-dodecane and n-tetradecane 11 and 16 % low, so the generator sets their volume shift to match the density at standard conditions. The stock tank oil then has 735.3 kg/m³.
6. The lift table¶
Lift table (VFPPROD)... generates the VFPPROD table of the wells with the Pipe unit operation and the same fluid: for each oil rate, THP, water cut and gas-oil ratio of the axes, it finds the BHP that lifts the fluid through 2560 m of 5 in tubing. A table of 288 points with water and gas took four hours to compute, so this tutorial uses the table that the tool generated for the Case Library case, vfp_dwsim.inc in examples/reservoir. Use the button when you change the tubing or the fluid, and run it overnight for a large table.
7. The reservoir model file¶
The reservoir model file (.DATA) is the input of OPM Flow; reservoir engineers call it a deck. The Python script of this tutorial writes it as OILFIELD.DATA, next to the two include files. Its main parts are:
- the grid, the porosity and the permeabilities of the three layers, the rock and the relative permeability tables (SWOF, SGOF);
INCLUDE 'pvt_dwsim.inc'andINCLUDE 'vfp_dwsim.inc', the two tables made by DWSIM;WCONPROD, which sets each producer to 8000 STB/d of oil with a BHP limit of 1000 psia, a THP limit of 300 psia and lift table 1. The THP limit and the lift table are what the coupling works through;WECON, the economic limit of the producers, andGCONINJE, the injection targets of the groups GINJ and WINJ, which the plant overrides in the coupled run;TSTEP 20*182.625, twenty report steps of half a year.
The coupling exchanges data once per report step. The Case Library case uses 120 monthly steps and needs 39 minutes; with 20 steps the coupled run of this tutorial takes about four minutes.
8. Read the reservoir model and map the wells¶
In Reservoir model file (.DATA) pick OILFIELD.DATA and press Read the reservoir model. The tool starts OPM Flow, reads the units, the report steps, the wells and the groups, and stops it. The Wells table lists P1, P2 and P3 with their THP limit and lift table, and Map the wells to the sources by name fills the Network source column with WH-P1, WH-P2 and WH-P3.

9. The coupling settings and the returns¶
In Coupling set:
- Relaxation of the THP limit: 0.5. The new THP limit moves half way from the old one to the pressure the network found, which keeps the rates from swinging from step to step;
- Largest THP limit change per step: 100 psi. A limit that jumps above what a well can deliver would make OPM Flow shut the well;
- Time limit of a flowsheet solve: 300 s.
In Returns from the flowsheet to the reservoir add three rows:
| Return | Value from | Object | Target |
|---|---|---|---|
| Gas injection | Stream, as gas | injection-gas |
GINJ |
| Water injection | Stream, as water | injection-water |
WINJ |
| Liquid production limit | Constant, 20000 | PROD |
The returns act one step later, since the reservoir step that produced the rates has already been computed when the plant is solved.
10. Run the reservoir alone, then coupled¶
Tick Run the reservoir alone and press Run. OPM Flow runs the twenty steps in a few seconds with the THP limits of the reservoir model, 300 psia for every well, and without the plant. Untick it and press Run again for the coupled run. After each step the status line shows the rates and the THP limits, and the Field, Wells and Returns tabs fill up as the run goes.
The script prints the THP limits of the coupled run:
| Day | Oil, STB/d | THP limit P1, psia | P2 | P3 |
|---|---|---|---|---|
| 183 | 24000 | 300 | 300 | 300 |
| 365 | 20000 | 400 | 400 | 400 |
| 548 | 20000 | 482 | 445 | 484 |
| 1096 | 20000 | 552 | 485 | 557 |
| 1826 | 19962 | 557 | 492 | 569 |
| 2557 | 18573 | 465 | 513 | 602 |
| 3652 | 17409 | 411 | 522 | 624 |
In the first step the wells produce 8000 STB/d each with the 300 psia limits of the reservoir model, because the plant's limit of 20000 STB/d reaches the reservoir only from the second step. From then on the network asks for more than 300 psia at the wellheads, and P2, with the shortest flowline, asks for the least. The THP limits climb by at most 100 psi per step and settle between 490 and 570 psia.
A THP limit is a ceiling, though. The Wells tab also lists the tubing head pressure that OPM Flow computes for each well: on the plateau the wells deliver 1800 to 1900 psia at the wellhead, far above what the network needs. The THP limits don't hold any of the wells at any step, and the script says so after the run. What holds the field at 20000 STB/d is the plant's liquid limit, which OPM Flow shares among the producers of group PROD.
Water reaches P1, next to the water injector, after about five years. P1 then produces less oil, its flowline carries less fluid, and the network needs less pressure at its wellhead, so its THP limit falls to 411 psia. P2 and P3 take over the plant's capacity and reach their own target of 8000 STB/d, and their flowlines need more pressure (522 and 624 psia at the end).


The Returns tab shows what the plant sent back at each step: the injection gas of the plant goes to GINJ in place of the 20000 Mscf/d of the reservoir model, and the injection water to WINJ in place of 13000 STB/d.

Results and Validation¶
The script prints the comparison of the two runs:
| Quantity | Reservoir alone | Coupled to the plant |
|---|---|---|
| THP limit of the producers, psia | 300 (fixed) | 400 to 570 on the plateau, 411 to 624 at the end |
| Wells held by their THP limit | 0 of 3 | 0 of 3 |
| Oil plateau, STB/d | 24000 | 20000 |
| Plateau held until day | 1826 | 1826 |
| Oil rate after ten years, STB/d | 16000 | 17409 |
| P1 after ten years | shut at step 17 | 1409 STB/d of oil, water cut 0.65 |
| Cumulative oil, million STB | 77.12 | 70.74 |
| Cumulative oil of P1 / P2 / P3, million STB | 18.68 / 29.22 / 29.22 | 16.93 / 26.99 / 26.82 |
| Average reservoir pressure after ten years, psia | 3096 | 3969 |
| Gas injection at the last step, Mscf/d | 20000 (target of the reservoir model) | 18053 (from the plant) |
| Water injection at the last step, STB/d | 13000 (target of the reservoir model) | 16019 (from the plant) |
Expected results
The reservoir alone recovers 77.12 million STB in ten years, and P1 is shut at step 17 by its economic limit. Coupled to the network and the plant, the same field recovers 70.74 million STB: 6.38 million STB (8.3 %) less. In this field the difference comes from the plant. The wells could deliver far more than the wellhead pressure the network asks for, so the THP limits don't hold them, but the plant takes only 20000 STB/d of liquid in place of the 24000 STB/d of the three well targets. The plant also injects the produced water with its make-up, so the reservoir pressure stays 873 psia higher, the field declines more slowly, and P1 keeps producing to the end. The coupled run takes about four minutes, and the whole script about seven.
The field and the plant are the ones of the Oil field from the reservoir to the plant case of the Case Library (cases/fluid-flow-and-piping/oil-field-reservoir-to-plant), which runs 120 monthly report steps. Its README gives 77.13 million STB for the reservoir alone and 70.29 million STB for the coupled run, a difference of 6.8 million STB (9 %), with THP limits of 490 to 620 psia. With half-year steps this tutorial finds the same picture: the reservoir alone matches to 0.01 million STB, and the coupled run recovers 0.45 million STB more, because the THP limits follow the network only twenty times instead of 120. The case doesn't have a reference from a plant or from another simulator: the comparison is between two ways of running the same model.
Automating This Tutorial¶
Files in this repository
- Python script:
examples/reservoir/02_reservoir_coupling.py - Lift table of the wells:
examples/reservoir/vfp_dwsim.inc - Pre-built flowsheet:
examples/saved/reservoir_coupling.dwxmz, with the coupling casereservoir_coupling.dwrscnext to it
The script needs DWSIM Plus at the Premium+ level: set DWSIM_PATRON_KEY to your Patreon key, or run it where the Plus license is activated. It also needs OPM Flow in WSL, in the environment ~/dwsim-opm/venv, and it stops with the tool's advice when the environment isn't ready. It builds the flowsheet, generates the black-oil PVT, writes the reservoir model file to DWSIM_RESERVOIR_DIR (a folder in the temporary folder when it isn't set), runs the reservoir alone and coupled, and prints the tables above. If DWSIM_SAVE_TO is set to a file name, it saves the flowsheet there with the coupling case next to it. The saved case leaves the reservoir model file empty, so pick OILFIELD.DATA in the window before you run it.
import os
import shutil
import sys
import tempfile
import time
import pythonnet
pythonnet.load("netfx") # DWSIM is a .NET Framework application
import clr # noqa: E402
DWSIM_BIN = os.environ.get("DWSIM_BIN")
if not DWSIM_BIN:
raise SystemExit("Set DWSIM_BIN to the DWSIM installation folder before running.")
for sub in ("", "unitops", "ppacks", "extenders"):
sys.path.append(os.path.join(DWSIM_BIN, sub))
for a in ("DWSIM.Automation", "DWSIM.Automation.FluentAPI", "DWSIM.UnitOperations", "DWSIM.UnitOperations.PipeNetwork",
"DWSIM.Extensions.ReservoirCoupling", "DWSIM.Support"):
clr.AddReference(a)
from System import Action # noqa: E402
from System.Collections.Generic import Dictionary # noqa: E402
from System.Threading import CancellationToken # noqa: E402
from DWSIM.Automation.FluentAPI import Flowsheet, License, PropertyPackages, Q # noqa: E402
from DWSIM.UnitOperations.PipeNetwork.Blocks import Pipe, Sink, Source # noqa: E402
from DWSIM.UnitOperations.PipeNetwork.Classes import BoundarySpecification, NodalFlowModel # noqa: E402
from DWSIM.UnitOperations.UnitOperations.Auxiliary.Pipe import PipeEditorStatus, PipeSection # noqa: E402
from DWSIM.Extensions.ReservoirCoupling import (DeckUnits, OpmEnvironment, ReservoirInfo, RuleRow, # noqa: E402
StepRecord, SurfaceFluid, UnitConversion, WellState)
from DWSIM.Extensions.ReservoirCoupling.Dwsim import CouplingSession # noqa: E402
from DWSIM.Support import Initialization # noqa: E402
# --- license: running a coupled case needs the Premium+ level ------------------------------------------------------
if not License.IsActivated:
key = os.environ.get("DWSIM_PATRON_KEY")
if not key or not License.CheckLicense(key):
raise SystemExit("The Reservoir Coupling tool is part of DWSIM Plus: set DWSIM_PATRON_KEY to your Patreon key.")
if Initialization.GetAccessLevel() < 3:
raise SystemExit("Running a coupled case needs the Premium+ level of the DWSIM Patreon membership.")
STB, MSCF, PSI, DAY = UnitConversion.M3PerStb, UnitConversion.M3PerMscf, UnitConversion.PaPerPsi, 86400.0
WELLS = ["P1", "P2", "P3"]
VENV = "~/dwsim-opm/venv" # the Python environment of OPM Flow inside WSL
REPORT_STEPS, STEP_DAYS = 20, 182.625 # ten years in half-year report steps
# --- 1. Is OPM Flow ready? -------------------------------------------------------------------------------------------
status = OpmEnvironment.Check(VENV)
print(status.Summary)
if not status.Ready:
raise SystemExit(status.Advice or "Open Tools > Reservoir Coupling (OPM Flow) in DWSIM and press Install.")
# --- 2. The surface fluids: stock tank oil, separator gas and water -------------------------------------------------
OIL = {"N-octane": 0.25, "N-decane": 0.30, "N-dodecane": 0.25, "N-tetradecane": 0.20}
GAS = {"Methane": 0.80, "Ethane": 0.10, "Propane": 0.07, "N-butane": 0.03}
fluid = SurfaceFluid()
fluid.OilComposition = Dictionary[str, float]()
for k, v in OIL.items():
fluid.OilComposition[k] = v
fluid.GasComposition = Dictionary[str, float]()
for k, v in GAS.items():
fluid.GasComposition[k] = v
compounds = list(fluid.Compounds(True)) # gas compounds, oil compounds, water
fs = (Flowsheet.Create("Reservoir to plant")
.WithCompounds(*compounds)
.WithPropertyPackage(PropertyPackages.PengRobinson))
def set_flows(stream, flows, t_c, p_pa):
"""Compound molar flows (mol/s) on a stream, then its temperature and pressure."""
for c in compounds:
stream.SetCompoundMolarFlow(c, flows[c] if flows.ContainsKey(c) else 0.0)
stream.At(Q.Celsius(t_c), Q.Pascal(p_pa))
stream.Object.Calculate()
# the two streams the coupling reads the surface compositions from, at standard conditions
set_flows(fs.AddMaterialStream("stock-tank-oil"), fluid.Mix(1.0, 0.0), 15.556, 101325.0)
set_flows(fs.AddMaterialStream("separator-gas"), fluid.Mix(0.0, 1.0), 15.556, 101325.0)
# --- 3. The gathering network: one flowline per well, a manifold and a trunk line to the plant ---------------------
net = fs.AddPipeNetwork("NET")
net.Object.NodalFlowModel = NodalFlowModel.Compositional # each pipe flashes the well fluid along its length
def set_pipe(node, length_m, rise_m, id_inch):
"""One straight carbon steel section: length, elevation change, outer and inner diameter."""
prof = node.As[Pipe]().BaseUnitOperation.Profile
prof.Sections.Clear()
sec = PipeSection(1, "Straight Tube", 1, 10, "Carbon Steel", length_m, rise_m, id_inch + 1.0, id_inch)
sec.PipeWallRugosity = 4.6e-5
prof.Sections.Add(1, sec)
prof.Status = PipeEditorStatus.OK
# a starting well stream: 8000 STB/d of oil with 1.2 Mscf/STB of gas and 10 % of water; the coupling overwrites it
seed_state = WellState()
seed_state.OilRate = 8000.0 * STB / DAY
seed_state.GasRate = seed_state.OilRate * 213.6
seed_state.WaterRate = 0.1 * seed_state.OilRate
seed = fluid.Recombine(seed_state)
FLOWLINES = {"P1": 6000.0, "P2": 3000.0, "P3": 6000.0} # m, 6 in lines
manifold = net.AddNode("MAN")
for w in WELLS:
src = net.AddSource("WH-" + w)
src.As[Source]().BoundarySpec = BoundarySpecification.MassFlow
node, line = net.AddNode("N-" + w), net.AddPipe("FL-" + w)
set_pipe(line, FLOWLINES[w], 10.0, 6.0)
net.ConnectChain(src, node, line, manifold)
ws = net.AttachStream(src, "wellstream-" + w)
set_flows(ws, seed, 60.0, 40e5)
src.As[Source]().MassFlowSpec = ws.Object.GetMassFlow()
trunk, delivery = net.AddPipe("TRUNK"), net.AddNode("DEL")
set_pipe(trunk, 4000.0, 10.0, 10.0)
sink = net.AddSink("SEP")
sink.As[Sink]().BoundarySpec = BoundarySpecification.Pressure
sink.As[Sink]().PressureSpec = 20e5 # the inlet separator holds 20 bar
net.ConnectChain(manifold, trunk, delivery, sink)
feed = net.AttachStream(sink, "to-separator")
set_flows(feed, seed, 60.0, 20e5)
# --- 4. The plant: separation, oil export, gas compression for injection, water injection --------------------------
S = {}
def ms(tag):
S[tag] = fs.AddMaterialStream(tag)
return S[tag]
def es(tag):
return fs.AddEnergyStream(tag)
fs.AddSeparator("V-100").ConnectFeed(feed).ConnectProduct(ms("hp-gas"), 0).ConnectProduct(ms("hp-oil"), 1) \
.ConnectProduct(ms("hp-water"), 2)
fs.AddValve("LV-100").WithOutletPressure(Q.Pascal(3e5)).ConnectFeed(S["hp-oil"]).ConnectProduct(ms("lp-feed"))
fs.AddSeparator("V-200").ConnectFeed(S["lp-feed"]).ConnectProduct(ms("lp-gas"), 0) \
.ConnectProduct(ms("stabilized-oil"), 1).ConnectProduct(ms("lp-water"), 2)
fs.AddPump("P-100").WithOutletPressure(Q.Pascal(30e5)).WithEfficiencyPercent(75) \
.ConnectFeed(S["stabilized-oil"]).ConnectProduct(ms("oil-export")).ConnectEnergyFeed(es("W-P-100"), 1)
# the flash gas goes back to the separator pressure and joins the separator gas
fs.AddCompressor("K-200").WithOutletPressure(Q.Pascal(20e5)).WithAdiabaticEfficiencyPercent(75) \
.ConnectFeed(S["lp-gas"]).ConnectProduct(ms("lp-gas-compressed")).ConnectEnergyFeed(es("W-K-200"), 1)
fs.AddCooler("E-200").WithOutletTemperature(Q.Celsius(40.0)).ConnectFeed(S["lp-gas-compressed"]) \
.ConnectProduct(ms("lp-gas-cooled"))
fs.AddMixer("MIX-100").ConnectFeed(S["hp-gas"], 0).ConnectFeed(S["lp-gas-cooled"], 1).ConnectProduct(ms("gas-to-compression"))
# two compression stages to 250 bar, with a scrubber before each that sends its water to injection
fs.AddSeparator("V-101").ConnectFeed(S["gas-to-compression"]).ConnectProduct(ms("k-101-suction"), 0) \
.ConnectProduct(ms("scrubber-1-liquid"), 1).ConnectProduct(ms("scrubber-1-water"), 2)
fs.AddCompressor("K-101").WithOutletPressure(Q.Pascal(70e5)).WithAdiabaticEfficiencyPercent(75) \
.ConnectFeed(S["k-101-suction"]).ConnectProduct(ms("k-101-discharge")).ConnectEnergyFeed(es("W-K-101"), 1)
fs.AddCooler("E-101").WithOutletTemperature(Q.Celsius(40.0)).ConnectFeed(S["k-101-discharge"]).ConnectProduct(ms("interstage"))
fs.AddSeparator("V-102").ConnectFeed(S["interstage"]).ConnectProduct(ms("k-102-suction"), 0) \
.ConnectProduct(ms("scrubber-2-liquid"), 1).ConnectProduct(ms("scrubber-2-water"), 2)
fs.AddCompressor("K-102").WithOutletPressure(Q.Pascal(250e5)).WithAdiabaticEfficiencyPercent(75) \
.ConnectFeed(S["k-102-suction"]).ConnectProduct(ms("k-102-discharge")).ConnectEnergyFeed(es("W-K-102"), 1)
fs.AddCooler("E-102").WithOutletTemperature(Q.Celsius(50.0)).ConnectFeed(S["k-102-discharge"]) \
.ConnectProduct(ms("high-pressure-gas"))
fs.AddSplitter("SPL-100").WithSplitRatios(0.05, 0.95).ConnectFeed(S["high-pressure-gas"]) \
.ConnectProduct(ms("fuel-gas"), 0).ConnectProduct(ms("injection-gas"), 1)
# produced water plus 25 kg/s of make-up water, pumped to 250 bar
makeup = ms("makeup-water")
for c in compounds:
makeup.SetCompoundMolarFlow(c, 25.0 / SurfaceFluid.WaterMolarMass if c == "Water" else 0.0)
makeup.At(Q.Celsius(25.0), Q.Pascal(3e5))
fs.AddMixer("MIX-200").ConnectFeed(S["hp-water"], 0).ConnectFeed(S["lp-water"], 1).ConnectFeed(makeup, 2) \
.ConnectFeed(S["scrubber-1-water"], 3).ConnectFeed(S["scrubber-2-water"], 4).ConnectProduct(ms("water-to-injection"))
fs.AddPump("P-200").WithOutletPressure(Q.Pascal(250e5)).WithEfficiencyPercent(75) \
.ConnectFeed(S["water-to-injection"]).ConnectProduct(ms("injection-water")).ConnectEnergyFeed(es("W-P-200"), 1)
t0 = time.time()
errors = fs.TrySolve()
print("Flowsheet solved in %.0f s with %d error(s)" % (time.time() - t0, errors.Count))
# --- 5. The reservoir model file, with the black-oil PVT and the lift table that DWSIM generated ------------------
HERE = os.path.dirname(os.path.abspath(__file__))
work = os.environ.get("DWSIM_RESERVOIR_DIR") or os.path.join(tempfile.gettempdir(), "dwsim_reservoir_tutorial")
os.makedirs(work, exist_ok=True)
shutil.copyfile(os.path.join(HERE, "vfp_dwsim.inc"), os.path.join(work, "vfp_dwsim.inc"))
session = CouplingSession(fs.Inner)
case = session.Case
case.PythonEnvironment = VENV
case.NetworkTag = "NET"
case.OilStream, case.GasStream, case.WaterCompound = "stock-tank-oil", "separator-gas", "Water"
# black-oil PVT of this fluid at the reservoir temperature, from the flowsheet's property package
t0 = time.time()
pvt = session.GeneratePvt(session.Prepare(True), DeckUnits.Field)
with open(os.path.join(work, "pvt_dwsim.inc"), "w", newline="\n") as f:
f.write(pvt.Keywords)
print("Black-oil PVT generated in %.0f s: stock tank oil %.1f kg/m3" % (time.time() - t0, pvt.OilDensity))
for note in pvt.Notes:
print(" note:", note)
SWC, SOR, SGC, SOGR = 0.20, 0.25, 0.04, 0.05
def swof():
rows = []
for i in range(13):
sw = SWC + (1.0 - SOR - SWC) * i / 12
s = (sw - SWC) / (1.0 - SOR - SWC)
rows.append((sw, 0.4 * s ** 2.5, (1.0 - s) ** 2.0, 0.0))
rows.append((1.0, 1.0, 0.0, 0.0))
return rows
def sgof():
rows = [(0.0, 0.0, 1.0, 0.0)]
top = 1.0 - SWC - SOGR
for i in range(13):
sg = SGC + (top - SGC) * i / 12
s = (sg - SGC) / (top - SGC)
rows.append((sg, 0.9 * s ** 2.0, (1.0 - s) ** 2.5 if i < 12 else 0.0, 0.0))
return rows
def table(rows):
return "\n".join(" %.4f %.5f %.5f %.1f" % r for r in rows) + " /"
MODEL = """-- Oil field of the DWSIM reservoir coupling tutorial (made up for the example).
RUNSPEC
TITLE
Oil field of the DWSIM reservoir coupling tutorial
DIMENS
10 10 3 /
OIL
GAS
WATER
DISGAS
FIELD
START
1 'JAN' 2026 /
TABDIMS
1 1 20 20 /
EQLDIMS
1 /
WELLDIMS
5 3 4 5 /
VFPPDIMS
6 4 4 3 1 1 /
UNIFOUT
GRID
INIT
DX
300*1000 /
DY
300*1000 /
DZ
100*25 100*35 100*50 /
TOPS
100*8300 /
PORO
300*0.27 /
PERMX
100*350 100*60 100*220 /
PERMY
100*350 100*60 100*220 /
PERMZ
100*35 100*6 100*22 /
PROPS
INCLUDE
'pvt_dwsim.inc' /
ROCK
14.7 3.0E-6 /
SWOF
%s
SGOF
%s
SOLUTION
EQUIL
8400 4800 8600 0 8200 0 1 0 0 /
RSVD
8300 1.1
8410 1.1 /
SUMMARY
FOPR
FGPR
FWPR
FPR
SCHEDULE
GRUPTREE
'PROD' 'FIELD' /
'GINJ' 'FIELD' /
'WINJ' 'FIELD' /
/
WELSPECS
'P1' 'PROD' 10 10 8400 'OIL' /
'P2' 'PROD' 10 3 8400 'OIL' /
'P3' 'PROD' 3 10 8400 'OIL' /
'GI1' 'GINJ' 1 1 8312 'GAS' /
'WI1' 'WINJ' 8 8 8400 'WATER' /
/
COMPDAT
'P1' 10 10 3 3 'OPEN' 1* 1* 0.5 /
'P2' 10 3 3 3 'OPEN' 1* 1* 0.5 /
'P3' 3 10 3 3 'OPEN' 1* 1* 0.5 /
'GI1' 1 1 1 1 'OPEN' 1* 1* 0.5 /
'WI1' 8 8 3 3 'OPEN' 1* 1* 0.5 /
/
INCLUDE
'vfp_dwsim.inc' /
-- each producer: 8000 STB/d of oil, at least 1000 psia at the bottom of the well, 300 psia at the wellhead, lift table 1
WCONPROD
'P1' 'OPEN' 'ORAT' 8000 4* 1000 300 1 /
'P2' 'OPEN' 'ORAT' 8000 4* 1000 300 1 /
'P3' 'OPEN' 'ORAT' 8000 4* 1000 300 1 /
/
-- a producer below 1000 STB/d of oil, or with a water cut above 0.8, is shut
WECON
'P*' 1000 1* 0.8 2* 'WELL' 'YES' /
/
GCONINJE
'GINJ' 'GAS' 'RATE' 20000 /
'WINJ' 'WATER' 'RATE' 13000 /
/
WCONINJE
'GI1' 'GAS' 'OPEN' 'RATE' 40000 1* 9000 /
'WI1' 'WATER' 'OPEN' 'RATE' 30000 1* 9000 /
/
TSTEP
%d*%g /
END
""" % (table(swof()), table(sgof()), REPORT_STEPS, STEP_DAYS)
model_path = os.path.join(work, "OILFIELD.DATA")
with open(model_path, "w", newline="\n") as f:
f.write(MODEL)
# --- 6. Read the reservoir model and map the producers to the sources of the network -------------------------------
case.DeckPath = model_path
case.OutputDirectory = os.path.join(work, "out")
info = session.ReadDeck()
print("Reservoir model: %d report steps, %s units" % (info.ReportSteps, info.Units))
for w in info.Wells:
kind = "producer" if w.IsProducer else ("injector, " + str(w.InjectedPhase).lower()) if w.IsInjector else "well"
extra = ", THP limit %.0f psia, lift table %d" % (w.DeckThpLimit, w.DeckVfpTable) if w.IsProducer else ""
print(" %-4s %s in group %s%s" % (w.Name, kind, w.Group, extra))
print(" producers mapped to the network:", session.AutoMapWells())
case.Relaxation = 0.5 # the new THP limit moves half way to the pressure the network found
case.MaximumThpStep = 100 # psi per report step
case.SolverTimeout = 300
case.OilDensity = 735.3
def rule(kind, source, obj, target, value=0.0):
r = RuleRow()
r.Kind, r.Source, r.SourceObject, r.Target, r.Value = kind, source, obj, target, value
return r
case.Rules.Add(rule("gasinj", "gas", "injection-gas", "GINJ")) # gas the plant has for injection
case.Rules.Add(rule("watinj", "water", "injection-water", "WINJ")) # water the plant has for injection
case.Rules.Add(rule("limit-liquid", "const", "", "PROD", 20000.0)) # the plant handles 20000 STB/d of liquid
# --- 7. Run the reservoir alone, then coupled to the plant ----------------------------------------------------------
def field_oil(rec):
"""Oil rate of the three producers at a report step, STB/d."""
return sum(rec.Wells[w].OilRate for w in WELLS if rec.Wells.ContainsKey(w)) * DAY / STB
def run(reservoir_only):
case.ReservoirOnly = reservoir_only
records = []
def on_step(rec, inf):
records.append(rec)
if not reservoir_only:
oil = field_oil(rec)
thp = " ".join("%4.0f" % (rec.ThpLimit[w] / PSI) if rec.ThpLimit.ContainsKey(w) else " -" for w in WELLS)
print(" day %5.0f oil %6.0f STB/d THP limits %s psia%s" % (
rec.TimeDays, oil, thp, " (" + rec.SurfaceError + ")" if rec.SurfaceError else ""))
t = time.time()
outcome = session.Run(session.Prepare(False), Action[StepRecord, ReservoirInfo](on_step), None,
getattr(CancellationToken, "None")) # "None" is a Python keyword
for note in outcome.Notes:
print(" note:", note)
return records, time.time() - t
def summary(records):
"""Cumulative oil (million STB) in total and by well, the plateau, the last oil rate and the reservoir pressure."""
cum_w, prev = {w: 0.0 for w in WELLS}, 0.0
for r in records:
dt, prev = r.TimeDays - prev, r.TimeDays
for w in WELLS:
if r.Wells.ContainsKey(w):
cum_w[w] += r.Wells[w].OilRate * DAY / STB * dt / 1e6
# the plateau is the rate of the second step: in the coupled run the plant limit acts from there on
plateau = field_oil(records[1])
end = max(r.TimeDays for r in records if field_oil(r) >= 0.99 * plateau)
last = records[-1]
last_w = {w: (last.Wells[w].OilRate * DAY / STB if last.Wells.ContainsKey(w) else 0.0) for w in WELLS}
wcut_w = {}
for w in WELLS:
q = last.Wells[w] if last.Wells.ContainsKey(w) else None
liquid = (q.OilRate + q.WaterRate) if q is not None else 0.0
wcut_w[w] = q.WaterRate / liquid if liquid > 0 else 0.0
return dict(cum=sum(cum_w.values()), cum_w=cum_w, plateau=plateau, end=end, last=field_oil(last),
last_w=last_w, wcut_w=wcut_w, pressure=last.AveragePressure / PSI)
print("\nReservoir alone, with the fixed 300 psia wellhead pressure of the reservoir model:")
alone, t_alone = run(True)
print(" %d report steps in %.0f s" % (len(alone), t_alone))
print("\nCoupled to the gathering network and the plant:")
coupled, t_coupled = run(False)
print(" %d report steps in %.0f s" % (len(coupled), t_coupled))
a, c = summary(alone), summary(coupled)
print("\n%-44s %16s %16s" % ("", "Reservoir alone", "Coupled"))
print("%-44s %16.0f %16.0f" % ("Oil plateau, STB/d", a["plateau"], c["plateau"]))
print("%-44s %16.0f %16.0f" % ("Plateau held until day", a["end"], c["end"]))
print("%-44s %16.0f %16.0f" % ("Oil rate after ten years, STB/d", a["last"], c["last"]))
print("%-44s %16.2f %16.2f" % ("Cumulative oil, million STB", a["cum"], c["cum"]))
for w in WELLS:
print("%-44s %16.2f %16.2f" % (" of which " + w, a["cum_w"][w], c["cum_w"][w]))
for w in WELLS:
print("%-44s %16s %16s" % (" oil rate and water cut of " + w + " at the end", "%.0f, %.2f" % (a["last_w"][w], a["wcut_w"][w]),
"%.0f, %.2f" % (c["last_w"][w], c["wcut_w"][w])))
print("%-44s %16.0f %16.0f" % ("Average reservoir pressure at the end, psia", a["pressure"], c["pressure"]))
print("Difference in cumulative oil: %.2f million STB (%.1f %%)" % (a["cum"] - c["cum"], 100 * (a["cum"] - c["cum"]) / a["cum"]))
# a well is held by its THP limit when the wellhead pressure OPM Flow reports sits on the limit; otherwise its rate,
# the group limit or its BHP limit holds it
for w in WELLS:
held = [r.TimeDays for r in coupled if r.Wells.ContainsKey(w) and r.ThpLimit.ContainsKey(w)
and r.Wells[w].OilRate > 0 and r.Wells[w].TubingHeadPressure <= 1.005 * r.ThpLimit[w]]
if held:
print("%s: held by its THP limit at %d of %d steps, from day %.0f" % (w, len(held), len(coupled), held[0]))
else:
print("%s: its THP limit didn't hold it at any step; the wellhead pressure stayed above the limit" % w)
# what the plant sent back at the last step
last = coupled[-1]
for name in last.ReturnInForce.Keys:
v = last.ReturnInForce[name]
unit, f = ("Mscf/d", DAY / MSCF) if "Gas" in name else ("STB/d", DAY / STB)
print("Return in force at the last step: %s = %.0f %s" % (name, v * f, unit))
OUT = os.environ.get("DWSIM_SAVE_TO")
if OUT:
# the coupling case goes next to the flowsheet without the folders of this computer: choose the reservoir
# model file in the window
case.ReservoirOnly, case.DeckPath, case.OutputDirectory = False, "", ""
case.SaveToFile(os.path.splitext(OUT)[0] + ".dwrsc")
fs.OrthogonalLayout(True)
fs.Save(OUT)
fs.SaveScreenshot(os.path.splitext(OUT)[0] + ".png")
print("saved", OUT)
Exercises
- Run the coupled case with a relaxation of 1. Do the THP limits settle faster, and do the rates swing from step to step?
- Raise the pressure of the inlet separator from 20 to 80 bar (the Sink
SEP). How much higher are the THP limits, does the script now report a well held by its THP limit, and how much oil does the field lose in ten years? - Delete the liquid production limit from the returns. Which well reaches its economic limit first, and how does the cumulative oil compare with the reservoir alone?
- Change
TSTEPto120*30.4375for monthly steps, as in the Case Library case. How long does the coupled run take, and how close is the cumulative oil to 70.29 million STB?
Further Reading¶
- OPM Flow, the reservoir simulator of the Open Porous Media initiative: https://opm-project.org
- A. F. Rasmussen et al. (2021). The Open Porous Media Flow reservoir simulator. Computers & Mathematics with Applications, 81, 159-185
- K. E. Brown and J. P. Brill (eds.). (1984). The Technology of Artificial Lift Methods. PennWell
- DWSIM User Guide: the Reservoir Coupling tool and the Pipe Network
Next Steps¶
You now know how a reservoir model and a surface model exchange the wellhead pressure, the injection and the plant capacity at every report step, why a reservoir run on its own overestimates the oil, and how to find out whether the network or the plant holds the wells back. Open the Oil field from the reservoir to the plant case of the Case Library to see the monthly run, or go back to the PVT and reservoir section.