0% found this document useful (0 votes)
135 views28 pages

Reservoir Modeling Using Matlab The Matalb Reservoir Simulation Toolbox MRST

The document discusses the MATLAB Reservoir Simulation Toolbox (MRST), which provides a platform for reservoir modelling and simulation using MATLAB. MRST has a large international user base including academic and industry users. It features standard data formats, data structures and library routines that allow for rapid prototyping of reservoir models using unstructured grids and differentiation operators. MRST is also used to develop both industry-standard reservoir simulations as well as new modelling methods through its object-oriented framework and state functions.

Uploaded by

The Truth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views28 pages

Reservoir Modeling Using Matlab The Matalb Reservoir Simulation Toolbox MRST

The document discusses the MATLAB Reservoir Simulation Toolbox (MRST), which provides a platform for reservoir modelling and simulation using MATLAB. MRST has a large international user base including academic and industry users. It features standard data formats, data structures and library routines that allow for rapid prototyping of reservoir models using unstructured grids and differentiation operators. MRST is also used to develop both industry-standard reservoir simulations as well as new modelling methods through its object-oriented framework and state functions.

Uploaded by

The Truth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Reservoir Modelling Using MATLAB - The MATLAB

Reservoir Simulation Toolbox (MRST)

Knut-Andreas Lie
SINTEF Digital, Oslo, Norway

MATLAB Energy Conference, 17–18 November 2020


MATLAB Reservoir
Simulation Toolbox (MRST)
Transforming research on
reservoir modelling

Unique prototyping platform:


Standard data formats
Data structures/library routines
Fully unstructured grids
Rapid prototyping:
– Differentiation operators
– Automatic differentiation
– Object-oriented framework
– State functions
Industry-standard simulation
http://www.mrst.no
MATLAB Reservoir
Simulation Toolbox (MRST)
Transforming research on
reservoir modelling

Large international user base:


downloads from the whole world
123 master theses
56 PhD theses
226 journal papers (not by us)
144 proceedings papers
Numbers are from Google Scholar notifications

Used both by academia and industry Google Analytics: access pattern for www.mrst.no
Period: 1 July 2018 to 31 December 2019
Reservoir simulation in MATLAB...? 3 / 22

Different development process:


Use abstractions to express your ideas in a form close to the underlying mathematics
Build your program using an interactive environment:
– try out each operation and build program as you go
Dynamic type checking lets you prototype while you test an existing program:
– run code line by line, inspect and change variables at any point
– step back and rerun parts of code with changed parameters
– add new behavior and data members while executing program

MATLAB is fairly efficient using vectorization, logical indexing, external iterative solvers, etc.
Avoids build process, linking libraries, cross-platform problems
Builtin mathematical abstractions, numerics, data analysis, visualization, debugging/profiling,
Use scripting language as a wrapper when you develop solvers in compiled languages
Community code: software organization 4 / 22

fully implicit

Modular design:

es
flow diagnostics discretizations

ul
od
m
small core with mature and well-tested functionality

n
d -o
Ad
used in many programs or modules grid coarsening multiscale methods

semi-independent modules that extend/override core 2

5
MRST core
6
6
6
cells.faces =
1 10
1
1
2
8
7
1
faces.nodes =
1
1
2
2
1
2
1
3
faces.neighbors =
0
2
3
5
2
3
5
0
9 2 2 3 1 6 2

functionality
2 5 3 4 0 6
4 12 3 3 4 1 1 3
3 3 7 4 7 4 1
3 2 5 2 6 4
8
2 4 8 5 3 1 8
1 5 4 12 6 2 8 5
1 7 4 9 6 6 4 7
upscaling 2
7
10
14 5
5
5 11
3
4
7
7
8
3
4
3
7
0
8
7 co2lab
3 6 9 8 5
8 13 6 6 9 3
Original permeability Upscaled (x−direction) Upscaled (y−direction) 4 6 5 9 6
7 13 10 4
3 11 7 14 10 5 CO2 saturation
5 : : : : at 500 years 12%
16%
1 4 7
56%
12%

3%
Residual (traps)

in-source documentation like in MATLAB


Residual
Residual (plume)
Injected volume: Movable (traps)
2.185e+07 m3 Movable (plume)
50 Original Height of CO2−column x 10
7 Leaked
Upscaled (x)
14
40 2
12

30 10 1.5

8
20 1
6

4
10 0.5
2

0 0 0
−1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 0 50 100 150 200 250 300 350 400 450 500

all modules must have code examples and/or tutorials visualization


input decks

new development: project −→ module ... ...

This simplifies how we distinguish public and in-house or


client-specific functionality
Latest release: 51 modules 5 / 22

Grid generation and coarsening


ECLIPSE input and output
Upscaling / multiscale solvers
Consistent discretizations
Black-oil, EOR, compositional
Fractures: DFM, EDFM, DPDP
Geomechanics, geochemistry, geothermal
Unsaturated media (Richards eq.)
Multisegment wells (general network)
CO2 storage laboratory
Adjoints, optimization, ensembles
Pre/postprocessing/visualization
Flow diagnostics
...
3000 files, 213 000 code lines
User resources (getting help) 6 / 22

website user forum textbook

manpages tutorial codes online tutorials


Fully unstructured grids 7 / 22

A wide variety of grid formats:


Cartesian and rectilinear
Internal gap
Many neighbors Degenerate cells

Non-matching faces
Low permeability
Corner-point
Twisted grid
Thin cells Tetrahedral, prismatic, PEBI
General polyhedral/polytopal
Hybrid, cut-cell, or depogrids
Local refinements . . .

MRST grids are chosen to always be


fully unstructured
−→ can implement algorithms without
knowing the specifics of the grid

Also: coarse grids made as static or


dynamic partitions of fine grid
Incompressible flow solvers 8 / 22

Oldest part of MRST:

∇ · ∇(p + ρ~g ) = 0 Procedural programming


%% Define the model Structs for reservoir state, rock
gravity reset on
G = cartGrid([2 , 2, 30], [1 , 1, 30]) ; parameters, wells, b.c., and source term
G = computeGeometry(G) ;
rock.perm = repmat(0.1∗darcy() , [G.cells.num, 1]) ; Fluid behavior: struct with function
fluid = initSingleFluid() ; pointers
bc = pside([] , G, 'TOP' , 1:G.cartDims(1) , . . .
1:G.cartDims(2) , 100.∗barsa()) ;

%% Assemble and solve the linear system Advantages:


S = computeMimeticIP(G, rock) ;
sol = solveIncompFlow(initResSol(G , 0.0) , . . . hide specific details of geomodel and
initWellSol([] , 0.0) , . . .
G, S, fluid, 'bc' , bc) ; fluid model
%% Plot the face pressures vectorization: efficient/compact code
newplot;
plotFaces(G, 1:G.faces.num, sol.facePressure./barsa) ; unified access to key parameters
set(gca, 'ZDir' , 'reverse ') , title( 'Pressure [bar] ')
view(3) , colorbar
Rapid prototyping: discrete differentiation operators 9 / 22

Idealized models Grid structure in MRST Industry models

c F(c) f C1 C2
1 1 1 3 1
7
8 1 2 2 1 2
8
1 3 3 1 8
3 1 4 4 9 1
7 2 5 5 4 2
6
2 6 6 2 5
9 4 1 2 7 7 2 6
2 2
2 8 8 2 7
.. .. ..
6 2 2 . . .
.. .. ..
1 5 3 1 . . .
5
.. ..
. .
.. ..
. .
3 4
Map: cell → faces Map: face → cells
Rapid prototyping: discrete differentiation operators 9 / 22

Idealized models Grid structure in MRST Industry models

c F(c) f C1 C2
1 1 1 3 1
7
8 1 2 2 1 2
8
1 3 3 1 8
3 1 4 4 9 1
7 2 5 5 4 2
6
2 6 6 2 5
9 4 1 2 7 7 2 6
2 2
2 8 8 2 7
.. .. ..
6 2 2 . . .
.. .. ..
1 5 3 1 . . .
5
.. ..
. .
.. ..
. .
3 4
Map: cell → faces Map: face → cells

For finite volumes, discrete grad operator maps from cell pair C1 (f ), C2 (f ) to face f :

grad(p)[f ] = p[C2 (f )] − p[C1 (f )],

where p[c] is a scalar quantity associated with cell c. Discrete div maps from faces to cells
Both are linear operators and can be represented as sparse matrix multiplications
Close correspondence with mathematics 10 / 22

Continuous Discrete in MATLAB

Incompressible flow: Incompressible flow:

∇ · (K∇p) + q = 0 eq = div ( T .* grad ( p )) + q ;

Compressible flow: Compressible flow:

∂(φρ)
+ ∇ · (ρK∇p) + q = 0 eq = ( pv ( p ).* rho ( p ) - pv ( p0 ).* rho ( p0 ))/ dt ...
∂t
+ div ( avg ( rho ( p )).* T .* grad ( p ))+ q ;
Close correspondence with mathematics 10 / 22

Continuous Discrete in MATLAB

Incompressible flow: Incompressible flow:

∇ · (K∇p) + q = 0 eq = div ( T .* grad ( p )) + q ;

Compressible flow: Compressible flow:

∂(φρ)
+ ∇ · (ρK∇p) + q = 0 eq = ( pv ( p ).* rho ( p ) - pv ( p0 ).* rho ( p0 ))/ dt ...
∂t
+ div ( avg ( rho ( p )).* T .* grad ( p ))+ q ;

Discretization of flow models leads to large systems of nonlinear equations. Can be


linearized and solved with Newton’s method
∂F i
F (u) = 0 ⇒ (u )(ui+1 − ui ) = −F (ui )
∂u
Coding necessary Jacobians is time-consuming and error prone
Automatic differentiation 11 / 22

General idea:
Any code consists of a limited set of arithmetic operations and elementary functions
Introduce an extended pair, hx, 1i, i.e., the value x and its derivative 1
Use chain rule and elementary derivative rules to mechanically accumulate derivatives at
specific values of x
– Elementary: v = sin(x) −→ hvi = hsin x, cos xi
– Arithmetic: v = f g −→ hvi = hf g, f gx + fx gi
– Chain rule: v = exp(f (x)) −→ hvi = hexp(f (x)), exp(f (x))f 0 (x)i
Use operator overloading to avoid messing up code

x = ADI Properties: y = ADI Properties: z = ADI Properties:


[x,y] = initVariablesADI(1,2); val: 1 val: 2 val: 0.4060
jac: {[1] [0]} jac: {[0] [1]} jac: {[-0.8120] [-0.4060]}
z = 3*exp(-x*y)


∂x ∂x ∂y ∂y ∂z ∂z

∂x ∂y ∂x ∂y ∂x x=1,y=2 ∂y x=1,y=2
Example: incompressible single-phase flow 12 / 22

% Make grid % Make grid using external grid generator


G = twister ( cartGrid ([8 8])); pv = [ -1 -1; 0 -.5; 1 -1; 1 1; 0 .5; -1 1; -1 -1];
G = c ompu teG eo metr y ( G ); fh = @ (p , x ) 0.025 + 0.375* sum ( p .^2 ,2);
[p , t ] = distmesh2d ( @dpoly , fh , 0.025 , [ -1 -1; 1 1] , pv , pv );
% Set source terms ( flow SW -> NE ) G = computeGeometry ( pebi ( triangleGrid (p , t )));
q = zeros ( G . cells . num ,1);
q ([1 end ]) = [1 -1]; % Set source terms ( flow SW -> NE )
q = zeros ( G . cells . num ,1);
% Unit insotropic permeability v = sum ( G . cells . centroids ,2);
K = ones ( G . cells . num ,4); K (: ,[2 3]) = 0; [ ~ , i1 ]= min ( v ); [ ~ , i2 ]= max ( v );
q ([ i1 i2 ]) = [1 -1];
Example: incompressible single-phase flow 12 / 22

% Make grid % Make grid using external grid generator


G = twister ( cartGrid ([8 8])); pv = [ -1 -1; 0 -.5; 1 -1; 1 1; 0 .5; -1 1; -1 -1];
G = c ompu teG eo metr y ( G ); fh = @ (p , x ) 0.025 + 0.375* sum ( p .^2 ,2);
[p , t ] = distmesh2d ( @dpoly , fh , 0.025 , [ -1 -1; 1 1] , pv , pv );
% Set source terms ( flow SW -> NE ) G = computeGeometry ( pebi ( triangleGrid (p , t )));
q = zeros ( G . cells . num ,1);
q ([1 end ]) = [1 -1]; % Set source terms ( flow SW -> NE )
q = zeros ( G . cells . num ,1);
% Unit insotropic permeability v = sum ( G . cells . centroids ,2);
K = ones ( G . cells . num ,4); K (: ,[2 3]) = 0; [ ~ , i1 ]= min ( v ); [ ~ , i2 ]= max ( v );
q ([ i1 i2 ]) = [1 -1];

S = setupOperatorsTPFA(G,rock) ; % Define Div, Grad, etc


p = initVariablesADI(zeros(G.cells.num,1)) ; % Initialize p as AD variable
eq = S.Div(S.T .∗ S.Grad(p)) + q; % Residual equation: F = Ap + q
eq(1) = eq(1) + p(1); % Fixate pressure
p =−eq.jac{1}\eq.val; % Solve system A
Example: compressible two-phase flow 13 / 22

% Evaluate equations
[p, sW] = initVariablesADI(p0, sW0)[rW,
; rO, vol] = deal(rhoW(p)
% Primary variables , rhoO(p) , pv(p))) ;
[pIx, sIx] = deal(1:nc, (nc+1):(2∗nc)): ; % Indices of p/S in eq. system
[tol, maxits] = deal(1e−5, 15); water =
% (vol. ∗rW.∗sW
Iteration − vol0.∗rW0.∗sW0)./dt + div(vW) ;
control
t = 0; water(inIx) = water(inIx) − inRate.∗rhoWS;
while t < totTime, :
t = t + dt; eqs = {oil, water}; % concatenate equations
resNorm = 1e99; nit=0; eq = cat(eqs{:}) ; % assemble
[p0, sW0] = deal(value(p) , value(sW))res
; =% eq.val;
Prev. time step not %ADresidual
variable
upd = −(eq.jac{1}
while (resNorm > tol) && (nit<= maxits) % Nonlinear \iteration
res) ; % loop
Newton update
% one Newton iteration
end % Update variables
∂O ∂O
i f nit > maxits, p.val = p.val + upd(pIx) ;
error( 'Newton solves did not converge
sW.val' ) = sW.val + upd(sIx) ; ∂p ∂Sw
end sW.val = max( min(sW.val, 1) , 0);
end resNorm = norm(res) ;
nit = nit + 1; ∂W ∂W
∂p ∂Sw
The AD-OO simulator framework 14 / 22

Initial state Physical model


Schedule

Type color legend


Simulator
Solves simulation schedule comprised Steps Controls
Class
of time steps and drive mechanisms Time step and control numbers Different wells and bc
(wells/bc) {(∆T1 , C1 ), ..., (∆Tn , Cn )}, {(W1 , BC1 ), ..., (Wm , BCm )} Struct

simulateScheduleAD Function(s)

Initial ministep:
State(Ti ), ∆Ti , Controls(Ci ) Nonlinear solver ∆t Time step selector Input
Solves nonlinear problems sub-divided Determines optimal time steps
into one or more mini steps using Contains object
State(Ti + ∆Ti ) Newton’s method SimpleTimeStepSelector,
Adjusted:
∆t̃
IterationCountSelector, Optional output
StateChangeTimeStepSelector, ...

Result handler State Physical model Linear solver


Write to storage Primary var
Stores and retrieves simulation data Primary variables: p, sw , sg , Rs , Rv ... s Defines mathematical model: Resid- δx Solves linearized problem and returns
from memory/disk in a transparent ual equations, Jacobians, limits on increments
and efficient manner. Update variables: updates, convergence definition...
BackslashSolverAD, AGMGSolverAD,
tion p ← p + δp, s ← s + δs, ...
aliza TwoPhaseOilWaterModel, CPRSolverAD, MultiscaleSolverAD, ...
visu
3D ThreePhaseBlackOilModel
[Re
s, J Assemble: Ax = b
Visualization Well solutions ac], in
fo
Visualize well curves, reservoir proper- Well data: qW, qO, qG, bhp, ...
ties, etc Well model Linearized problem
Well equations, control switch, well- Jacobians, residual equations and
plotCellData, plotToolbar, Well curves
bore pressure drop, ... meta-information about their types
plotWellSols, ...
Capabilities as in commercial simulators 15 / 22

Example:
Input deck
Data
Input parser
Class
Reads complete simulation decks:
grid and petrophysics, fluid and rock Struct
properties, region information, well
definitions, operating schedule, con- Function
vergence control, etc
Input

Contains
Oil (stb)
Water (stb)
2.5 Gas (mscf)

Reservoir model State Schedule


2
Description of geology and fluid behavior as Physical variables inside Time steps and controls and
well as discrete averaging and spatial dis- the reservoir settings for wells and boundary 1.5
cretization operators p, sw , so , sg , c, rv , rs conditions
1

Grid Petrophysics Fluids Well state Wells 0.5

Physical variables inside


0.8

0
0.6
the wellbore 500 1000 1500 2000 2500 3000
qsw , qso , qsg , qsp , pbh
0.4

0.2
Time (days)
0
0 0.2 0.4 0.6 0.8 1

Field production compared with


OPM Flow for the Norne field
State functions: modularity and computational cache 16 / 22

It would be convenient to have:


Dependency management: keep track of dependency
graph, ensure all input quantities have been evaluated
before evaluating a function
Generic interfaces: avoid defining functional
dependencies explicitly, e.g., G(S), and G(p, S).
Lazy evaluation with caching
Enable spatial dependence in parameters while
preserving vectorization potential
Implementation independent of the choice of primary
variables
State functions: modularity and computational cache 16 / 22

State function: any function that is


It would be convenient to have: uniquely determined by the contents of
Dependency management: keep track of dependency the state struct alone
graph, ensure all input quantities have been evaluated Implemented as class objects, gathered
before evaluating a function in functional groups
Generic interfaces: avoid defining functional
G(x, y, a, b) = xy + ab
dependencies explicitly, e.g., G(S), and G(p, S).
state
Lazy evaluation with caching
a b x y
Enable spatial dependence in parameters while
preserving vectorization potential group
Implementation independent of the choice of primary A B X Y
variables
AB XY

G
Simulator: differentiable graph 17 / 22

Wells
Idea: apply this concept to
Qi,α Qi ρw
α flow property evaluation
W →c qα
WI
PVT
µα pc − pbh − g∆zρmix
PVT calculations
Flux
accumulation, flux, and source terms
state pα Φ wip
∇pα
bhp spatial/temporal discretization
Θα λfα
bα ρα Rsmax
rs gρα ∆z vα
Simulator −→ differentiable graph
Accumulation Tf Tf Θα
pressure
Mi,α Mi Vi,α Vi

s Θα ≤ 0 λfi,α Further granularity


kα λα ρα xi,α
Immiscible components
pc λi,α
Black-oil type components
Compositional components
Example: State-function diagram for a simple black-oil model.
Each entity is a state function that is easy to replace. Concentration components
Combined at runtime to form compact
models with only necessary unknowns
What about computational performance? 18 / 22

Total time of a program consists of several parts:


programming + debugging
+ documenting + testing + executing

MRST is designed to prioritize the first four over the last

Does this mean that MRST is slow and not scalable?


What about computational performance? 18 / 22

Potential concerns:
Total time of a program consists of several parts:
MATLAB is interpreted
programming + debugging cure: JIT, vectorization, logical indexing,
+ documenting + testing + executing pre-allocation, highly-efficient libraries
MRST is designed to prioritize the first four over the last Redundant computations
cure: state functions = dependency
Does this mean that MRST is slow and not scalable? graph + computational cache
Computational overhead
No, I would say its is surprisingly efficient cure: new auto diff backends
Scalability/performance
cure: external high-end iterative solvers
New backends for automatic differentiation 19 / 22

single-phase
2 3ph, immiscible
10
3ph, blackoil
6c, compositional
Assembly time [s]

0.5 s / million cells


50 s / million cells

100

10-2

1 104 1 105 1 106 2 106


Number of cells
overhead dominates

New AD backends: storage optimized wrt access pattern, MEX-accelerated operations


Efficient linear solvers 20 / 22

Interface to external linear algebra packages implemented as classes in AD-OO framework

Example: compressible three-phase, black-oil problem


Solver Req. 8,000 cells 125,000 cells 421,875 cells 1,000,000 cells
LU – 2.49 s 576.58 s – –

CPR – 0.90 s 137.30 s – –
CPR∗ AGMG 0.18 s 3.60 s 13.78 s 43.39 s
CPR∗ AMGCL 0.21 s 3.44 s 16.20 s 51.35 s
CPR AMGCL 0.07 s 0.43 s 3.38 s 10.20 s
CPR AMGCL† 0.05 s 0.86 s 1.97 s 5.60 s

CPR AMGCL 0.05 s 0.38 s 1.33 s 3.82 s
∗ – in MATLAB, † – block AMGCL (block ILU + AMG/CPR), ‡ – block AMGCL with tweaks

Performance is approaching commercial and compiled academic codes


New book: Advanced modelling with MRST 21 / 22

Berge et al.: Constrained Voronoi grids Al Kobaisi & Zhang: nonlinear FVM Lie & Møyner: multiscale methods

Wong et al.: embedded discrete fractures Olorode et al.; fractured unconventionals March et al.: unified framework, fractures

Klemetsdal & Lie: discontinuous Galerkin


Møyner: state functions, AD backends
Sun et al.: chemical EOR
Møyner: compositional
Varela et al.: unsaturated poroelasticity Collignon et al.: geothermal systems Andersen: coupled flow & geomechanics
Acknowledgements 22 / 22

Thanks to all my co-developers at SINTEF (Olav Møyner, Funding:


in particular), our master and PhD students, and our Research Council of Norway
national and international collaborators. SINTEF
Equinor: gold open access for the
Thanks also to all MRST users who have asked interesting
MRST textbook
questions that have helped us shape the software
Chevron, Ecopetrol, Eni, Equinor,
ExxonMobil, Shell, SLB, Total,
Wintershall DEA, . . .

You might also like